问:
How does Spark CrossValidator determine how to apply the grid parameters
The following snippet from the Spark docs for ML Tuning  https://spark.apache.org/docs/latest/ml-tuning.html apparently sets up the numFeatures for a Hashing TermFrequency  and regParam (regularization) for a LogisticRegression model:

The HashingTF and LogisticRegression:

```<code>val hashingTF = new HashingTF()
  .setInputCol(tokenizer.getOutputCol)
  .setOutputCol("features")
val lr = new LogisticRegression()
  .setMaxIter(10)
</code>```

The ParamGridBuilder for the CrossValidator :

```<code>// We use a ParamGridBuilder to construct a grid of parameters to search over.
// With 3 values for hashingTF.numFeatures and 2 values for lr.regParam,
// this grid will have 3 x 2 = 6 parameter settings for CrossValidator to choose from.
val paramGrid = new ParamGridBuilder()
  .addGrid(hashingTF.numFeatures, Array(10, 100, 1000))
  .addGrid(lr.regParam, Array(0.1, 0.01))
  .build()
</code>```

How does the CrossValidator "know" how to apply the grid values to the respective entities? I was looking to see if it were by reflection but that were not clear .

The methods that are likely being set by the `CrossValidator are:

HashingTF:

```<code>  /** @group setParam */
  @Since("1.2.0")
  def setNumFeatures(value: Int): this.type = set(numFeatures, value)
</code>```

LogisticRegression:

```<code>class LogisticRegressionModel @Since("1.3.0") (
 ..
 @Since("1.3.0") val numFeatures: Int,
</code>```

And here is the invocation on the CrossValidator:

```<code>val cv = new CrossValidator()
  .setEstimator(pipeline)
  .setEvaluator(new BinaryClassificationEvaluator)
  .setEstimatorParamMaps(paramGrid)
  .setNumFolds(2)  // Use 3+ in practice
</code>```

I was not able to determine how the setEstimatorParamMaps results in properly setting the HashingTF and LogisticRegression values. (Note this does work!)

The reason for this question is I want to add a new Evaluator and am uncertain how to match that up with the CrossValidator capabilities.

A specific example: for LDAModel: we have tuning parameters k, vocabSize, and docConcentration : how should the ParamGrid be set up for those?

答:
A specific example: for LDAModel: we have tuning parameters k, vocabSize, and docConcentration : how should the ParamGrid be set up for those?

addGrid takes a Param and Array of compatible values. Typically it is set on Estimator (LDA) not Transformer (LDAModel`).

To set k, docConcentration just follow the types:

```<code>val lda = new LDA()

val paramGrid = new ParamGridBuilder()
 .addGrid(lda.k, Array(3, 5, 7))
 .addGrid(lda.docConcentration, Array(Array(0.1, 0.4, 0.5)))
 .build()
</code>```

we have tuning parameters (...) vocabSize

Vocab size is defined by the input vector. It is cannot be tuned.

How does the CrossValidator "know" how to apply the grid values to the respective entities?

Models provide fit method which takes dataset and ParamMap. For example LDA:

```<code>def fit(dataset: Dataset[_], paramMap: ParamMap): LDAModel
</code>```

Fits a single model to the input data with provided parameter map.

This variant is used by CrossValidator.

Body:
The following snippet from the Spark docs for ML Tuning  https://spark.apache.org/docs/latest/ml-tuning.html apparently sets up the numFeatures for a Hashing TermFrequency  and regParam (regularization) for a LogisticRegression model:

The HashingTF and LogisticRegression:

val hashingTF = new HashingTF()
  .setInputCol(tokenizer.getOutputCol)
  .setOutputCol("features")
val lr = new LogisticRegression()
  .setMaxIter(10)

The ParamGridBuilder for the CrossValidator :

// We use a ParamGridBuilder to construct a grid of parameters to search over.
// With 3 values for hashingTF.numFeatures and 2 values for lr.regParam,
// this grid will have 3 x 2 = 6 parameter settings for CrossValidator to choose from.
val paramGrid = new ParamGridBuilder()
  .addGrid(hashingTF.numFeatures, Array(10, 100, 1000))
  .addGrid(lr.regParam, Array(0.1, 0.01))
  .build()

How does the CrossValidator "know" how to apply the grid values to the respective entities? I was looking to see if it were by reflection but that were not clear .

The methods that are likely being set by the `CrossValidator are:

HashingTF:

  /** @group setParam */
  @Since("1.2.0")
  def setNumFeatures(value: Int): this.type = set(numFeatures, value)

LogisticRegression:

class LogisticRegressionModel @Since("1.3.0") (
 ..
 @Since("1.3.0") val numFeatures: Int,

And here is the invocation on the CrossValidator:

val cv = new CrossValidator()
  .setEstimator(pipeline)
  .setEvaluator(new BinaryClassificationEvaluator)
  .setEstimatorParamMaps(paramGrid)
  .setNumFolds(2)  // Use 3+ in practice

I was not able to determine how the setEstimatorParamMaps results in properly setting the HashingTF and LogisticRegression values. (Note this does work!)

The reason for this question is I want to add a new Evaluator and am uncertain how to match that up with the CrossValidator capabilities.

A specific example: for LDAModel: we have tuning parameters k, vocabSize, and docConcentration : how should the ParamGrid be set up for those?

Body:
A specific example: for LDAModel: we have tuning parameters k, vocabSize, and docConcentration : how should the ParamGrid be set up for those?

addGrid takes a Param and Array of compatible values. Typically it is set on Estimator (LDA) not Transformer (LDAModel`).

To set k, docConcentration just follow the types:

val lda = new LDA()

val paramGrid = new ParamGridBuilder()
 .addGrid(lda.k, Array(3, 5, 7))
 .addGrid(lda.docConcentration, Array(Array(0.1, 0.4, 0.5)))
 .build()

we have tuning parameters (...) vocabSize

Vocab size is defined by the input vector. It is cannot be tuned.

How does the CrossValidator "know" how to apply the grid values to the respective entities?

Models provide fit method which takes dataset and ParamMap. For example LDA:

def fit(dataset: Dataset[_], paramMap: ParamMap): LDAModel

Fits a single model to the input data with provided parameter map.

This variant is used by CrossValidator.


来源: stackexchange

问:
venv doesn't create activate script python3
When trying to create a virtulenv using venv with python 3 on ubuntu it isn’t creating an activate script. It conitunally exits with an error 1.

Following docs and other posts on SO such as https://stackoverflow.com/a/19848770

I have tried creating it 2 different ways.

```<code>sayth@sayth-TravelMate-5740G:~/scripts$ python3 -m venv test4
Error: Command '['/home/sayth/scripts/test4/bin/python3', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 1
sayth@sayth-TravelMate-5740G:~/scripts$ source test4/bin/activate
bash: test4/bin/activate: No such file or directory
sayth@sayth-TravelMate-5740G:~/scripts$ ls test4/bin/
python  python3
</code>```

or

```<code>sayth@sayth-TravelMate-5740G:~/scripts$ pyvenv-3.4 test5
Error: Command '['/home/sayth/scripts/test5/bin/python3.4', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 1
sayth@sayth-TravelMate-5740G:~/scripts$ ls test5/bin/
python  python3  python3.4
</code>```

How can I get it to fully create a venv?

If I do it as below with stil no success unsure what the issue is?

```<code>sayth@sayth-TravelMate-5740G:~/scripts$ python3 -Im venv panda3
Error: Command '['/home/sayth/scripts/panda3/bin/python3', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 1
sayth@sayth-TravelMate-5740G:~/scripts$ python3 -m venv panda4
Error: Command '['/home/sayth/scripts/panda4/bin/python3', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 1
</code>```

答:
The command:

```<code>python3 -m virtualenv env
</code>```

works for me, whereas:

```<code>python3 -m venv env
</code>```

does not.

ContentLicense: CC BY-SA 3.0

Body:
When trying to create a virtulenv using venv with python 3 on ubuntu it isn’t creating an activate script. It conitunally exits with an error 1.

Following docs and other posts on SO such as https://stackoverflow.com/a/19848770

I have tried creating it 2 different ways.

sayth@sayth-TravelMate-5740G:~/scripts$ python3 -m venv test4
Error: Command '['/home/sayth/scripts/test4/bin/python3', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 1
sayth@sayth-TravelMate-5740G:~/scripts$ source test4/bin/activate
bash: test4/bin/activate: No such file or directory
sayth@sayth-TravelMate-5740G:~/scripts$ ls test4/bin/
python  python3

or

sayth@sayth-TravelMate-5740G:~/scripts$ pyvenv-3.4 test5
Error: Command '['/home/sayth/scripts/test5/bin/python3.4', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 1
sayth@sayth-TravelMate-5740G:~/scripts$ ls test5/bin/
python  python3  python3.4

How can I get it to fully create a venv?

If I do it as below with stil no success unsure what the issue is?

sayth@sayth-TravelMate-5740G:~/scripts$ python3 -Im venv panda3
Error: Command '['/home/sayth/scripts/panda3/bin/python3', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 1
sayth@sayth-TravelMate-5740G:~/scripts$ python3 -m venv panda4
Error: Command '['/home/sayth/scripts/panda4/bin/python3', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 1

Body:
The command:

python3 -m virtualenv env

works for me, whereas:

python3 -m venv env

does not.


问:
Connect to postgres from google script
Mysql protocol and support in jdbc.https://developers.google.com/apps-script/guides/jdbc How can I use postgres?</p>

答:
Nope. The documentation only lists these four:

MySQL

MSSQL

Oracle Database

Cloud SQL

However, you can leverage google cloud functions to create a custom service that can connect to a postgres database. You can then call that service using Google Apps Script.

