Nested Conditional Properties for Local file references not working in python-jsonschema - jsonschema

My RefResolver and Validator script is
from jsonschema import RefResolver
from jsonschema.validators import validator_for
from tests.automation.io.helpers.loader import load_schema
base = load_schema('base.schema.json') # {"$schema": "http://json-schema.org/draft-07/schema#" }
definitions = load_schema('defination.schema.json') # https://jsonschema.dev/s/FZDbO
schema = load_schema('update.schema.json') # https://jsonschema.dev/s/lvLFa
schema_store = {
base.get('$id','base.schema.json') : base,
definitions.get('$id','defination.schema.json') : definitions,
schema.get('$id','update.schema.json') : schema,
}
resolver = RefResolver.from_schema(base, store=schema_store)
Validator = validator_for(base)
validator = Validator(schema, resolver=resolver)
data = {
"common_data": {
"os_ip": "127.0.0.1",
"os_user": "root",
"os_pwd": "hello",
"remote_os": "Windows"
},
"dup_file": "ad7a.exe"
}
validator.validate(data)
My JSON Schema looks like
base.schema.json => {"$schema": "http://json-schema.org/draft-07/schema#" }
defination.schema.json => https://jsonschema.dev/s/FZDbO
update.schema.json => https://jsonschema.dev/s/lvLFa
Getting error : jsonschema.exceptions.ValidationError: 'ad7a.exe' does not match '^(.*.)(bin)$'
Same thing I have tested https://json-schema.hyperjump.io/ it working perfectly fine , suspecting some issue with python-jsonschema only.

Related

Ktor parsing of arrays with nested objects config

I am trying to use the following configuration in Ktor:
source {
quotes {
inputTopicBaseName = "quotes"
providers = [
{
provider = "BHS"
windows = [
{
grace = "PT1M"
size = "PT1M"
}
]
},
{
provider = "LSX"
windows = [
{
grace = "PT1M"
size = "PT1M"
}
]
}
]
}
type = QUOTES
}
When I invoke environment.config.config("source.quotes").configList("providers"), it fails with the following exception
Exception in thread "main" io.ktor.server.config.ApplicationConfigurationException: Property source.quotes.providers.size not found.
at io.ktor.server.config.MapApplicationConfig.configList(MapApplicationConfig.kt:57)
at io.ktor.server.config.MergedApplicationConfig.configList(MergedApplicationConfig.kt:37)
Why is this not working?
This is a bug that will be fixed in Ktor 2.2.0.

Set programmatically jsonValidation for dynamic mapping

I am creating a new vscode extension, and I need to extend the standard usage of the jsonValidation system already present in vscode.
Note : I am talking about the system defined in package.json :
"contributes" : {
"languages": [
{
"id" : "yml",
"filenamePatterns": ["module.service"]
},
{
"id" : "json",
"filenamePatterns": ["module.*"]
}
],
"jsonValidation": [
{
"fileMatch": "module.test",
"url": "./resources/test.schema"
}
]
}
Now, I need to create a dynamic mapping, where the json fields filematch/url are defined from some internal rules (like version and other internal stuff). The standard usage is static : one fileMatch -> one schema.
I want for example to read the version from the json file to validate, and set the schema after that :
{
"version" : "1.1"
}
validation schema must be test-schema.1.1 instead of test-schema.1.0
note : The question is only about the modification of the configuration provided by package.json from the extensions.ts
Thanks for the support
** EDIT since the previous solution was not working in all cases
There is one solution to modify the package.json at the activating of the function.
export function activate(context: vscode.ExtensionContext) {
const myPlugin = vscode.extensions.getExtension("your.plugin.id");
if (!myPlugin)
{
throw new Error("Composer plugin is not found...")
}
// Get the current workspace path to found the schema later.
const folderPath = vscode.workspace.workspaceFolders;
if (!folderPath)
{
return;
}
const baseUri : vscode.Uri = folderPath[0].uri;
let packageJSON = myPlugin.packageJSON;
if (packageJSON && packageJSON.contributes && packageJSON.contributes.jsonValidation)
{
let jsonValidation = packageJSON.contributes.jsonValidation;
const schemaUri : vscode.Uri = vscode.Uri.joinPath(baseUri, "/schema/value-0.3.0.json-schema");
const schema = new JsonSchemaMatch("value.ospp", schemaUri)
jsonValidation.push(schema);
}
}
And the json schema class
class JsonSchemaMatch
{
fileMatch: string;
url : string;
constructor(fileMatch : string, url: vscode.Uri)
{
this.fileMatch = fileMatch;
this.url = url.path;
}
}
Another important information is the loading of the element of contributes is not reread after modification, for example
class Language
{
id: string;
filenamePatterns : string[];
constructor(id : string, filenamePatterns: string[])
{
this.id = id;
this.filenamePatterns = filenamePatterns;
}
}
if (packageJSON && packageJSON.contributes && packageJSON.contributes.languages)
{
let languages : Language[] = packageJSON.contributes.languages;
for (let language of languages) {
if (language.id == "json") {
language.filenamePatterns.push("test.my-json-type")
}
}
}
This change has no effect, since the loading of file association is already done (I have not dig for the reason, but I think this is the case)
In this case, creating a settings.json in the workspace directory can do the job:
settings.json
{
"files.associations": {
"target.snmp": "json",
"stack.cfg": "json"
}
}
Be aware that the settings.json can be created by the user with legitimate reason, so don't override it, just fill it.