Title: Connect to postgres from google script


问:
How do I solve "Server terminated early with status 127" when running node.js on Linux?
I’m using node 5.10.0 on this version of Linux

```<code>[davea@mydevbox mydir]$ uname -a
Linux mydevbox.mydomain.com 7.3.8-25.26.amzn1.x86_64 #1 SMP Wed Mar 16 17:15:34 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux
</code>```

I’m getting the below error when running my script (“Server terminated early with status 127”).  I have verified that I can reach the URL in question using “wget”, so I can’t tell what else I need to make this thing work …

```<code>[davea@mydevbox mydir]$ node myscript.js
Validation Complete
/home/davea/node_modules/selenium-webdriver/lib/promise.js:654
    throw error;
    ^

Error: Server terminated early with status 127
    at Error (native)
    at /home/davea/node_modules/selenium-webdriver/remote/index.js:242:20
    at ManagedPromise.invokeCallback_ (/home/davea/node_modules/selenium-webdriver/lib/promise.js:1343:14)
    at TaskQueue.execute_ (/home/davea/node_modules/selenium-webdriver/lib/promise.js:2868:14)
    at TaskQueue.executeNext_ (/home/davea/node_modules/selenium-webdriver/lib/promise.js:2851:21)
    at /home/davea/node_modules/selenium-webdriver/lib/promise.js:2730:27
    at /home/davea/node_modules/selenium-webdriver/lib/promise.js:639:7
    at process._tickCallback (internal/process/next_tick.js:103:7)
From: Task: WebDriver.createSession()
    at acquireSession (/home/davea/node_modules/selenium-webdriver/lib/webdriver.js:107:22)
    at Function.createSession (/home/davea/node_modules/selenium-webdriver/lib/webdriver.js:337:12)
    at Driver (/home/davea/node_modules/selenium-webdriver/chrome.js:778:38)
    at Builder.build (/home/davea/node_modules/selenium-webdriver/builder.js:464:16)
    at Object.<anonymous> (/home/davea/mydir/js/Optimus.js:14:4)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Module.require (module.js:367:17)
From: Task: WebDriver.navigate().to(http://localhost:8081/myproject)
    at Driver.schedule (/home/davea/node_modules/selenium-webdriver/lib/webdriver.js:386:17)
    at Navigation.to (/home/davea/node_modules/selenium-webdriver/lib/webdriver.js:1029:25)
    at Driver.get (/home/davea/node_modules/selenium-webdriver/lib/webdriver.js:797:28)
    at Object.exports.Login.Page (/home/davea/mydir/js/Optimus.js:505:16)
    at Object.exports.smokeTest (/home/davea/mydir/js/Optimus.js:2442:19)
    at Object.<anonymous> (/home/davea/mydir/SkyNet.js:13:6)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
</code>```

答:
As suggested by other answers, the error message means you have unmet dependencies.

In my case of selenium e2e test, fixes are:

apt-get install default-jre as mentioned by @Johannes

apt-get -f install for a fix install

apt-get install chromium-browser Make sure to install the correct version of chrome related to your chromedriver, e.g. chrome 60-62 for chromedriver 2.33

Config webdriver to start chrome in 'headless' mode, as to avoid other unnecessary dependencies. In node it looks like:

    const options = new chromeDriver.Options();
      options.addArguments(
        'headless',
        'disable-gpu',
      );
      new webdriver.Builder()
        .forBrowser('chrome')
        .setChromeOptions(options)
        .build();

Body:
I’m using node 5.10.0 on this version of Linux

[davea@mydevbox mydir]$ uname -a
Linux mydevbox.mydomain.com 7.3.8-25.26.amzn1.x86_64 #1 SMP Wed Mar 16 17:15:34 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

I’m getting the below error when running my script (“Server terminated early with status 127”).  I have verified that I can reach the URL in question using “wget”, so I can’t tell what else I need to make this thing work …

[davea@mydevbox mydir]$ node myscript.js
Validation Complete
/home/davea/node_modules/selenium-webdriver/lib/promise.js:654
    throw error;
    ^

Error: Server terminated early with status 127
    at Error (native)
    at /home/davea/node_modules/selenium-webdriver/remote/index.js:242:20
    at ManagedPromise.invokeCallback_ (/home/davea/node_modules/selenium-webdriver/lib/promise.js:1343:14)
    at TaskQueue.execute_ (/home/davea/node_modules/selenium-webdriver/lib/promise.js:2868:14)
    at TaskQueue.executeNext_ (/home/davea/node_modules/selenium-webdriver/lib/promise.js:2851:21)
    at /home/davea/node_modules/selenium-webdriver/lib/promise.js:2730:27
    at /home/davea/node_modules/selenium-webdriver/lib/promise.js:639:7
    at process._tickCallback (internal/process/next_tick.js:103:7)
From: Task: WebDriver.createSession()
    at acquireSession (/home/davea/node_modules/selenium-webdriver/lib/webdriver.js:107:22)
    at Function.createSession (/home/davea/node_modules/selenium-webdriver/lib/webdriver.js:337:12)
    at Driver (/home/davea/node_modules/selenium-webdriver/chrome.js:778:38)
    at Builder.build (/home/davea/node_modules/selenium-webdriver/builder.js:464:16)
    at Object.<anonymous> (/home/davea/mydir/js/Optimus.js:14:4)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Module.require (module.js:367:17)
From: Task: WebDriver.navigate().to(http://localhost:8081/myproject)
    at Driver.schedule (/home/davea/node_modules/selenium-webdriver/lib/webdriver.js:386:17)
    at Navigation.to (/home/davea/node_modules/selenium-webdriver/lib/webdriver.js:1029:25)
    at Driver.get (/home/davea/node_modules/selenium-webdriver/lib/webdriver.js:797:28)
    at Object.exports.Login.Page (/home/davea/mydir/js/Optimus.js:505:16)
    at Object.exports.smokeTest (/home/davea/mydir/js/Optimus.js:2442:19)
    at Object.<anonymous> (/home/davea/mydir/SkyNet.js:13:6)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)


问:
Python - Remove quotes and double minus using replace
Given a string such as

```<code>--"I like salami. "-I want to walk to the shops"
</code>```

How can I return the string such as

```<code>I like salami. I want to walk to the shops.
</code>```

I can alter each individually but when I use '-"' it fails.

Quotes

```<code>b = '"'

for char in b:
    solution = MyString.replace(char,"")

#output --I like salami. -I want to walk to the shops
</code>```

Minus

```<code>b = '-'

for char in b:
    solution = MyString.replace(char,"")

#output "I like salami. "I want to walk to the shops"
</code>```

Together

```<code>MyString = '--"I like salami. "-I want to walk to the shops"'

b = '"-'

for char in b:
    print(MyString.replace(char,""))

#output "I like salami. "I want to walk to the shops"
</code>```

答:
Just do it like this:

```<code>MyString = '--"I like salami. "-I want to walk to the shops"'
MyString = MyString.replace('"',"")
MyString = MyString.replace('-',"")
print MyString
#output: I like salami. I want to walk to the shops
</code>```

Or you can use Regular expression and do it like this:

```<code>import re
MyString = '--"I like salami. "-I want to walk to the shops"'
MyString = re.sub('["-]', '', MyString)
print MyString
#output: I like salami. I want to walk to the shops
</code>```

Remember to install re if it doesn't exist already. Tell me if there are any problems.

Body:
Given a string such as

--"I like salami. "-I want to walk to the shops"

How can I return the string such as

I like salami. I want to walk to the shops.

I can alter each individually but when I use '-"' it fails.

Quotes

b = '"'

for char in b:
    solution = MyString.replace(char,"")

#output --I like salami. -I want to walk to the shops

Minus

b = '-'

for char in b:
    solution = MyString.replace(char,"")

#output "I like salami. "I want to walk to the shops"

Together

MyString = '--"I like salami. "-I want to walk to the shops"'

b = '"-'

for char in b:
    print(MyString.replace(char,""))

#output "I like salami. "I want to walk to the shops"

Body:
Just do it like this:

MyString = '--"I like salami. "-I want to walk to the shops"'
MyString = MyString.replace('"',"")
MyString = MyString.replace('-',"")
print MyString
#output: I like salami. I want to walk to the shops

Or you can use Regular expression and do it like this:

import re
MyString = '--"I like salami. "-I want to walk to the shops"'
MyString = re.sub('["-]', '', MyString)
print MyString
#output: I like salami. I want to walk to the shops

Remember to install re if it doesn't exist already. Tell me if there are any problems.


问:
How does one get the code as a string of an object?
I was attempting to do a little metaprogramming and I was wondering how to get the code for an object (or ActiveRecord relation) passed to a method. Ideally, it would return the string of the ruby code. For example:

```<code>class Bike
end

# Ideal response
get_code_for(Bike.new)
#=> 'Bike.new'

get_code_for(User.where(id: 123))
#=> 'User.where(id: 123)'

get_code_for(Article.published)
#=> 'Article.published'
</code>```

This works for numerics and strings, however, for classes and relations, the arguments are evaluated and return something along the lines of #<Bike:0x000056338e33fca8>.

答:
If you want a pointer to a method, you can get that with Class#method. This gets you a Method instance which has methods such as #receiver and #name.

```<code>m = Bike.method(:new)
m.receiver # => Bike
m.name # => :new
m.call # => #<Bike:0x000000017a7078>
format("%s.%s", m.receiver, m.name) # => "Bike.new"
</code>```

Body:
I was attempting to do a little metaprogramming and I was wondering how to get the code for an object (or ActiveRecord relation) passed to a method. Ideally, it would return the string of the ruby code. For example:

class Bike
end

# Ideal response
get_code_for(Bike.new)
#=> 'Bike.new'

get_code_for(User.where(id: 123))
#=> 'User.where(id: 123)'

get_code_for(Article.published)
#=> 'Article.published'

This works for numerics and strings, however, for classes and relations, the arguments are evaluated and return something along the lines of #<Bike:0x000056338e33fca8>.

Body:
If you want a pointer to a method, you can get that with Class#method. This gets you a Method instance which has methods such as #receiver and #name.

m = Bike.method(:new)
m.receiver # => Bike
m.name # => :new
m.call # => #<Bike:0x000000017a7078>
format("%s.%s", m.receiver, m.name) # => "Bike.new"


问:
The remote server returned an error: (401) Unauthorized in Microsoft.ProjectOxford
Call GetSentimentAsync is failing with error 401 as mentioned in title

```<code>var client = new SentimentClient(Constants.API_KEY);
var request = new SentimentRequest();
var response = await client.GetSentimentAsync(request);
</code>```

My resource group for generating key in Azure has location "South Central US", my location is Colorado, my subscription is "Visual Studio Enterprise"

I used this page to test my service
https://westus.dev.cognitive.microsoft.com/docs/services/TextAnalytics.V2.0/operations/56f30ceeeda5650db055a3c7

If I use https://westus.dev.cognitive.microsoft.com/docs/services/TextAnalytics.V2.0/operations/someID link to test call. It gives 401.

If I use https://southcentralus.dev.cognitive.microsoft.com/docs/services/TextAnalytics.V2.0/operations/someID/ then it is giving 200.

Seems like issue is related to the Region I selected at the time of creation of New Resource in Azure. Seems like default Region is not what I selected, South Central US

So, what should I do make my call succeed? Where I can mention region in making API call?

Thanks
Abbas

答:
Location is in the API call itself: https://[location].api.cognitive.microsoft.com/text/analytics/v2.0/sentiment. In your case, you should use southcentralus in place of [location].

Example of POST request is on this page: https://southcentralus.dev.cognitive.microsoft.com/docs/services/TextAnalytics.V2.0/operations/56f30ceeeda5650db055a3c9/console.

Body:
Call GetSentimentAsync is failing with error 401 as mentioned in title

var client = new SentimentClient(Constants.API_KEY);
var request = new SentimentRequest();
var response = await client.GetSentimentAsync(request);

My resource group for generating key in Azure has location "South Central US", my location is Colorado, my subscription is "Visual Studio Enterprise"

I used this page to test my service
https://westus.dev.cognitive.microsoft.com/docs/services/TextAnalytics.V2.0/operations/56f30ceeeda5650db055a3c7

If I use https://westus.dev.cognitive.microsoft.com/docs/services/TextAnalytics.V2.0/operations/someID link to test call. It gives 401.

If I use https://southcentralus.dev.cognitive.microsoft.com/docs/services/TextAnalytics.V2.0/operations/someID/ then it is giving 200.

Seems like issue is related to the Region I selected at the time of creation of New Resource in Azure. Seems like default Region is not what I selected, South Central US

So, what should I do make my call succeed? Where I can mention region in making API call?

Thanks
Abbas


问:
JS: Why are variables allowed to be declared both with and without the `var` keyword...?
It is possible to declare a javascript variable both with and without the var keyword.

```<code>var a = 100; // this works!
    b = 200; // and this does too!
</code>```

It is also possible to declare a variable without initialisation.

```<code>var c;       // this is just as acceptable!
</code>```

But then why is the same NOT true for a variable without var, to be declared without initialisation.

```<code>var c;
    d;       // causes a reference error to occur!
</code>```

Why?

答:
You can do that in non-strict mode

```<code>   var a = 100; // this works!
        b = 200; // and this does too!
</code>```

for non-strict mode, someVar = someValue, if someVar is not existed, javascript will declare it and assign a someValue to someVar.

For that case:

```<code>var c;
    d;       // causes a reference error to occur!
</code>```

line 1: var c; --> declare c, it's valid syntax.
line 2: d;  --> you access d, but d is underfined --> causes error !!!
assume d is defined anywhere before that line, so it should NOT cause error!!

Body:
It is possible to declare a javascript variable both with and without the var keyword.

var a = 100; // this works!
    b = 200; // and this does too!

It is also possible to declare a variable without initialisation.

var c;       // this is just as acceptable!

But then why is the same NOT true for a variable without var, to be declared without initialisation.

var c;
    d;       // causes a reference error to occur!

Why?

Body:
You can do that in non-strict mode

   var a = 100; // this works!
        b = 200; // and this does too!

for non-strict mode, someVar = someValue, if someVar is not existed, javascript will declare it and assign a someValue to someVar.

For that case:

var c;
    d;       // causes a reference error to occur!

line 1: var c; --> declare c, it's valid syntax.
line 2: d;  --> you access d, but d is underfined --> causes error !!!
assume d is defined anywhere before that line, so it should NOT cause error!!


问:
new to java system cant find path
```<code>/**
 * @(#)ListFiles.java
 *
 * ListFiles application
 *
 * @author Jack
 * @version 1.00 2017/12/6
 */

public class ListFiles {

   public static void main(String[] args) {

      java.io.File
      java.io.File listroot = new java.io.File("c:/");
      java.io.File[] files = listroot.listFiles();

      System.out.println("Print root files from c:");

      for (java.io.File file : files) {
         if (file.isDirectory())
            continue;
         System.out.println(file.getPath());
      }
   }
}
</code>```

<p>--------------------Configuration: ListFiles - JDK version 1.8.0_151  - --------------------
javac: file not found: src_listfiles.txt (The system cannot find the path specified)</p>

答:
You have syntax error in your program , try this :

```<code>public class cn {

   public static void main(String[] args) {

      java.io.File f;
      java.io.File listroot = new java.io.File("c:/");
      java.io.File[] files = listroot.listFiles();

      System.out.println("Print root files from c:");

      for (java.io.File file : files) {
         if (file.isDirectory())
            continue;
         System.out.println(file.getPath());
      }
   }
}
</code>```

Above program working in Eclipse ide.

Title: new to java system cant find path

Body:
/**
 * @(#)ListFiles.java
 *
 * ListFiles application
 *
 * @author Jack
 * @version 1.00 2017/12/6
 */

public class ListFiles {

   public static void main(String[] args) {

      java.io.File
      java.io.File listroot = new java.io.File("c:/");
      java.io.File[] files = listroot.listFiles();

      System.out.println("Print root files from c:");

      for (java.io.File file : files) {
         if (file.isDirectory())
            continue;
         System.out.println(file.getPath());
      }
   }
}

--------------------Configuration: ListFiles - JDK version 1.8.0_151  - --------------------
javac: file not found: src_listfiles.txt (The system cannot find the path specified)

Body:
You have syntax error in your program , try this :

public class cn {

   public static void main(String[] args) {

      java.io.File f;
      java.io.File listroot = new java.io.File("c:/");
      java.io.File[] files = listroot.listFiles();

      System.out.println("Print root files from c:");

      for (java.io.File file : files) {
         if (file.isDirectory())
            continue;
         System.out.println(file.getPath());
      }
   }
}

Above program working in Eclipse ide.


答:
Python string.replace doesn't do an in-place replace, but instead returns a new string which contains the replacement. Since you are not using the return value from the first replace, it is discarded and the second iteration of your loop with the character - replaces just this character and not ", in the original string. For the intended effect, you can use the following snippet:

```<code>MyString = '--"I like salami. "-I want to walk to the shops"'
b = '"-'
for char in b:
    MyString = MyString.replace(char,"")
print(MyString)
#Outputs: I like salami. I want to walk to the shops
</code>```

Title: Python - Remove quotes and double minus using replace

Body:
Python string.replace doesn't do an in-place replace, but instead returns a new string which contains the replacement. Since you are not using the return value from the first replace, it is discarded and the second iteration of your loop with the character - replaces just this character and not ", in the original string. For the intended effect, you can use the following snippet:

MyString = '--"I like salami. "-I want to walk to the shops"'
b = '"-'
for char in b:
    MyString = MyString.replace(char,"")
print(MyString)
#Outputs: I like salami. I want to walk to the shops


问:
How to redirect *after* dropping a facebook tracking pixel (or similar)
Trying to figure out how to redirect to a new page after dropping a Facebook retargeting pixel.

We already have everything else setup but want to add this functionality (the same as https://meteor.link/)

We currently use window.location.replace('https://thelinkgoeshere.com'); but I think the Facebook is async so we can't just add the pixel code above it.

Thanks for any help you can provide!

答:
If you look closely at the Facebook pixel code, you'll notice that somewhere in that code, the dynamic script tag being inserted by the pixel has it's async property set to true like so:

```<code>t.async=!0;
</code>```

!0 evaluates to true.

To change this behavior, find where this property is being set in the pixel, and change it to false:

```<code>t.async=false;
</code>```

Normally this would not be recommended as turning off async will block further execution until the script is loaded and executed, but in your case that's exactly what you need.

Once you set async to false, it is guaranteed that the FB pixel JS code will load and run before the next script that follows the pixel:

```<code><script>
    // FB pixel here with async false
</script>

<script>
    window.location.replace('https://thelinkgoeshere.com');
<script>
</code>```

Body:
If you look closely at the Facebook pixel code, you'll notice that somewhere in that code, the dynamic script tag being inserted by the pixel has it's async property set to true like so:

t.async=!0;

!0 evaluates to true.

To change this behavior, find where this property is being set in the pixel, and change it to false:

t.async=false;

Normally this would not be recommended as turning off async will block further execution until the script is loaded and executed, but in your case that's exactly what you need.

Once you set async to false, it is guaranteed that the FB pixel JS code will load and run before the next script that follows the pixel:

<script>
    // FB pixel here with async false
</script>

<script>
    window.location.replace('https://thelinkgoeshere.com');
<script>


问:
Dealing with Views in Phalcon Controllers
I am working on a newly created Phalcon project, and I don't really know how to actually use multiples views.

What is the entry point? I don't really know when each method in the controller is called, under which conditions, etc.

Where is the control flow defined? is it based in the name of the view? or is there a place where you can register them?

答:
Phalcon is a bit different than other well-known PHP frameworks, in that not much is pre-configured or pre-built by default. It's quite loosely-coupled. So you have to decide where and how your control flow will work. This means that you will need to dig deeper in the documentation and also that there could be different way to achieve the same thing.

I'm going to walk you through a simple example and provide references, so you can understand it more.

1) You would start by defining a bootstrap file (or files) that will define the routes, or entry points, and will setup and create the application. This bootstrap file could be called by an index.php file that is the default file served by the web server. Here is an example of how such bootstrap file will define the routes or entry points (note: these are just fragments and do not represent all the things that a bootstrap file should do):