Testing elm lib with local Native directory

How do we organize our test directory when developing some libraries that uses Native js code?
I tried to work this out, but I'm blocked here, with this error at runtime when running test/test.sh:
Elm.Native.Mylib = {};
^
TypeError: Cannot read property 'Native' of undefined
git repository
My directories are structured this way:
Mylib:
- src :
- Mylib.elm
- Native :
- MyLib.js
- tests :
- Test.elm
- Test.sh
- elm-package.json
the tests/elm-package.json contains :
{
"version": "1.0.0",
"summary": "helpful summary of your project, less than 80 characters",
"repository": "https://github.com/user/project.git",
"license": "BSD3",
"source-directories": [
"."
,"../src"
],
"exposed-modules": [],
"native-modules": true,
"dependencies": {
"elm-community/elm-test": "1.1.0 <= v < 2.0.0",
"elm-lang/core": "4.0.1 <= v < 5.0.0"
},
"elm-version": "0.17.0 <= v < 0.18.0"
}
the tests/Test.elm is :
module Main exposing (..)
import Basics exposing (..)
import ElmTest exposing (..)
import Mylib exposing (..)
tests : Test
tests =
suite "elm-Mylib Library Tests"
[ ]
main =
runSuite tests
The tests/test.sh is
#!/bin/sh
elm-package install -y
elm-make --yes --output test.js Test.elm
node test.js
The src/Mylib.elm is
module Mylib exposing (..)
import Native.Mylib exposing (..)
import Task exposing (Task)
import Time exposing (Time)
print : a -> Task x ()
print value =
Native.Mylib.log (toString value)
getCurrentTime : Task x Time
getCurrentTime =
Native.Mylib.getCurrentTime
The src/Native/Mylib.js is
Elm.Native.Mylib = {};
Elm.Native.Mylib.make = function(localRuntime) {
localRuntime.Native = localRuntime.Native || {};
localRuntime.Native.Mylib = localRuntime.Native.Mylib || {};
if (localRuntime.Native.Mylib.values)
{
return localRuntime.Native.Mylib.values;
}
var Task = Elm.Native.Task.make(localRuntime);
var Utils = Elm.Native.Utils.make(localRuntime);
function log(string)
{
return Task.asyncFunction(function(callback) {
console.log(string);
return callback(Task.succeed(Utils.Tuple0));
});
}
var getCurrentTime = Task.asyncFunction(function(callback) {
return callback(Task.succeed(Date.now()));
});
return localRuntime.Native.Mylib.values = {
log: log,
getCurrentTime: getCurrentTime
};
};
Try this:
var _user$project$Native_MyLib = function() {
return {
exported: function(arg) { return "One" },
exported2: F2(function(arg) { return "Two" }),
exported3: F3(function(arg) { return "Three" }),
}
}();
It works for grater than Elm 0.17.
Buy you should also use full qualified import:
import Natve.MyLib
exported : String -> String
Native.MyLib.exported
exported2 : String -> String -> String
Native.MyLib.exported2
exported3 : String -> String -> String -> String
Native.MyLib.exported3
User and project values are from your/local elm-package.json:
"repository": "https://github.com/user/project.git",

How to convert `json query` to `sql query`?