```<code>use Phalcon\Di\FactoryDefault;

// initializes the dependency injector of Phalcon framework
$injector = new FactoryDefault();

// defines the routes
$injector->setShared('router', function () {
    return require_once('some/path/routes.php');
});
</code>```

Then it the routes.php file:

```<code>use Phalcon\Mvc\Router;
use Phalcon\Mvc\Router\Group as RouterGroup;

// instantiates the router
$router = new Router(false);
// defines routes for the 'users' controller
$user_routes = new RouterGroup(['controller' => 'users']);
$user_routes->setPrefix('/users');
$user_routes->addGet('/show/{id:[0-9]{1,9}}', ['action' => 'show']);
$router->mount($user_routes);
return $router;
</code>```

Im defining routes in an alternate way, by defining routes groups. I find it to be more easy to organize routes by resource or controller.

2) When you enter the url example.com/users/show/123, the routes above will match this to the controller users and action show. This is specified by the chunks of code ['controller' => 'users'], setPrefix('/users') and '/show/{id:[0-9]{1,9}}', ['action' => 'show']

3) So now you create the controller. You create a file in, let's say, controllers/UsersController.php. And then you create its action; note the name that you used in the route (show) and the suffix of Action:

```<code>public function showAction(int $id) {
    // ... do all you need to do...

    // fetch data
    $user = UserModel::findFirst(blah blah);

    // pass data to view
    $this->view->setVar('user', $user);

    // Phalcon automatically calls the view; from the manual:
    /*
    Phalcon automatically passes the execution to the view component as soon as a particular
    controller has completed its cycle. The view component will look in the views folder for
    a folder named as the same name of the last controller executed and then for a file named
    as the last action executed.
    */

    // but in case you would need to specify a different one
    $this->view->render('users', 'another_view');
}
</code>```

There is much more stuff related to views; consult the manual.

Note that you will need to register such controller in the bootstrap file like (Im also including examples on how to register other things):

```<code>use Phalcon\Loader;
// registers namespaces and other classes
$loader = new Loader();
$loader->registerNamespaces([
    'MyNameSpace\Controllers' => 'path/controllers/',
    'MyNameSpace\Models' => 'path/models/',
    'MyNameSpace\Views' => 'path/views/'
]);
$loader->register();
</code>```

4) You will also need to register a few things for the views. In the bootstrap file

```<code>use Phalcon\Mvc\View;

$injector->setShared('view', function () {
    $view = new View();
    $view->setViewsDir('path/views/');
    return $view;
});
</code>```

And this, together with other things you will need to do, particularly in the bootstrap process, will get you started in sending requests to the controller and action/view defined in the routes.

Those were basic examples. There is much more that you will need to learn, because I only gave you a few pieces to get you started. So here are some links that can explain more. Remember, there are several different ways to achieve the same thing in Phalcon.

Bootstrapping:

https://docs.phalconphp.com/en/3.2/di

https://docs.phalconphp.com/en/3.2/loader

https://docs.phalconphp.com/en/3.2/dispatcher

Routing: https://docs.phalconphp.com/en/3.2/routing

Controllers: https://docs.phalconphp.com/en/3.2/controllers

More on Views (from registering to passing data to them, to templating and more): https://docs.phalconphp.com/en/3.2/views

And a simple tutorial to teach you some basic things: https://docs.phalconphp.com/en/3.2/tutorial-rest

Body:
Phalcon is a bit different than other well-known PHP frameworks, in that not much is pre-configured or pre-built by default. It's quite loosely-coupled. So you have to decide where and how your control flow will work. This means that you will need to dig deeper in the documentation and also that there could be different way to achieve the same thing.

I'm going to walk you through a simple example and provide references, so you can understand it more.

1) You would start by defining a bootstrap file (or files) that will define the routes, or entry points, and will setup and create the application. This bootstrap file could be called by an index.php file that is the default file served by the web server. Here is an example of how such bootstrap file will define the routes or entry points (note: these are just fragments and do not represent all the things that a bootstrap file should do):

use Phalcon\Di\FactoryDefault;

// initializes the dependency injector of Phalcon framework
$injector = new FactoryDefault();

// defines the routes
$injector->setShared('router', function () {
    return require_once('some/path/routes.php');
});

Then it the routes.php file:

use Phalcon\Mvc\Router;
use Phalcon\Mvc\Router\Group as RouterGroup;

// instantiates the router
$router = new Router(false);
// defines routes for the 'users' controller
$user_routes = new RouterGroup(['controller' => 'users']);
$user_routes->setPrefix('/users');
$user_routes->addGet('/show/{id:[0-9]{1,9}}', ['action' => 'show']);
$router->mount($user_routes);
return $router;

Im defining routes in an alternate way, by defining routes groups. I find it to be more easy to organize routes by resource or controller.

2) When you enter the url example.com/users/show/123, the routes above will match this to the controller users and action show. This is specified by the chunks of code ['controller' => 'users'], setPrefix('/users') and '/show/{id:[0-9]{1,9}}', ['action' => 'show']

3) So now you create the controller. You create a file in, let's say, controllers/UsersController.php. And then you create its action; note the name that you used in the route (show) and the suffix of Action:

public function showAction(int $id) {
    // ... do all you need to do...

    // fetch data
    $user = UserModel::findFirst(blah blah);

    // pass data to view
    $this->view->setVar('user', $user);

    // Phalcon automatically calls the view; from the manual:
    /*
    Phalcon automatically passes the execution to the view component as soon as a particular
    controller has completed its cycle. The view component will look in the views folder for
    a folder named as the same name of the last controller executed and then for a file named
    as the last action executed.
    */

    // but in case you would need to specify a different one
    $this->view->render('users', 'another_view');
}

There is much more stuff related to views; consult the manual.

Note that you will need to register such controller in the bootstrap file like (Im also including examples on how to register other things):

use Phalcon\Loader;
// registers namespaces and other classes
$loader = new Loader();
$loader->registerNamespaces([
    'MyNameSpace\Controllers' => 'path/controllers/',
    'MyNameSpace\Models' => 'path/models/',
    'MyNameSpace\Views' => 'path/views/'
]);
$loader->register();

4) You will also need to register a few things for the views. In the bootstrap file

use Phalcon\Mvc\View;

$injector->setShared('view', function () {
    $view = new View();
    $view->setViewsDir('path/views/');
    return $view;
});

And this, together with other things you will need to do, particularly in the bootstrap process, will get you started in sending requests to the controller and action/view defined in the routes.

Those were basic examples. There is much more that you will need to learn, because I only gave you a few pieces to get you started. So here are some links that can explain more. Remember, there are several different ways to achieve the same thing in Phalcon.

Bootstrapping:

https://docs.phalconphp.com/en/3.2/di

https://docs.phalconphp.com/en/3.2/loader

https://docs.phalconphp.com/en/3.2/dispatcher

Routing: https://docs.phalconphp.com/en/3.2/routing

Controllers: https://docs.phalconphp.com/en/3.2/controllers

More on Views (from registering to passing data to them, to templating and more): https://docs.phalconphp.com/en/3.2/views

And a simple tutorial to teach you some basic things: https://docs.phalconphp.com/en/3.2/tutorial-rest


问:
Is it possible to use a variable as part of an image URL?
I am making a quiz on a basic website using PHP and HTML/CSS and have answers stored in a PHP array.

I would like to display the quiz answers and the corresponding images (which I have named to match) using the simplest method.
For example if $ANSWER="cat", I want to display "cat.jpg"

If it were possible to use a variable in the image URL it would be wonderful, but I haven't been able to find an example of this.

Should this syntax work?

```<code>echo '<img src=/pictures/"$ANSWER".jpg >';
</code>```

So far I'm getting no output but not sure if it's due to a bug somewhere else.

答:
Hi :) Hope this helps :)

```<code><?php
$ANSWER="cat";
?>
<img src="pictures/<?php echo "$ANSWER.jpg"; ?>">
</code>```

Proven and tested :)

Body:
I am making a quiz on a basic website using PHP and HTML/CSS and have answers stored in a PHP array.

I would like to display the quiz answers and the corresponding images (which I have named to match) using the simplest method.
For example if $ANSWER="cat", I want to display "cat.jpg"

If it were possible to use a variable in the image URL it would be wonderful, but I haven't been able to find an example of this.

Should this syntax work?

echo '';

So far I'm getting no output but not sure if it's due to a bug somewhere else.