I have an AngularJS App designed to build queries in JSON format, those queries are built with many tables, fields, and operators like "join", "inner", "where","and","or","like", etc.
AngularJS App is sending this JSON queries to my Django-Restframework backend, so I need to translate that JSON query into SQL query, to be able to run Raw SQL with previous validations of what tables/models are allowed for select.
I don't need a full JSON query to SQL query translation, I just want to translate selects with support for clauses like "where","and", "or", "group_by".
For better understanding of my question I put the following snippets:
{
"selectedFields": {
"orders": {
"id": true,
"orderdate": true},
"customers": {
"customername": true,
"customerlastname": true}
},
"from": ["orders"],
"inner_join":
{
"customers": {
"on_eq": [
{
"orders": {
"customderID": true
},
},
{
"customers": {
"customerID": ture
}
}
]
}
}
}
SELECT
Orders.OrderID,
Customers.CustomerName,
Customers.CustomerLastName,
Orders.OrderDate
FROM Orders
INNER JOIN Customers
ON Orders.CustomerID=Customers.CustomerID;
I took the example from: http://www.w3schools.com/sql/sql_join.asp
Please note that I am not trying to serialize any SQL query output to JSON.
I found a NodeJS package (https://www.npmjs.com/package/json-sql) who converts JSON queries to SQL queries, so I made a NodeJS script and then I create a class in Python to call NodeJS script.
With this approach I just need to send all AngularJS queries following this syntax (https://github.com/2do2go/json-sql/tree/master/docs#join)
NodeJS script.
// Use:
//$ nodejs reporter/services.js '{"type":"select","fields":["a","b"],"table":"table"}'
var jsonSql = require('json-sql')();
var json_query = JSON.parse(process.argv[2]);
var sql = jsonSql.build(json_query);
console.log(sql.query);
DRF class:
from unipath import Path
import json
from django.conf import settings
from Naked.toolshed.shell import muterun_js
full_path = str(Path(settings.BASE_DIR, "reporter/services.js"))
class JSONToSQL:
def __init__(self, json_):
self.json = json_
self.sql = None
self.dic = json.loads(json_)
self.to_sql()
def to_sql(self):
response = muterun_js('%s \'%s\'' % (full_path, self.json))
if response.exitcode == 0:
self.sql = str(response.stdout).replace("\n","")
You could write some custom JS to parse the object like this:
var selectedfields ='';
var fields = Object.keys(obj.selectedFields);
for (i=0;i<fields.length; i++) {
var subfields = Object.keys(obj.selectedFields[fields[i]]);
for (j=0;j<subfields.length; j++) {
selectedfields = selectedfields + fields[i]+'.'+subfields[j]+' ';
}
}
var from="";
for (i=0;i<obj.from.length; i++) {
if (from=="") {
from = obj.from[i]
} else {
from = from + ',' +obj.from[i]
}
}
var output = 'SELECT '+selectedfields+ ' FROM '+from;
document.getElementById('output').innerHTML=output;
or in angular you would use $scope.output = ... from within a controller perhaps.
jsfiddle here: https://jsfiddle.net/jsheridan390/fpbp6cz0/1/

Titanium Alloy - how to persist model singleton?

runs in iOs & Android
coffeeScript
I have a model such as:
exports.definition =
config:
columns:
cookie: "string"
defaults:
cookie: ""
adapter:
# is this valid?
type: "sql"
collection_name: "userInfo"
extendModel: (Model) ->
_.extend Model::,
isSignedIn:->
this.get('cookie').length > 0
Model
And a index.xml:
<Alloy>
<Model id="userInfo" src="userInfo" instance="true"/>
So, this userInfo properties change during the lifecycle of the app, the user logs in, and I want to keep that cookie being persisted as well as auto-loaded on app init.
How do I do that in this framework?
UPDATE another Q&A
For reference here: http://developer.appcelerator.com/question/147601/alloy---persist-and-load-a-singleton-model#255723
They don't explain it well in the appcelerator docs, but if you want to store and retreive properties using build-in alloy properties sync adapter you have to specify a unique "id" when using models. You did it already in the xml markup: <Model id="userInfo" but that will work for that view file only. If you want to access/update this property in the controller you do this:
var UserInfo = Alloy.createModel("userInfo", {id: "userInfo"});
UserInfo.fetch();
UserInfo.set("cookie", "new value");
UserInfo.save();
If you want to keep the reference to this property thruout the code, I believe, you just attach it to the global namespace in the alloy.js:
var UserInfo = Alloy.createModel("userInfo", {id: "userInfo"});
UserInfo.fetch();
Alloy.Globals.UserInfo = UserInfo;
In the controllers you do:
var UserInfo = Alloy.Globals.UserInfo;
Put your model userInfo.js into app/model, it will probably look like this:
exports.definition = {
config : {
"columns" : {
"cookie" : "string"
},
"defaults" : { "cookie" : "" }
"adapter" : {
"type" : "sql",
"collection_name" : "userInfo"
}
},
extendModel : function(Model) {
_.extend(Model.prototype, {
isSignedIn : function() {
this.get('cookie').length > 0
}
});
return Model;
},
extendCollection : function(Collection) {
_.extend(Collection.prototype, {
});
return Collection;
}
}
From here it depends on what you want to do, but you can easily fetch the model from the collection userInfo, just put this: <Collection src="userInfo"/> in your xml file.
As a side note, I usually just use the Titanium.App.Properties stuff to store user information. Properties are used for storing application-related data in property/value pairs that persist beyond application sessions and device power cycles. For example:
// Returns the object if it exists, or null if it does not
var lastLoginUserInfo = Ti.App.Properties.getObject('userInfo', null);
if(lastLoginUserInfo === null) {
var userInfo = {cookie : "Whatever the cookie is", id : "123456789"};
Ti.App.Properties.setObject('userInfo', userInfo);
} else {
// Show the cookie value of user info
alert(lastLoginUserInfo.cookie);
}