Body:
Hi :) Hope this helps :)

<?php
$ANSWER="cat";
?>
<img src="pictures/<?php echo "$ANSWER.jpg"; ?>">

Proven and tested :)


问:
Anychart tables: How to include thousand separators?
How can I put the text "100.000" in a table in Anychart? When I try to get the string "100.000" in, it is modified to "100".

For a working example see https://jsfiddle.net/Republiq/xcemvm9L/

```<code>table = anychart.standalones.table(2,2);
table.getCell(0,0).content("100.000");
table.container("container").draw();
</code>```

答:
If you want to use such number formatting for the whole table you can define numberLocale in the beginning. If the actual number is 100 and '.' - is a decimal separator and you want to show 3 zeros as decimals, put the following lines before creating the table:

```<code>anychart.format.locales.default.numberLocale.decimalsCount = 3;
anychart.format.locales.default.numberLocale.zeroFillDecimals = true;
</code>```

And then put in the number as:

```<code>table.getCell(0,0).content(100);
</code>```

If '.' - is a group separator and the actual number is 100000, put the following line:
    anychart.format.locales.default.numberLocale.groupsSeparator = '.';
And then put in the number as:

```<code> table.getCell(0,0).content(100000);
</code>```

If you want to use special format only for a single cell, we recommend you to use number formatter, which helps to configure all these options only for a single number. For example, it may looks like:

```<code>table = anychart.standalones.table(5,5);
table.getCell(0,0).content(anychart.format.number(100000, 3, ".", ","));
table.container("container").draw();
</code>```

Also, you may learn more about this useful method and find examples in this article

Body:
How can I put the text "100.000" in a table in Anychart? When I try to get the string "100.000" in, it is modified to "100".

For a working example see https://jsfiddle.net/Republiq/xcemvm9L/

table = anychart.standalones.table(2,2);
table.getCell(0,0).content("100.000");
table.container("container").draw();

Body:
If you want to use such number formatting for the whole table you can define numberLocale in the beginning. If the actual number is 100 and '.' - is a decimal separator and you want to show 3 zeros as decimals, put the following lines before creating the table:

anychart.format.locales.default.numberLocale.decimalsCount = 3;
anychart.format.locales.default.numberLocale.zeroFillDecimals = true;

And then put in the number as:

table.getCell(0,0).content(100);

If '.' - is a group separator and the actual number is 100000, put the following line:
    anychart.format.locales.default.numberLocale.groupsSeparator = '.';
And then put in the number as:

 table.getCell(0,0).content(100000);

If you want to use special format only for a single cell, we recommend you to use number formatter, which helps to configure all these options only for a single number. For example, it may looks like:

table = anychart.standalones.table(5,5);
table.getCell(0,0).content(anychart.format.number(100000, 3, ".", ","));
table.container("container").draw();

Also, you may learn more about this useful method and find examples in this article


问:
Pass $(this) to a function
I am trying to build a media playlist that can advance the credits, play the video and change the title on thumb-hover, end of video and on next/prev click. So I need to write some functions that can then be called together. So like this:

```<code>    function showBox()
    {
        $(this).parents('.container').find('.box').show();
    };

    function hideBox()
    {
        $(this).parents('.container').find('.box').hide();
    };

    $('a').hover(
        function()
        {
            showBox();
        },
        function()
        {
            hideBox();
        }
    );
</code>```

The problem is that $(this) does not carry through to the functions from the .hover. How do I do this?

答:
In Javascript you can use call() or apply() to execute a function and explicitly specify this for it:

```<code>$('a').hover(
    function()
    {
        showBox.call(this);
    },
    function()
    {
        hideBox.call(this);
    }
);
</code>```

The first parameter given to call() specifies the object that this will refer to in the function. Any further parameters are used as parameters in the function call.

ContentLicense: CC BY-SA 4.0

Title: Pass $(this) to a function

Body:
I am trying to build a media playlist that can advance the credits, play the video and change the title on thumb-hover, end of video and on next/prev click. So I need to write some functions that can then be called together. So like this:

    function showBox()
    {
        $(this).parents('.container').find('.box').show();
    };

    function hideBox()
    {
        $(this).parents('.container').find('.box').hide();
    };

    $('a').hover(
        function()
        {
            showBox();
        },
        function()
        {
            hideBox();
        }
    );

The problem is that $(this) does not carry through to the functions from the .hover. How do I do this?

Body:
In Javascript you can use call() or apply() to execute a function and explicitly specify this for it:

$('a').hover(
    function()
    {
        showBox.call(this);
    },
    function()
    {
        hideBox.call(this);
    }
);

The first parameter given to call() specifies the object that this will refer to in the function. Any further parameters are used as parameters in the function call.

ContentLicense: CC BY-SA 2.5


答:
The .replace(oldstr, newstr) method will help you, and it is simple and daisy-chainable. So...

```<code>MyString = MyString.replace('"', '').replace('-', '')
</code>```

Note that the .replace() method only replaces substrings in one shot. It cannot do individual characters. For that, you could do it with a regular expression, but that's more complicated. That module can be accessed with import re.  You could use:

```<code>MyString = re.sub('["-]', '', MyString)
</code>```

Also, on a sidenote... Quoting can be tricky. But there are FOUR different ways you can quote something: in a pair of single quotes, a pair of double quotes, or a pair of triple single-quotes or triple double-quotes. So, all the below are strings in Python:

```<code>'hello'
"Don't you think"  # string with an apostrophe is easily in double quotes
'''that this is a really really..'''
"""long quote?  Hey!
    this quote is actually more than one line long!"""
</code>```

Body:
Given a string such as

--"I like salami. "-I want to walk to the shops"

How can I return the string such as

I like salami. I want to walk to the shops.

I can alter each individually but when I use '-"' it fails.

Quotes

b = '"'

for char in b:
    solution = MyString.replace(char,"")

#output --I like salami. -I want to walk to the shops

Minus

b = '-'

for char in b:
    solution = MyString.replace(char,"")

#output "I like salami. "I want to walk to the shops"

Together

MyString = '--"I like salami. "-I want to walk to the shops"'

b = '"-'

for char in b:
    print(MyString.replace(char,""))

#output "I like salami. "I want to walk to the shops"

Body:
The .replace(oldstr, newstr) method will help you, and it is simple and daisy-chainable. So...

MyString = MyString.replace('"', '').replace('-', '')

Note that the .replace() method only replaces substrings in one shot. It cannot do individual characters. For that, you could do it with a regular expression, but that's more complicated. That module can be accessed with import re.  You could use:

MyString = re.sub('["-]', '', MyString)

Also, on a sidenote... Quoting can be tricky. But there are FOUR different ways you can quote something: in a pair of single quotes, a pair of double quotes, or a pair of triple single-quotes or triple double-quotes. So, all the below are strings in Python:

'hello'
"Don't you think"  # string with an apostrophe is easily in double quotes
'''that this is a really really..'''
"""long quote?  Hey!
    this quote is actually more than one line long!"""


问:
Authentication on angular spa using msal.js
my angular app has 1000s unique routes and users should be able to click on login button from any of those pages. Have implemented msal.js basing on this sample :

https://github.com/Gimly/simpleAngularAzureB2C/blob/master/src/app/authentication.service.ts

I am getting following error when calling login method:

AADB2C90006:+The+redirect+URI+'http://localhost:39579/unique-uri'+provided+in+the+request+is+not+registered+for+the+client+id+

Is there a way to get around this?

Thanks!

答:
By default, the Msal.UserAgentApplication constructor sets the "redirect_uri" request parameter to the current URL, which doesn't scale.

The Msal.UserAgentApplication constructor accepts a "redirectUri" options argument that enables the "redirect_uri" request parameter to be set to a fixed URL (e.g. "http://localhost:39579/authcallback") that is registered for the Azure AD B2C application.

Before MSAL generates the authentication request to Azure AD B2C, it writes the current URL (e.g., "http://localhost:39579/unique-uri") to storage and then redirects the user agent to the authentication endpoint.

At the "/authcallback" endpoint, you must create a new instance of Msal.UserAgentApplication, to handle the authentication response.

After MSAL verifies the authentication response from Azure AD B2C, it reads the original URL from storage and then returns the user agent to this URL.


问:
Add scale bar (in meters) to scatterplot of GPS coordinates in Stata

I am graphing a series of GPS points using twoway scatter in Stata. This is just to visualize where the points are for some quick validation. I would like to add a scale bar for both the x and y axes to get a sense of how far apart the points actually are.

Here is some code to input a few coordinates and graph a scatterplot, specifying the axis ranges:

```<code>* Input example data
    clear
    input key lat lon
    1   -17.01639   36.11884
    2   -17.01669   36.11916
    3   -17.01692   36.11666
    4   -17.01575   36.11607
    5   -17.01551   36.11619
    6   -17.01543   36.11665
    7   -17.01581   36.11706
    8   -17.01665   36.11672
    9   -17.01543   36.11612
    10  -17.01724   36.11668
    end

* Install Geodist (we will need this later)
    cap which geodist
        if _rc == 111 ssc install geodist   // Installs geodist if necessary

* Create y/x axis ranges using min and max latitude and longitude
    sort lat
    local ymin = lat[1]
    local ymax = lat[_N]
    local ydelta = (`ymax' - `ymin')/3

    sort lon
    local xmin = lon[1]
    local xmax = lon[_N]
    local xdelta = (`xmax' - `xmin')/3

* Graph points
    twoway scatter lat lon,                                 ///
        ylabel(`ymin'(`ydelta')`ymax', angle(forty_five))   ///
        xlabel(`xmin'(`xdelta')`xmax')
</code>```

You should get a lovely basic scatterplot. This is great, but I have no idea how far the points actually are from each other. Now, we can get a sense of the distance between the minimum and maximum latitude/longitude using the following:

```<code>* Store x and y ranges in locals
    geodist `ymin' `xmin' `ymax' `xmin'
    local yrange = `r(distance)'

    geodist `ymin' `xmin' `ymin' `xmax'
    local xrange = `r(distance)'
</code>```

For this data, y spans 0.2km and x spans 0.329km.

Note: I know that on a spherical projection of the earth the distance between ymin and ymax may not map perfectly onto subsets of that distance (e.g. the distance from ymin to ymax/2 may not be precisely the same as half the distance between ymin and ymax). But for what I need this visualization for, and the fact that these data are usally clustered within 2km of each other, its accurate enough.

So, how can I create a scale bar for each of x and y to show what, for example, 100m looks like? In this example, the y scale would look different than the x scale, so maybe I need to find a way to change the y-ranges and x-ranges so that they can represent the same scale?

答:
I am not sure if this is exactly what you want, I don't have any experience with geo2xy in Stata, but with regular twoway and a bit of algebra you can get approximate values for these scales (especially since you say you're working on a small scale where approximating is okay)

I put the code below, but it is a little long, so here is the executive summary:

First, we want to calculate the latitude and longitude values for a distance of 1 meter. We can do this because we have the range in kilometers and minimum and maximum values for latitude and longitude.

I then put this distance into a twoway connect graph on the same scatter plot we had before.

To get the value for the 1 meter distance I do the following:

We can assume this is pretty much linear (0 maps to 0 kilometers and xmax-xmin maps to xrange kilometers) so to get one meter we can plug this in to a linear equation y=mx+b, note b is 0 and our slope = xrange/(xmax-xmin). Then, we can set 1 meter = 1/1000 * 1/slope or 1 meter = (xmax-xmin)/(xrange*1000). In my example I use 100 meters because 1 meter was too small, but to change the scaling you just have to change the 1/1000 to whatever scale you want.
We can then do the same thing for the y axis and add them to the dataset and graph them.

here is the code I used to play around with it after running your code from above:

```<code>local xmeter = (`xmax'-`xmin')/(`xrange'*10)
local ymeter = (`ymax'-`ymin')/(`yrange'*10)
local xbit = (`xmax'-`xmin')/20
local ybit = (`ymax'-`ymin')/20
local xmin_and_bit = `xmin' + `xbit'
local ymin_and_bit = `ymin' + `ybit'
local xmin_and_bit_and_one_meter = `xmin' + `xbit' + `xmeter'
local ymin_and_bit_and_one_meter = `ymin' + `ybit' + `ymeter'

// generate a dummy variable for data vs lengths
gen scale = 0

// add four observations for our distance markers
local new_obs_num = _N + 4
set obs `new_obs_num'

// point for ymin and xmin+bit
replace scale = 1 if _n == _N - 3
replace lat = `ymin' if _n == _N - 3
replace lon = `xmin_and_bit' if _n == _N - 3

// point for ymin and xmin+bit+1
replace scale = 1 if _n == _N - 2
replace lat = `ymin' if _n == _N - 2
replace lon = `xmin_and_bit_and_one_meter' if _n == _N - 2

// point for ymin+bit and xmin
replace scale = 2 if _n == _N - 1
replace lat = `ymin_and_bit' if _n == _N - 1
replace lon = `xmin' if _n == _N - 1

// point for ymin+bit+1 and xmin
replace scale = 2 if _n == _N
replace lat = `ymin_and_bit_and_one_meter' if _n == _N
replace lon = `xmin' if _n == _N

// now graph the scatter plot if scale == 0,
// the x 100 meters if scale == 1,
// and y 100 meters if scale == 2
twoway (scatter lat lon if scale == 0) ///
    (connected lat lon if scale == 1, ///
        msymbol(+) lcolor(black) mcolor(black)) ///
    (connected lat lon if scale == 2, ///
        msymbol(+) lcolor(black) mcolor(black)), ///
    ylabel(`ymin'(`ydelta')`ymax', angle(forty_five))   ///
    xlabel(`xmin'(`xdelta')`xmax') ///
    legend(off) ///
    note("Points are points and lines show 100 meters")
</code>```

Body:
I am graphing a series of GPS points using twoway scatter in Stata. This is just to visualize where the points are for some quick validation. I would like to add a scale bar for both the x and y axes to get a sense of how far apart the points actually are.

Here is some code to input a few coordinates and graph a scatterplot, specifying the axis ranges:

* Input example data
    clear
    input key lat lon
    1   -17.01639   36.11884
    2   -17.01669   36.11916
    3   -17.01692   36.11666
    4   -17.01575   36.11607
    5   -17.01551   36.11619
    6   -17.01543   36.11665
    7   -17.01581   36.11706
    8   -17.01665   36.11672
    9   -17.01543   36.11612
    10  -17.01724   36.11668
    end

* Install Geodist (we will need this later)
    cap which geodist
        if _rc == 111 ssc install geodist   // Installs geodist if necessary

* Create y/x axis ranges using min and max latitude and longitude
    sort lat
    local ymin = lat[1]
    local ymax = lat[_N]
    local ydelta = (`ymax' - `ymin')/3

    sort lon
    local xmin = lon[1]
    local xmax = lon[_N]
    local xdelta = (`xmax' - `xmin')/3

* Graph points
    twoway scatter lat lon,                                 ///
        ylabel(`ymin'(`ydelta')`ymax', angle(forty_five))   ///
        xlabel(`xmin'(`xdelta')`xmax')

You should get a lovely basic scatterplot. This is great, but I have no idea how far the points actually are from each other. Now, we can get a sense of the distance between the minimum and maximum latitude/longitude using the following:

* Store x and y ranges in locals
    geodist `ymin' `xmin' `ymax' `xmin'
    local yrange = `r(distance)'

    geodist `ymin' `xmin' `ymin' `xmax'
    local xrange = `r(distance)'

For this data, y spans 0.2km and x spans 0.329km.

Note: I know that on a spherical projection of the earth the distance between ymin and ymax may not map perfectly onto subsets of that distance (e.g. the distance from ymin to ymax/2 may not be precisely the same as half the distance between ymin and ymax). But for what I need this visualization for, and the fact that these data are usally clustered within 2km of each other, its accurate enough.

So, how can I create a scale bar for each of x and y to show what, for example, 100m looks like? In this example, the y scale would look different than the x scale, so maybe I need to find a way to change the y-ranges and x-ranges so that they can represent the same scale?

Body:
I am not sure if this is exactly what you want, I don't have any experience with geo2xy in Stata, but with regular twoway and a bit of algebra you can get approximate values for these scales (especially since you say you're working on a small scale where approximating is okay)

I put the code below, but it is a little long, so here is the executive summary:

First, we want to calculate the latitude and longitude values for a distance of 1 meter. We can do this because we have the range in kilometers and minimum and maximum values for latitude and longitude.

I then put this distance into a twoway connect graph on the same scatter plot we had before.

To get the value for the 1 meter distance I do the following:

We can assume this is pretty much linear (0 maps to 0 kilometers and xmax-xmin maps to xrange kilometers) so to get one meter we can plug this in to a linear equation y=mx+b, note b is 0 and our slope = xrange/(xmax-xmin). Then, we can set 1 meter = 1/1000 * 1/slope or 1 meter = (xmax-xmin)/(xrange*1000). In my example I use 100 meters because 1 meter was too small, but to change the scaling you just have to change the 1/1000 to whatever scale you want.
We can then do the same thing for the y axis and add them to the dataset and graph them.

here is the code I used to play around with it after running your code from above:

local xmeter = (`xmax'-`xmin')/(`xrange'*10)
local ymeter = (`ymax'-`ymin')/(`yrange'*10)
local xbit = (`xmax'-`xmin')/20
local ybit = (`ymax'-`ymin')/20
local xmin_and_bit = `xmin' + `xbit'
local ymin_and_bit = `ymin' + `ybit'
local xmin_and_bit_and_one_meter = `xmin' + `xbit' + `xmeter'
local ymin_and_bit_and_one_meter = `ymin' + `ybit' + `ymeter'

// generate a dummy variable for data vs lengths
gen scale = 0

// add four observations for our distance markers
local new_obs_num = _N + 4
set obs `new_obs_num'

// point for ymin and xmin+bit
replace scale = 1 if _n == _N - 3
replace lat = `ymin' if _n == _N - 3
replace lon = `xmin_and_bit' if _n == _N - 3

// point for ymin and xmin+bit+1
replace scale = 1 if _n == _N - 2
replace lat = `ymin' if _n == _N - 2
replace lon = `xmin_and_bit_and_one_meter' if _n == _N - 2

// point for ymin+bit and xmin
replace scale = 2 if _n == _N - 1
replace lat = `ymin_and_bit' if _n == _N - 1
replace lon = `xmin' if _n == _N - 1

// point for ymin+bit+1 and xmin
replace scale = 2 if _n == _N
replace lat = `ymin_and_bit_and_one_meter' if _n == _N
replace lon = `xmin' if _n == _N

// now graph the scatter plot if scale == 0,
// the x 100 meters if scale == 1,
// and y 100 meters if scale == 2
twoway (scatter lat lon if scale == 0) ///
    (connected lat lon if scale == 1, ///
        msymbol(+) lcolor(black) mcolor(black)) ///
    (connected lat lon if scale == 2, ///
        msymbol(+) lcolor(black) mcolor(black)), ///
    ylabel(`ymin'(`ydelta')`ymax', angle(forty_five))   ///
    xlabel(`xmin'(`xdelta')`xmax') ///
    legend(off) ///
    note("Points are points and lines show 100 meters")


问:
boost python with threads
It seems boost::python and boost::thread don't really like each other for what I can tell.

Please refer to http://pastebin.com/Cy123mJK

This is a simplification of the problems I am having with my boost::python and boost::thread-based application.

If anyone can tell me why these problems are occurring; I have no clue, since I strictly make sure python interaction is done with one thread at once.

At some point, the program crashes with a segfault for no obvious reason. Also, it's impossible to catch this crash it seems...

Help much appreciated!

答:
You are running python in multiple threads at the same time in Producer::run() and Consumer::run().

To be exact, you run this before locking the mutex:

```<code>boost::python::object writer = this->k->Get<boost::python::object>("write");
</code>```

Maybe you didn't realize that Boost eventually calls PyObject_GetItem when you call boost::python::object::operator[](const std::string&) in Keeper::Get. You need to move that Get-call to the correct location, after locking and before using the returned function:

```<code>{
  boost::mutex::scoped_lock l(this->k->python_keeper);
  boost::python::object writer = this->k->Get<boost::python::object>("write");
  writer(boost::python::str(os.str()));
}
</code>```

Edit: Removed Py_Finalize(). Yes you are right, boost.python doesn't like it.

Title: boost python with threads

Body:
You are running python in multiple threads at the same time in Producer::run() and Consumer::run().

To be exact, you run this before locking the mutex:

boost::python::object writer = this->k->Get<boost::python::object>("write");

Maybe you didn't realize that Boost eventually calls PyObject_GetItem when you call boost::python::object::operator[](const std::string&) in Keeper::Get. You need to move that Get-call to the correct location, after locking and before using the returned function:

{
  boost::mutex::scoped_lock l(this->k->python_keeper);
  boost::python::object writer = this->k->Get<boost::python::object>("write");
  writer(boost::python::str(os.str()));
}

Edit: Removed Py_Finalize(). Yes you are right, boost.python doesn't like it.


问:
How do I push letters to into a string?
I want to take the var ascii and put it into a string. The code only returns each char within the loop.</p>

```<code>    function rot13(str) { // LBH QVQ VG!
        var newStr = str;
        for (var i = 0; i < str.length; i++){
            var letter = str.charAt(i);
            var code = letter.charCodeAt();

            if (code > 77){
                ascii = code - 13;
            }
            else if (code === 32 ){
                ascii = code;
            }
            else{
                var ascii = code + 13;
            }
        }
    }

    rot13("SERR PBQR PNZC"); //returns FREE CODE CAMP
</code>```

答:
To answer you, you already have written the code, but just used messed up a bit here and there - </p>

```<code>   function rot13(str) { // LBH QVQ VG!
        console.log (str);
        var newStr = str;
        var ascii = "";
        for (var i = 0; i < newStr.length; i++){
            var letter = newStr.charAt(i);
            //console.log (letter);
            var code = letter.charCodeAt();
            //console.log (code);

            if (code > 77){
                ascii = code - 13;
                //console.log (ascii);
            }
            else if (code === 32 ){
                ascii = code;
                //console.log (ascii);
            }
            else{
                ascii = code + 13;
                //console.log (ascii);
            }
            var sipher = "";
            sipher = String.fromCharCode(ascii);
            newStr += sipher;

        }
        console.log (sipher);

            return newStr;
    }
</code>```

Title: How do I push letters to into a string?

Body:
I want to take the var ascii and put it into a string. The code only returns each char within the loop.

    function rot13(str) { // LBH QVQ VG!
        var newStr = str;
        for (var i = 0; i < str.length; i++){
            var letter = str.charAt(i);
            var code = letter.charCodeAt();

            if (code > 77){
                ascii = code - 13;
            }
            else if (code === 32 ){
                ascii = code;
            }
            else{
                var ascii = code + 13;
            }
        }
    }

    rot13("SERR PBQR PNZC"); //returns FREE CODE CAMP

Body:
To answer you, you already have written the code, but just used messed up a bit here and there -

   function rot13(str) { // LBH QVQ VG!
        console.log (str);
        var newStr = str;
        var ascii = "";
        for (var i = 0; i < newStr.length; i++){
            var letter = newStr.charAt(i);
            //console.log (letter);
            var code = letter.charCodeAt();
            //console.log (code);

            if (code > 77){
                ascii = code - 13;
                //console.log (ascii);
            }
            else if (code === 32 ){
                ascii = code;
                //console.log (ascii);
            }
            else{
                ascii = code + 13;
                //console.log (ascii);
            }
            var sipher = "";
            sipher = String.fromCharCode(ascii);
            newStr += sipher;

        }
        console.log (sipher);

            return newStr;
    }


问:
an efficient way to loop an slice/array in go
basically I have this:

```<code>package main

import "fmt"

type Struct1 struct {
    id   int
    name string
}

type Struct2 struct {
    id       int
    lastname string
}

type Struct3 struct {
    id   int
    real bool
}

func main() {
    var (
     s1 []Struct1
     s2 []Struct2
     s3 []Struct3
    )
    s1 = append(s1, Struct1{id: 1, name: "Eliot"}, Struct1{id: 2, name: "Tyrell"}, Struct1{id: 3, name: "Mr Robot"})
    s2 = append(s2, Struct2{id: 1, lastname: "Anderson"}, Struct2{id: 2, lastname: "Wellick"})
    s3 = append(s3, Struct3{id: 1, real: true}, Struct3{id: 2, real: true}, Struct3{id: 3, real: false})
}
</code>```

I want to show something like this:

Eliot Anderson real(true)

Tyrell Wellick real(true)

But I don't want to loop the s1 inside the s2 and then inside the s3

Example:

```<code>for i := 0; i < len(s1); i++ {
        for j := 0; j < len(s2); j++ {
            if s1[i].id == s2[j].id {
                for k := 0; k < len(s3); k++ {
                    if s2[j].id == s3[k].id {
                        // some code ...
                    }
                }
            }
        }
    }
</code>```

So, what other ways are there to doing that?

答:
The right way would be to put them in a hash(called map in Golang). That way you can get performance and you could do with only one loop iterating over id's.

Here's an example with your sample data:

```<code>package main

import (
    "fmt"
)

type Struct1 struct {
    id   int
    name string
}

type Struct2 struct {
    id       int
    lastname string
}

type Struct3 struct {
    id   int
    real bool
}

func main() {
    //var (
    //s1 []Struct1
    //      s2 []Struct2
    //  s3 []Struct3
    //  )
    s1Hash := make(map[int]Struct1)
    s2Hash := make(map[int]Struct2)
    s3Hash := make(map[int]Struct3)

    s11 := Struct1{id: 1, name: "Eliot"}
    s12 := Struct1{id: 2, name: "Tyrell"}
    s13 := Struct1{id: 3, name: "Mr Robot"}
    s1Hash[s11.id] = s11
    s1Hash[s12.id] = s12
    s1Hash[s13.id] = s13

    s21 := Struct2{id: 1, lastname: "Anderson"}
    s22 := Struct2{id: 2, lastname: "Wellick"}
    s2Hash[s21.id] = s21
    s2Hash[s22.id] = s22

    s31 := Struct3{id: 1, real: true}
    s32 := Struct3{id: 2, real: true}
    s33 := Struct3{id: 3, real: false}
    s3Hash[s31.id] = s31
    s3Hash[s32.id] = s32
    s3Hash[s33.id] = s33

    //s1 = append(s1, Struct1{id: 1, name: "Eliot"}, Struct1{id: 2, name: "Tyrell"}, Struct1{id: 3, name: "Mr Robot"})
    //s2 = append(s2, Struct2{id: 1, lastname: "Anderson"}, Struct2{id: 2, lastname: "Wellick"})
    //s3 = append(s3, Struct3{id: 1, real: true}, Struct3{id: 2, real: true}, Struct3{id: 3, real: false})

    //i to loop over possible id range
    for i := 1; i <= len(s1Hash); i++ {
        fmt.Println("i is ", i)
        if _, ok := s1Hash[i]; ok {
            fmt.Printf("Name: %s ", s1Hash[i].name)
        }

        if _, ok := s2Hash[i]; ok {
            fmt.Printf(" Lastname: %s ", s2Hash[i].lastname)
        }

        if _, ok := s3Hash[i]; ok {
            fmt.Printf(" Real: %t\n", s3Hash[i].real)
        }
        //fmt.Printf("%s %s real:%t\n", s1Hash[i].name, s2[i].lastname, s3[i].real)
    }

}
</code>```

Output:

```<code>i is  1
Name: Eliot  Lastname: Anderson  Real: true
i is  2
Name: Tyrell  Lastname: Wellick  Real: true
i is  3
Name: Mr Robot  Real: false
</code>```

Check this out on playground. Hope this helps!

p.s. : Eventually if you may delete all struct entries for some ID's and add newer ID's - you can consider adding the valid ID's into a map map[int]bool  (mymap[id] = true) and iterate over the map using range instead of the for i.. as above.

Body:
basically I have this:

package main

import "fmt"

type Struct1 struct {
    id   int
    name string
}

type Struct2 struct {
    id       int
    lastname string
}

type Struct3 struct {
    id   int
    real bool
}

func main() {
    var (
     s1 []Struct1
     s2 []Struct2
     s3 []Struct3
    )
    s1 = append(s1, Struct1{id: 1, name: "Eliot"}, Struct1{id: 2, name: "Tyrell"}, Struct1{id: 3, name: "Mr Robot"})
    s2 = append(s2, Struct2{id: 1, lastname: "Anderson"}, Struct2{id: 2, lastname: "Wellick"})
    s3 = append(s3, Struct3{id: 1, real: true}, Struct3{id: 2, real: true}, Struct3{id: 3, real: false})
}

I want to show something like this:

Eliot Anderson real(true)

Tyrell Wellick real(true)

But I don't want to loop the s1 inside the s2 and then inside the s3

Example:

for i := 0; i < len(s1); i++ {
        for j := 0; j < len(s2); j++ {
            if s1[i].id == s2[j].id {
                for k := 0; k < len(s3); k++ {
                    if s2[j].id == s3[k].id {
                        // some code ...
                    }
                }
            }
        }
    }

So, what other ways are there to doing that?

Body:
The right way would be to put them in a hash(called map in Golang). That way you can get performance and you could do with only one loop iterating over id's.

Here's an example with your sample data:

package main

import (
    "fmt"
)

type Struct1 struct {
    id   int
    name string
}

type Struct2 struct {
    id       int
    lastname string
}

type Struct3 struct {
    id   int
    real bool
}

func main() {
    //var (
    //s1 []Struct1
    //      s2 []Struct2
    //  s3 []Struct3
    //  )
    s1Hash := make(map[int]Struct1)
    s2Hash := make(map[int]Struct2)
    s3Hash := make(map[int]Struct3)

    s11 := Struct1{id: 1, name: "Eliot"}
    s12 := Struct1{id: 2, name: "Tyrell"}
    s13 := Struct1{id: 3, name: "Mr Robot"}
    s1Hash[s11.id] = s11
    s1Hash[s12.id] = s12
    s1Hash[s13.id] = s13

    s21 := Struct2{id: 1, lastname: "Anderson"}
    s22 := Struct2{id: 2, lastname: "Wellick"}
    s2Hash[s21.id] = s21
    s2Hash[s22.id] = s22

    s31 := Struct3{id: 1, real: true}
    s32 := Struct3{id: 2, real: true}
    s33 := Struct3{id: 3, real: false}
    s3Hash[s31.id] = s31
    s3Hash[s32.id] = s32
    s3Hash[s33.id] = s33

    //s1 = append(s1, Struct1{id: 1, name: "Eliot"}, Struct1{id: 2, name: "Tyrell"}, Struct1{id: 3, name: "Mr Robot"})
    //s2 = append(s2, Struct2{id: 1, lastname: "Anderson"}, Struct2{id: 2, lastname: "Wellick"})
    //s3 = append(s3, Struct3{id: 1, real: true}, Struct3{id: 2, real: true}, Struct3{id: 3, real: false})

    //i to loop over possible id range
    for i := 1; i <= len(s1Hash); i++ {
        fmt.Println("i is ", i)
        if _, ok := s1Hash[i]; ok {
            fmt.Printf("Name: %s ", s1Hash[i].name)
        }

        if _, ok := s2Hash[i]; ok {
            fmt.Printf(" Lastname: %s ", s2Hash[i].lastname)
        }

        if _, ok := s3Hash[i]; ok {
            fmt.Printf(" Real: %t\n", s3Hash[i].real)
        }
        //fmt.Printf("%s %s real:%t\n", s1Hash[i].name, s2[i].lastname, s3[i].real)
    }

}

Output:

i is  1
Name: Eliot  Lastname: Anderson  Real: true
i is  2
Name: Tyrell  Lastname: Wellick  Real: true
i is  3
Name: Mr Robot  Real: false

Check this out on playground. Hope this helps!

p.s. : Eventually if you may delete all struct entries for some ID's and add newer ID's - you can consider adding the valid ID's into a map map[int]bool  (mymap[id] = true) and iterate over the map using range instead of the for i.. as above.


问:
JSON schema: conditional dependency
I can't seem to figure out how to achieve something in JSON schema. Let's say I have two fields: status and quote.

Conditional dependencies are as follow:

IF status is ["Y", "N"], THEN quote is required

IF status is anything else from enum, THEN quote is not required

IF status is not present in JSON, THEN quote can be anything

I am trying to achieve this behaviour with the following schema:

```<code>{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "quote": {
      "type": "string",
    },

    "status": {
      "type": "string",
      "enum": ["Y", "N", "M", "A", "S"]
    }
  },

  "oneOf": [
      {
        "properties": {
          "status": {"enum": ["Y", "N"]}
        },
        "required": [
          "quote"
        ]
      },
      {
        "properties": {
          "status": {"enum": ["Y", "N", "M", "A", "S"]}
        }
      }
  ]
}
</code>```

The first two conditions work as expected, but whenever the status field is left out from the JSON, the validation fails. And the wanted behaviour is that I can have a field quote to be whatever whenever status field is not there.

How can I achieve this?

UPDATE

So I managed to achieve what I asked initially, however, I now have the additional requirement. That is, I have an additional field author that is required whenever status is ["M", "A"] and otherwise it's just optional. If status is not present, both quote and author can be anything. I tried that like follows:

```<code>{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "quote": { "type": "string" },
    "author": { "type": "string" },
    "status": { "enum": ["Y", "N", "M", "A", "S"] }
  },
  "allOf": [
    { "$ref": "#/definitions/y-or-n-requires-quote" },
    { "$ref": "#/definitions/m-or-a-requires-author" }
  ],
  "definitions": {
    "y-or-n-requires-quote": {
      "anyOf": [
        { "not": { "$ref": "#/definitions/status-is-y-or-n" } },
        { "required": ["quote"] }
      ]
    },
    "m-or-a-requires-author": {
      "anyOf": [
        { "not": { "$ref": "#/definitions/status-is-m-or-a" } },
        { "required": ["author"] }
      ]
    },

    "status-is-y-or-n": {
      "properties": {
        "status": { "enum": ["Y", "N"] }
      }
    },

    "status-is-m-or-a": {
      "properties": {
        "status": { "enum": ["M", "A"] }
      }
    }
  }
}
</code>```

However, using this schema doesn't work for JSON where status is not present.

答:
You need to use a boolean logic concept called implication (!A or B).  It's a way of expressing an if-then constraint.  In this case, what we want to express is: either status is not "Y"/"N" or quote is required.</p>

```<code>{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "quote": { "type": "string" },
    "status": { "enum": ["Y", "N", "M", "A", "S"] }
  },
  "allOf": [
    { "$ref": "#/definitions/y-or-n-requires-quote" }
  ],
  "definitions": {
    "y-or-n-requires-quote": {
      "anyOf": [
        { "not": { "$ref": "#/definitions/status-is-y-or-n" } },
        { "required": ["quote"] }
      ]
    },
    "status-is-y-or-n": {
      "properties": {
        "status": { "enum": ["Y", "N"] }
      },
      "required": ["status"]
    }
  }
}
</code>```

Title: JSON schema: conditional dependency

Body:
I can't seem to figure out how to achieve something in JSON schema. Let's say I have two fields: status and quote.

Conditional dependencies are as follow:

IF status is ["Y", "N"], THEN quote is required

IF status is anything else from enum, THEN quote is not required

IF status is not present in JSON, THEN quote can be anything

I am trying to achieve this behaviour with the following schema:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "quote": {
      "type": "string",
    },

    "status": {
      "type": "string",
      "enum": ["Y", "N", "M", "A", "S"]
    }
  },

  "oneOf": [
      {
        "properties": {
          "status": {"enum": ["Y", "N"]}
        },
        "required": [
          "quote"
        ]
      },
      {
        "properties": {
          "status": {"enum": ["Y", "N", "M", "A", "S"]}
        }
      }
  ]
}

The first two conditions work as expected, but whenever the status field is left out from the JSON, the validation fails. And the wanted behaviour is that I can have a field quote to be whatever whenever status field is not there.

How can I achieve this?

UPDATE

So I managed to achieve what I asked initially, however, I now have the additional requirement. That is, I have an additional field author that is required whenever status is ["M", "A"] and otherwise it's just optional. If status is not present, both quote and author can be anything. I tried that like follows:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "quote": { "type": "string" },
    "author": { "type": "string" },
    "status": { "enum": ["Y", "N", "M", "A", "S"] }
  },
  "allOf": [
    { "$ref": "#/definitions/y-or-n-requires-quote" },
    { "$ref": "#/definitions/m-or-a-requires-author" }
  ],
  "definitions": {
    "y-or-n-requires-quote": {
      "anyOf": [
        { "not": { "$ref": "#/definitions/status-is-y-or-n" } },
        { "required": ["quote"] }
      ]
    },
    "m-or-a-requires-author": {
      "anyOf": [
        { "not": { "$ref": "#/definitions/status-is-m-or-a" } },
        { "required": ["author"] }
      ]
    },

    "status-is-y-or-n": {
      "properties": {
        "status": { "enum": ["Y", "N"] }
      }
    },

    "status-is-m-or-a": {
      "properties": {
        "status": { "enum": ["M", "A"] }
      }
    }
  }
}

However, using this schema doesn't work for JSON where status is not present.

Body:
You need to use a boolean logic concept called implication (!A or B).  It's a way of expressing an if-then constraint.  In this case, what we want to express is: either status is not "Y"/"N" or quote is required.

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "quote": { "type": "string" },
    "status": { "enum": ["Y", "N", "M", "A", "S"] }
  },
  "allOf": [
    { "$ref": "#/definitions/y-or-n-requires-quote" }
  ],
  "definitions": {
    "y-or-n-requires-quote": {
      "anyOf": [
        { "not": { "$ref": "#/definitions/status-is-y-or-n" } },
        { "required": ["quote"] }
      ]
    },
    "status-is-y-or-n": {
      "properties": {
        "status": { "enum": ["Y", "N"] }
      },
      "required": ["status"]
    }
  }
}