问:
embedding image into jupyter notebook and exporting to HTML
I am running Python 3.7 on Windows using pycharm. I have a jupyter notebook and I would like to embed an image into the notebook. I know all the ways of doing standard embedding with markdown language, BUT ideally what I want is:

a.  Embed the image via markdown language, i.e. the notebook cell is in 'markdown' state, not 'Code' state, AND ALSO

b.  Have it able to export to HTML and retain that image in the HTML file. i.e. on the notebook. I want to click File -> Download as -> HTML (.html), save the notebook file in .html format, and then when I send it to my buddy, the image that I attached is in the notebook, and he sees it.

I know i could do this in a cell ('code'):

```<code>from IPython.display import Image
Image(filename="myfile.jpg")
</code>```

but I do not want to use 'Code', since when I send to my buddy, he will see the In [] code statement and the Out [] of the image in the notebook html file.

Note: This would be an image that was on my laptop that I would want in the html formatted exported notebook. It is NOT on the web where he could refer to it with a www type statement. Unless I'm crazy, there is no way to do this with markdown command in a cell, the only way to do it (with the image embedded 'permanently' into the .html format of the notebook), would be via a cell that was in 'Code' celltype.

答:
You can install the Unofficial Jupyter Notebook Extensions.

It has some interesting extensions (e.g. spell checker, collapsible headings, ...). One of the extensions is Export HTML With Embedded Images which exactly does what you want.

To install Nbextensions using pip do the following:

```<code>$ pip install jupyter_contrib_nbextensions
$ pip install jupyter_nbextensions_configurator
$ jupyter contrib nbextension install --user
$ jupyter nbextensions_configurator enable --user
</code>```

Then you will see in your Jupyter homepage a new tab (Nbextensions), where you can enable and configure different extension.

After enabling the "Export HTML With Embedded Images", you will see the corresponding option in the "File-Download as" menu.

Body:
I am running Python 3.7 on Windows using pycharm. I have a jupyter notebook and I would like to embed an image into the notebook. I know all the ways of doing standard embedding with markdown language, BUT ideally what I want is:

a.  Embed the image via markdown language, i.e. the notebook cell is in 'markdown' state, not 'Code' state, AND ALSO

b.  Have it able to export to HTML and retain that image in the HTML file. i.e. on the notebook. I want to click File -> Download as -> HTML (.html), save the notebook file in .html format, and then when I send it to my buddy, the image that I attached is in the notebook, and he sees it.

I know i could do this in a cell ('code'):

from IPython.display import Image
Image(filename="myfile.jpg")

but I do not want to use 'Code', since when I send to my buddy, he will see the In [] code statement and the Out [] of the image in the notebook html file.

Note: This would be an image that was on my laptop that I would want in the html formatted exported notebook. It is NOT on the web where he could refer to it with a www type statement. Unless I'm crazy, there is no way to do this with markdown command in a cell, the only way to do it (with the image embedded 'permanently' into the .html format of the notebook), would be via a cell that was in 'Code' celltype.

Body:
You can install the Unofficial Jupyter Notebook Extensions.

It has some interesting extensions (e.g. spell checker, collapsible headings, ...). One of the extensions is Export HTML With Embedded Images which exactly does what you want.

To install Nbextensions using pip do the following:

$ pip install jupyter_contrib_nbextensions
$ pip install jupyter_nbextensions_configurator
$ jupyter contrib nbextension install --user
$ jupyter nbextensions_configurator enable --user

Then you will see in your Jupyter homepage a new tab (Nbextensions), where you can enable and configure different extension.

After enabling the "Export HTML With Embedded Images", you will see the corresponding option in the "File-Download as" menu.


来源: stackexchange

问:
NODEJS How do I perform an action when URL response status is 404?
I am making a discord bot and I want to make a command that sends 3 random characters and then puts those characters at the end of a url to check if it exists (in this case I am using steam accounts to check if the id is taken) but I need to make it so that when the response status is 404 it will send a message to say the ID is not taken.

```<code>var urlExists = require('url-exists');

      //3CHAR
   else if (message.content == "+3char") {
     message.channel.send(getRandomString(3));

   var theURL = "https://steamcommunity.com/id/" + message.channel.lastmessage;

         urlExists("theURL");

      if (response.status != 404) {
      return;

    }

    else {message.channel.send("`URL is not taken`");}

}
</code>```

This is what I have right now, however I get the error 'response is not defined'.
Any suggestion would be gladly appreciated!

答:
Your running into an async issue.  You need to pass in a callback function to urlExists.  The callback function executes once the urlExists object finishes executing.

https://www.npmjs.com/package/url-exists

```<code>var urlExists = require('url-exists');

urlExists('https://www.google.com', function(err, exists) {
  console.log(exists); // true
});

urlExists('https://www.fakeurl.notreal', function(err, exists) {
  console.log(exists); // false
});
</code>```

In your case, you'd want to do something along the lines of:

```<code>var urlExists = require('url-exists');

var theURL = "https://steamcommunity.com/id/" + message.channel.lastmessage;

urlExists("theURL", (err, exists) => {
  if (err) {
    // handle error
  }

  if (exists) {
    message.channel.send("`URL is not taken`");
  } else {
    // do something when the URL does not exist
  }
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am making a discord bot and I want to make a command that sends 3 random characters and then puts those characters at the end of a url to check if it exists (in this case I am using steam accounts to check if the id is taken) but I need to make it so that when the response status is 404 it will send a message to say the ID is not taken.

var urlExists = require('url-exists');

      //3CHAR
   else if (message.content == "+3char") {
     message.channel.send(getRandomString(3));

   var theURL = "https://steamcommunity.com/id/" + message.channel.lastmessage;

         urlExists("theURL");

      if (response.status != 404) {
      return;

    }

    else {message.channel.send("`URL is not taken`");}

}

This is what I have right now, however I get the error 'response is not defined'.
Any suggestion would be gladly appreciated!

Body:
Your running into an async issue.  You need to pass in a callback function to urlExists.  The callback function executes once the urlExists object finishes executing.

https://www.npmjs.com/package/url-exists

var urlExists = require('url-exists');

urlExists('https://www.google.com', function(err, exists) {
  console.log(exists); // true
});

urlExists('https://www.fakeurl.notreal', function(err, exists) {
  console.log(exists); // false
});

In your case, you'd want to do something along the lines of:

var urlExists = require('url-exists');

var theURL = "https://steamcommunity.com/id/" + message.channel.lastmessage;

urlExists("theURL", (err, exists) => {
  if (err) {
    // handle error
  }

  if (exists) {
    message.channel.send("`URL is not taken`");
  } else {
    // do something when the URL does not exist
  }
});


问:
Is there a standard way for Javascript classes to refer to each other?
I was wondering, is there a standard way for class properties and methods to refer to each other in their declaration? For example:

```<code>class A {
  methodA(){
    b.methodB()
    ...
  }
}

class B {
  methodB(){...}
}

const a = new A();
const b = new B();

///will throw ReferenceError: Cannot access 'b' before initialization;
</code>```

I understand that you can add methodA in later after all class/object declarations, but it gets quite untidy after many repetitions, which I feel like defeats the purpose of classes. Or that you can delay the reference through some other means. Is there a standard way to do this?

答:
First, Javascript has no "classes". The class keyword is just there to make it look familiar. It should have been proto instead of class.

It's better to use mixins. Also it very much depends on whether to be able to propagate changes to methodB to all decedents of A, or if you want that.

See also "prose-like syntax"

No propagation - copying

If you don't need propagation and you need to copy a lot of methods over:

```<code>const A = {
    name: 'I am A.'
}

const B = {
    name: 'I am B.', // this will overwrite A when we #assign. so be careful to assign it back
    methodB() {
        console.log(`${this.name} - foo`)
    }
}

const a = Object.create(A)

Object.assign(a, B)
a.name = A.name

// methodB is changed but it won't propagate.
B.methodB = function() {
    console.log(`${this.name} - bar`)
}

a.methodB() // I am A. - foo
B.methodB() // I am B. - bar
</code>```

With propagation.

And if you only need 1 or a few methods:

```<code>const A = {
    name: 'I am A.'
}

const B = {
    name: 'I am B.',
    methodB() {
        console.log(`${this.name} - foo`)
    }
}

const a = Object.create(A)

a.methodA = function() {
    B.methodB.call(this)
}

B.methodB = function() {
    console.log(`${this.name} - bar`)
}

a.methodA() // I am A. - bar
B.methodB() // I am B. - bar
</code>```

Body:
I was wondering, is there a standard way for class properties and methods to refer to each other in their declaration? For example:

class A {
  methodA(){
    b.methodB()
    ...
  }
}

class B {
  methodB(){...}
}

const a = new A();
const b = new B();

///will throw ReferenceError: Cannot access 'b' before initialization;

I understand that you can add methodA in later after all class/object declarations, but it gets quite untidy after many repetitions, which I feel like defeats the purpose of classes. Or that you can delay the reference through some other means. Is there a standard way to do this?

Body:
First, Javascript has no "classes". The class keyword is just there to make it look familiar. It should have been proto instead of class.

It's better to use mixins. Also it very much depends on whether to be able to propagate changes to methodB to all decedents of A, or if you want that.

See also "prose-like syntax"

No propagation - copying

If you don't need propagation and you need to copy a lot of methods over:

const A = {
    name: 'I am A.'
}

const B = {
    name: 'I am B.', // this will overwrite A when we #assign. so be careful to assign it back
    methodB() {
        console.log(`${this.name} - foo`)
    }
}

const a = Object.create(A)

Object.assign(a, B)
a.name = A.name

// methodB is changed but it won't propagate.
B.methodB = function() {
    console.log(`${this.name} - bar`)
}

a.methodB() // I am A. - foo
B.methodB() // I am B. - bar

With propagation.

And if you only need 1 or a few methods:

const A = {
    name: 'I am A.'
}

const B = {
    name: 'I am B.',
    methodB() {
        console.log(`${this.name} - foo`)
    }
}

const a = Object.create(A)

a.methodA = function() {
    B.methodB.call(this)
}

B.methodB = function() {
    console.log(`${this.name} - bar`)
}

a.methodA() // I am A. - bar
B.methodB() // I am B. - bar


问:
HTML Validation: Why is it not valid to put an interactive element inside an interactive element?
Disclaimer: I understand that it is not valid HTML. I am trying to understand why is it not allowed?

W3C suggests that an interactive element like button or a mustn't contain another interactive element.

I could find a lot of resources mentioning this rule and some workarounds, also some resources related to how this impacts accessibility and screenreaders, but almost all of those resources talk about the fact that this is a requirement but do not explain why.

https://adrianroselli.com/2016/12/be-wary-of-nesting-roles.html

https://codepen.io/vloux/pen/wXGyOv

Nesting  inside <button> doesn't work in Firefox

https://github.com/dequelabs/axe-core/issues/601

I wasn't really able to find an explanation for why is it not allowed? does it lead to any usability problems?

This is a related question:
Why should interactive element not be used within an anchor?

The accepted answer is satisfactory but is not enough to make this rule a requirement. The described situation can be avoided using proper event handling.

Also, if nested interactive content is invalid, how are we supposed to have something like this:

A card which is clickable as a whole, and also has a clickable secondary CTA inside it.
I know a workaround would be to have a primary and secondary CTA inside the card, but shouldn't the above be allowed as well?

Here is a fiddle:
https://jsfiddle.net/t9qbwas5/2/

```<code><button type="button" class="card">
  The card itself is the primary CTA.
  <br/>
  <br/>
  some important content to read through.
  some important content to read through.
  some important content to read through.
  <div class="cta">
   Secondary CTA
  </div>
</button>

.cta {
  padding: 4px;
  background: #00a9a9;
  color: white;
  width: 80px;
  margin: auto;
  margin-top: 8px;
  margin-bottom: 8px;
}

.card {
  width: 200px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;
}
</code>```

In the above example, I am achieving this by using a clickable div inside the button, but that is not semantic (?) and also functionality wise, it is an interactive element inside another one. I am trying to understand that even if I use this workaround, is it fundamentally wrong to have nested interactive elements? is it a bad design/usability practice?

答:
A card which is clickable as a whole, and also has a clickable secondary CTA inside it.

Although visually imaginable and technically possible, it's not accessible for assistive technologies, like screenreaders

Let's make a simple example:

```<code><button>
    Click for action 1
    <button>Click for action 2</button>
</button>
</code>```

The accessible name for the first <button> would be "Click for action1 Click for action 2". And if you define an aria-label="Click for action 1", then the inner button element would not be read at all.

If you really want to make a whole element clickable, you can perfectly use javascript and still be accessible

```<code><div class="outer">
  <button type="button" class="card">
    The card itself is the primary CTA.
  </button>
  <br/>
  <br/>
  some important content to read through.
  some important content to read through.
  some important content to read through.

  <button class="cta">
   Secondary CTA
  </button>
</div>

<script>
$(".outer").on("click", function() {$(".card").click()});
</script>

<style>
.outer {cursor: pointer}
</style>
</code>```

With this example, you will correctly have two buttons rendered to screenreaders, the first one "The card itselfis the primary CTA" and the second one "Secondary CTA", while a mouse click on the whole card would lead the same action as the first button.

Body:
Disclaimer: I understand that it is not valid HTML. I am trying to understand why is it not allowed?

W3C suggests that an interactive element like button or a mustn't contain another interactive element.

I could find a lot of resources mentioning this rule and some workarounds, also some resources related to how this impacts accessibility and screenreaders, but almost all of those resources talk about the fact that this is a requirement but do not explain why.

https://adrianroselli.com/2016/12/be-wary-of-nesting-roles.html

https://codepen.io/vloux/pen/wXGyOv

Nesting  inside <button> doesn't work in Firefox

https://github.com/dequelabs/axe-core/issues/601

I wasn't really able to find an explanation for why is it not allowed? does it lead to any usability problems?

This is a related question:
Why should interactive element not be used within an anchor?

The accepted answer is satisfactory but is not enough to make this rule a requirement. The described situation can be avoided using proper event handling.

Also, if nested interactive content is invalid, how are we supposed to have something like this:

A card which is clickable as a whole, and also has a clickable secondary CTA inside it.
I know a workaround would be to have a primary and secondary CTA inside the card, but shouldn't the above be allowed as well?

Here is a fiddle:
https://jsfiddle.net/t9qbwas5/2/

<button type="button" class="card">
  The card itself is the primary CTA.

  some important content to read through.
  some important content to read through.
  some important content to read through.

   Secondary CTA

</button>

.cta {
  padding: 4px;
  background: #00a9a9;
  color: white;
  width: 80px;
  margin: auto;
  margin-top: 8px;
  margin-bottom: 8px;
}

.card {
  width: 200px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;
}

In the above example, I am achieving this by using a clickable div inside the button, but that is not semantic (?) and also functionality wise, it is an interactive element inside another one. I am trying to understand that even if I use this workaround, is it fundamentally wrong to have nested interactive elements? is it a bad design/usability practice?

Body:
A card which is clickable as a whole, and also has a clickable secondary CTA inside it.

Although visually imaginable and technically possible, it's not accessible for assistive technologies, like screenreaders

Let's make a simple example:

<button>
    Click for action 1
    <button>Click for action 2</button>
</button>

The accessible name for the first <button> would be "Click for action1 Click for action 2". And if you define an aria-label="Click for action 1", then the inner button element would not be read at all.

If you really want to make a whole element clickable, you can perfectly use javascript and still be accessible

<div class="outer">
  <button type="button" class="card">
    The card itself is the primary CTA.
  </button>
  <br/>
  <br/>
  some important content to read through.
  some important content to read through.
  some important content to read through.

  <button class="cta">
   Secondary CTA
  </button>
</div>

<script>
$(".outer").on("click", function() {$(".card").click()});
</script>

<style>
.outer {cursor: pointer}
</style>

With this example, you will correctly have two buttons rendered to screenreaders, the first one "The card itselfis the primary CTA" and the second one "Secondary CTA", while a mouse click on the whole card would lead the same action as the first button.


问:
How to get a sum of an array column field in an angular array 9.1.9?
I amI am using Angular 9.1.9 and Html. I want to sum or total a nested array field and show in row.

I have a array list ('adherant') with multiple fields  . I want to sum of an array columns field {{ Montant total }} and show in a text total like the photo.using Angular 9 and Html. I want to sum of an array columns field {{ Montant total }} and show in a text total like the photo.
if there is a pipe methode , or filter !

files

interface adher {
  four?: string;
  mont: number;
  nombr: number;
  monmois: number;
  }

const adherant: adher[] = [
  {
    four: 'Russia',
    mont: 444,
    nombr: 17075200,
    monmois: 146989754
  },
  {
    four: 'Russasia',
    mont: 444,
    nombr: 17075200,
    monmois: 146989754
  },{
    four: 'ssss',
    mont: 444,
    nombr: 17075200,
    monmois: 146989754
  },{
    four: 'Russddddia',
    mont: 444,
    nombr: 17075200,
    monmois: 146989754
  },{
    four: 'sdsd',
    mont: 444,
    nombr: 17075200,
    monmois: 146989754
  },{
    four: 'Russcxcxcxia',
    mont: 444,
    nombr: 17075200,
    monmois: 146989754
  }
];```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="table table-striped">

                        <thead>

                            <tr>
                                <th scope="col">Fournisseur</th>
                                <th scope="col">Montant totale</th>
                                <th scope="col">Nombre de mois</th>
                                <th scope="col">Montant par mois</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr *ngFor="let adh of adherant |filter:search">
                                <th scope="row">{{ adh.four }}</th>
                                <td>
                                    {{ adh.mont }}
                                </td>
                                <td>{{ adh.nombr | number}}</td>
                                <td>{{ adh.monmois | number }}</td>
                            </tr>
                        </tbody>
                    </table></code>```

答:
In component declare :-

public total;

this.total= this.adherant.reduce((prev,next)=>prev+next.mont,0);

Use it like {{total}} in template

Body:
I amI am using Angular 9.1.9 and Html. I want to sum or total a nested array field and show in row.

I have a array list ('adherant') with multiple fields  . I want to sum of an array columns field {{ Montant total }} and show in a text total like the photo.using Angular 9 and Html. I want to sum of an array columns field {{ Montant total }} and show in a text total like the photo.
if there is a pipe methode , or filter !

files

interface adher {
  four?: string;
  mont: number;
  nombr: number;
  monmois: number;
  }

const adherant: adher[] = [
  {
    four: 'Russia',
    mont: 444,
    nombr: 17075200,
    monmois: 146989754
  },
  {
    four: 'Russasia',
    mont: 444,
    nombr: 17075200,
    monmois: 146989754
  },{
    four: 'ssss',
    mont: 444,
    nombr: 17075200,
    monmois: 146989754
  },{
    four: 'Russddddia',
    mont: 444,
    nombr: 17075200,
    monmois: 146989754
  },{
    four: 'sdsd',
    mont: 444,
    nombr: 17075200,
    monmois: 146989754
  },{
    four: 'Russcxcxcxia',
    mont: 444,
    nombr: 17075200,
    monmois: 146989754
  }
];

                                Fournisseur
                                Montant totale
                                Nombre de mois
                                Montant par mois

                                {{ adh.four }}

                                    {{ adh.mont }}

                                {{ adh.nombr | number}}
                                {{ adh.monmois | number }}


问:
Stripe creating multiple phases in PHP
I am trying to create multiple phases using Stripe for a very specific use case. Running the below code using the Stripe Billings API doesn't actually create multiple phases. It only creates a single phase (the last one).

```<code>$schedule = \Stripe\SubscriptionSchedule::create([
  'customer' => 'cus_HMDwmb8iAV0X7k',
  'start_date' => 'now',
  'end_behavior' => 'cancel',
    'phases' => [
      [
        'end_date' => 1592910720,
        'proration_behavior' => 'none',
        'plans' => [
          [
            'price_data' => [
              'unit_amount' => 5000,
              'currency' => 'usd',
              'product' => 'prod_HMrCxIwor5bbjO',
              'recurring' => [
                  'interval' => 'year',
              ],
            ],
          ],
        ],
      ],
    ],

    'phases' => [
      [
        'end_date' => 1594850400,
        'proration_behavior' => 'none',
        'plans' => [
          [
            'price_data' => [
              'unit_amount' => 6000,
              'currency' => 'usd',
              'product' => 'prod_HMrCxIwor5bbjO',
              'recurring' => [
                  'interval' => 'year',
              ],
            ],
          ],
        ],
      ],
    ],

]);
</code>```

A similar request using Curl works fine:

```<code>curl https://api.stripe.com/v1/subscription_schedules \
  -u sk_test_xxx: \
  -d customer=cus_HMDwmb8iAV0X7k \
  -d start_date=now \
  -d end_behavior=cancel \
  -d phases[0][plans][0][price_data][product]=prod_HMrCxIwor5bbjO \
  -d phases[0][plans][0][price_data][currency]=usd \
  -d phases[0][plans][0][price_data][unit_amount]=1000 \
  -d phases[0][plans][0][price_data][recurring][interval]=year \
  -d phases[0][end_date]=1592043010 \
  -d phases[0][proration_behavior]=none \
  -d phases[1][plans][0][price_data][product]=prod_HMrCxIwor5bbjO \
  -d phases[1][plans][0][price_data][currency]=usd \
  -d phases[1][plans][0][price_data][unit_amount]=15000 \
  -d phases[1][plans][0][price_data][recurring][interval]=year \
  -d phases[1][end_date]=1592910720 \
  -d phases[1][proration_behavior]=none \
  -d phases[2][plans][0][price_data][product]=prod_HMrCxIwor5bbjO \
  -d phases[2][plans][0][price_data][currency]=usd \
  -d phases[2][plans][0][price_data][unit_amount]=20000 \
  -d phases[2][plans][0][price_data][recurring][interval]=year \
  -d phases[2][end_date]=1594850400 \
  -d phases[2][proration_behavior]=none \
  -d phases[3][plans][0][price_data][product]=prod_HMrCxIwor5bbjO \
  -d phases[3][plans][0][price_data][currency]=usd \
  -d phases[3][plans][0][price_data][unit_amount]=35000 \
  -d phases[3][plans][0][price_data][recurring][interval]=year \
  -d phases[3][end_date]=1595851200 \
  -d phases[3][proration_behavior]=none \
  -d phases[4][plans][0][price_data][product]=prod_HMrCxIwor5bbjO \
  -d phases[4][plans][0][price_data][currency]=usd \
  -d phases[4][plans][0][price_data][unit_amount]=21000 \
  -d phases[4][plans][0][price_data][recurring][interval]=day \
  -d phases[4][end_date]=1597021320 \
  -d phases[4][proration_behavior]=none
</code>```

The only difference I see is that on the Curl request I am explicitly passing the phase number.

Any help is appreciated.

答:
In your php call you are specifying the phases parameter twice. So only the second phases definition is being used to create the subscription schedule. The fix here is to move all the phases under a single array and parameter as follows:

```<code>$schedule = \Stripe\SubscriptionSchedule::create([
  'customer' => $customer->id,
  'start_date' => 'now',
  'end_behavior' => 'cancel',
    'phases' => [
      [
        'end_date' => 1592910720,
        'proration_behavior' => 'none',
        'plans' => [
          [
            'price_data' => [
              'unit_amount' => 5000,
              'currency' => 'usd',
              'product' => $product->id,
              'recurring' => [
                  'interval' => 'year',
              ],
            ],
          ],
        ],
      ],
      [
        'end_date' => 1594850400,
        'proration_behavior' => 'none',
        'plans' => [
          [
            'price_data' => [
              'unit_amount' => 6000,
              'currency' => 'usd',
              'product' => $product->id,
              'recurring' => [
                  'interval' => 'year',
              ],
            ],
          ],
        ],
      ],
    ],
]);
</code>```

The only difference I see is that on the Curl request I am explicitly
  passing the phase number.

It's more that you are passing in the phase index in the phases array. You have to be explicit about this in cURL, but in php you can just add each element to an array and the indexes are implied.

Title: Stripe creating multiple phases in PHP

Body:
I am trying to create multiple phases using Stripe for a very specific use case. Running the below code using the Stripe Billings API doesn't actually create multiple phases. It only creates a single phase (the last one).

$schedule = \Stripe\SubscriptionSchedule::create([
  'customer' => 'cus_HMDwmb8iAV0X7k',
  'start_date' => 'now',
  'end_behavior' => 'cancel',
    'phases' => [
      [
        'end_date' => 1592910720,
        'proration_behavior' => 'none',
        'plans' => [
          [
            'price_data' => [
              'unit_amount' => 5000,
              'currency' => 'usd',
              'product' => 'prod_HMrCxIwor5bbjO',
              'recurring' => [
                  'interval' => 'year',
              ],
            ],
          ],
        ],
      ],
    ],

    'phases' => [
      [
        'end_date' => 1594850400,
        'proration_behavior' => 'none',
        'plans' => [
          [
            'price_data' => [
              'unit_amount' => 6000,
              'currency' => 'usd',
              'product' => 'prod_HMrCxIwor5bbjO',
              'recurring' => [
                  'interval' => 'year',
              ],
            ],
          ],
        ],
      ],
    ],

]);

A similar request using Curl works fine:

curl https://api.stripe.com/v1/subscription_schedules \
  -u sk_test_xxx: \
  -d customer=cus_HMDwmb8iAV0X7k \
  -d start_date=now \
  -d end_behavior=cancel \
  -d phases[0][plans][0][price_data][product]=prod_HMrCxIwor5bbjO \
  -d phases[0][plans][0][price_data][currency]=usd \
  -d phases[0][plans][0][price_data][unit_amount]=1000 \
  -d phases[0][plans][0][price_data][recurring][interval]=year \
  -d phases[0][end_date]=1592043010 \
  -d phases[0][proration_behavior]=none \
  -d phases[1][plans][0][price_data][product]=prod_HMrCxIwor5bbjO \
  -d phases[1][plans][0][price_data][currency]=usd \
  -d phases[1][plans][0][price_data][unit_amount]=15000 \
  -d phases[1][plans][0][price_data][recurring][interval]=year \
  -d phases[1][end_date]=1592910720 \
  -d phases[1][proration_behavior]=none \
  -d phases[2][plans][0][price_data][product]=prod_HMrCxIwor5bbjO \
  -d phases[2][plans][0][price_data][currency]=usd \
  -d phases[2][plans][0][price_data][unit_amount]=20000 \
  -d phases[2][plans][0][price_data][recurring][interval]=year \
  -d phases[2][end_date]=1594850400 \
  -d phases[2][proration_behavior]=none \
  -d phases[3][plans][0][price_data][product]=prod_HMrCxIwor5bbjO \
  -d phases[3][plans][0][price_data][currency]=usd \
  -d phases[3][plans][0][price_data][unit_amount]=35000 \
  -d phases[3][plans][0][price_data][recurring][interval]=year \
  -d phases[3][end_date]=1595851200 \
  -d phases[3][proration_behavior]=none \
  -d phases[4][plans][0][price_data][product]=prod_HMrCxIwor5bbjO \
  -d phases[4][plans][0][price_data][currency]=usd \
  -d phases[4][plans][0][price_data][unit_amount]=21000 \
  -d phases[4][plans][0][price_data][recurring][interval]=day \
  -d phases[4][end_date]=1597021320 \
  -d phases[4][proration_behavior]=none

The only difference I see is that on the Curl request I am explicitly passing the phase number.

Any help is appreciated.

Body:
In your php call you are specifying the phases parameter twice. So only the second phases definition is being used to create the subscription schedule. The fix here is to move all the phases under a single array and parameter as follows:

$schedule = \Stripe\SubscriptionSchedule::create([
  'customer' => $customer->id,
  'start_date' => 'now',
  'end_behavior' => 'cancel',
    'phases' => [
      [
        'end_date' => 1592910720,
        'proration_behavior' => 'none',
        'plans' => [
          [
            'price_data' => [
              'unit_amount' => 5000,
              'currency' => 'usd',
              'product' => $product->id,
              'recurring' => [
                  'interval' => 'year',
              ],
            ],
          ],
        ],
      ],
      [
        'end_date' => 1594850400,
        'proration_behavior' => 'none',
        'plans' => [
          [
            'price_data' => [
              'unit_amount' => 6000,
              'currency' => 'usd',
              'product' => $product->id,
              'recurring' => [
                  'interval' => 'year',
              ],
            ],
          ],
        ],
      ],
    ],
]);

The only difference I see is that on the Curl request I am explicitly
  passing the phase number.

It's more that you are passing in the phase index in the phases array. You have to be explicit about this in cURL, but in php you can just add each element to an array and the indexes are implied.


问:
Java date time subtraction
String date1 = "2020/05/08 16.38.37"
String date2 = "2020/04/08 20.18.10"

I wish to subtract complete date1 with complete date2 (date and time both included) and get the result in hours  in java .
How to proceed ?

答:
java.time

First don’t keep your dates and times as strings in your program. Just as you don’t use strings for keeping your numbers and Boolean values (I hope), you shouldn’t for dates and times either. Use proper date and time types from java.time, the modern Java date and time API.

Assuming that your dates and times are in some well-defined time zone, I suggest using ZonedDateTime for them.

```<code>    ZoneId zone = ZoneId.of("America/Montreal");
    ZonedDateTime dateTime1 = ZonedDateTime.of(2020, 5, 8, 16, 38, 37, 0, zone);
    ZonedDateTime dateTime2 = ZonedDateTime.of(2020, 4, 8, 20, 18, 10, 0, zone);
</code>```

Finding the difference is a one-liner:

```<code>    long diffHours = ChronoUnit.HOURS.between(dateTime2, dateTime1);

    System.out.println("Difference in hours: " + diffHours);
</code>```

Output from this example snippet is:

```<code>Difference in hours: 716
</code>```

Please insert your desired time zone where I put America/Montreal. Choosing a different time zone may cause us to get an hour more or fewer if the transition to or from summer time (DST) lies between the two dates.

Parsing date-time input

If your dates and times are string input, the first thing you need to do with them is parse them. An example:

```<code>    DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("uuuu/MM/dd HH.mm.ss");

    String string1 = "2020/05/08 16.38.37";
    String string2 = "2020/04/08 20.18.10";

    ZonedDateTime dateTime1 = LocalDateTime.parse(string1, inputFormatter).atZone(zone);
    ZonedDateTime dateTime2 = LocalDateTime.parse(string2, inputFormatter).atZone(zone);

    System.out.println("Date and time 1: " + dateTime1);
    System.out.println("Date and time 2: " + dateTime2);`
</code>```

```<code>Date and time 1: 2020-05-08T16:38:37-04:00[America/Montreal]
Date and time 2: 2020-04-08T20:18:10-04:00[America/Montreal]
</code>```

Link

Oracle tutorial: Date Time explaining how to use java.time.

Title: Java date time subtraction

Body:
java.time

First don’t keep your dates and times as strings in your program. Just as you don’t use strings for keeping your numbers and Boolean values (I hope), you shouldn’t for dates and times either. Use proper date and time types from java.time, the modern Java date and time API.

Assuming that your dates and times are in some well-defined time zone, I suggest using ZonedDateTime for them.

    ZoneId zone = ZoneId.of("America/Montreal");
    ZonedDateTime dateTime1 = ZonedDateTime.of(2020, 5, 8, 16, 38, 37, 0, zone);
    ZonedDateTime dateTime2 = ZonedDateTime.of(2020, 4, 8, 20, 18, 10, 0, zone);

Finding the difference is a one-liner:

    long diffHours = ChronoUnit.HOURS.between(dateTime2, dateTime1);

    System.out.println("Difference in hours: " + diffHours);

Output from this example snippet is:

Difference in hours: 716

Please insert your desired time zone where I put America/Montreal. Choosing a different time zone may cause us to get an hour more or fewer if the transition to or from summer time (DST) lies between the two dates.

Parsing date-time input

If your dates and times are string input, the first thing you need to do with them is parse them. An example:

    DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("uuuu/MM/dd HH.mm.ss");

    String string1 = "2020/05/08 16.38.37";
    String string2 = "2020/04/08 20.18.10";

    ZonedDateTime dateTime1 = LocalDateTime.parse(string1, inputFormatter).atZone(zone);
    ZonedDateTime dateTime2 = LocalDateTime.parse(string2, inputFormatter).atZone(zone);

    System.out.println("Date and time 1: " + dateTime1);
    System.out.println("Date and time 2: " + dateTime2);`

Date and time 1: 2020-05-08T16:38:37-04:00[America/Montreal]
Date and time 2: 2020-04-08T20:18:10-04:00[America/Montreal]

Link

Oracle tutorial: Date Time explaining how to use java.time.


问:
JavaScript open in a new window, not tab
I have a select box that calls window.open(url) when an item is selected.  Firefox will open the page in a new tab by default.  However, I would like the page to open in a new window, not a new tab.

How can I accomplish this?

答:
Interestingly, I found that if you pass in an empty string (as opposed to a null string, or a list of properties) for the third attribute of window.open, it would open in a new tab for Chrome, Firefox, and IE.  If absent, the behavior was different.

So, this is my new call:

```<code> window.open(url, windowName, '');
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Interestingly, I found that if you pass in an empty string (as opposed to a null string, or a list of properties) for the third attribute of window.open, it would open in a new tab for Chrome, Firefox, and IE.  If absent, the behavior was different.

So, this is my new call:

 window.open(url, windowName, '');

ContentLicense: CC BY-SA 3.0


问:
Using column value as dataframe index in list dataframes (Map or lapply with seq_along)?
I have a list of dataframes list1 and need a new column 'mn' in each dataframe that is the mean of a conditional number of columns based on the value in another column num plus one. So, for num=3 the new column would be the mean of the first four columns. For the example below

```<code>df1 <- data.frame(num= c(3, 1, 1, 1, 2), d1= c(1, 17, 17, 17, 15), d2= c(1, 15, 15, 15, 21), d3= c(6, 21, 21, 21, 23), d4= c(2, 3, 3, 3, 2))
df2 <- data.frame(num= c(3, 2, 2, 2, 2), d1= c(1, 10, 10, 10, 15), d2= c(1, 5, 5, 5, 21), d3= c(6, 2, 2, 2, 23), d4= c(2, 3, 3, 3, 5))
list1 <- list(df1, df2)
</code>```

I would expect

```<code>newlist
[[1]]
   num   d1   d2   d3   d4    mn
1   3    1    1    6    2    2.5
2   1    17   15   21   3    16.0
3   1    17   15   21   3    16.0
</code>```

The closest I've gotten is

```<code>newlist <- lapply(list1, function(x) {
  x <- cbind(x, sapply(x$num, function(y) {
      y <- rowSums(x[2:(2+y)])/(y+1)
      }))
  })
</code>```

which binds columns for the means of every row. Based on this post I think I need a seq_along or maybe a Map on the inside function but I can't figure out how to implement it.

答:
An option is to loop over the list with lapply, extract the number of elements for each row with apply based on the 'num' column value (+1), get the mean and create the new column in transform

```<code>lapply(list1, function(x)  transform(x,
       mn = apply(x, 1, function(y) mean(y[-1][seq(y[1]+1)]))))
#[[1]]
#  num d1 d2 d3 d4       mn
#1   3  1  1  6  2  2.50000
#2   1 17 15 21  3 16.00000
#3   1 17 15 21  3 16.00000
#4   1 17 15 21  3 16.00000
#5   2 15 21 23  2 19.66667

#[[2]]
#  num d1 d2 d3 d4        mn
#1   3  1  1  6  2  2.500000
#2   2 10  5  2  3  5.666667
#3   2 10  5  2  3  5.666667
#4   2 10  5  2  3  5.666667
#5   2 15 21 23  5 19.666667
</code>```

Or with tidyverse, by pivoting to 'long' format with pivot_longer, do a group by row and get the mean of the first 'n' elements based on the 'num' value

```<code>library(purrr)
library(dplyr)
library(tidyr)
map(list1, ~
        .x %>%
           mutate(rn = row_number()) %>%
           pivot_longer(cols = starts_with('d')) %>%
           group_by(rn) %>%
           summarise(value = mean(value[seq_len(first(num) + 1)])) %>%
           pull(value) %>%
           bind_cols(.x, mn = .))
</code>```

Body:
I have a list of dataframes list1 and need a new column 'mn' in each dataframe that is the mean of a conditional number of columns based on the value in another column num plus one. So, for num=3 the new column would be the mean of the first four columns. For the example below

df1 <- data.frame(num= c(3, 1, 1, 1, 2), d1= c(1, 17, 17, 17, 15), d2= c(1, 15, 15, 15, 21), d3= c(6, 21, 21, 21, 23), d4= c(2, 3, 3, 3, 2))
df2 <- data.frame(num= c(3, 2, 2, 2, 2), d1= c(1, 10, 10, 10, 15), d2= c(1, 5, 5, 5, 21), d3= c(6, 2, 2, 2, 23), d4= c(2, 3, 3, 3, 5))
list1 <- list(df1, df2)

I would expect

newlist
[[1]]
   num   d1   d2   d3   d4    mn
1   3    1    1    6    2    2.5
2   1    17   15   21   3    16.0
3   1    17   15   21   3    16.0

The closest I've gotten is

newlist <- lapply(list1, function(x) {
  x <- cbind(x, sapply(x$num, function(y) {
      y <- rowSums(x[2:(2+y)])/(y+1)
      }))
  })

which binds columns for the means of every row. Based on this post I think I need a seq_along or maybe a Map on the inside function but I can't figure out how to implement it.

Body:
An option is to loop over the list with lapply, extract the number of elements for each row with apply based on the 'num' column value (+1), get the mean and create the new column in transform

lapply(list1, function(x)  transform(x,
       mn = apply(x, 1, function(y) mean(y[-1][seq(y[1]+1)]))))
#[[1]]
#  num d1 d2 d3 d4       mn
#1   3  1  1  6  2  2.50000
#2   1 17 15 21  3 16.00000
#3   1 17 15 21  3 16.00000
#4   1 17 15 21  3 16.00000
#5   2 15 21 23  2 19.66667

#[[2]]
#  num d1 d2 d3 d4        mn
#1   3  1  1  6  2  2.500000
#2   2 10  5  2  3  5.666667
#3   2 10  5  2  3  5.666667
#4   2 10  5  2  3  5.666667
#5   2 15 21 23  5 19.666667

Or with tidyverse, by pivoting to 'long' format with pivot_longer, do a group by row and get the mean of the first 'n' elements based on the 'num' value

library(purrr)
library(dplyr)
library(tidyr)
map(list1, ~
        .x %>%
           mutate(rn = row_number()) %>%
           pivot_longer(cols = starts_with('d')) %>%
           group_by(rn) %>%
           summarise(value = mean(value[seq_len(first(num) + 1)])) %>%
           pull(value) %>%
           bind_cols(.x, mn = .))


问:
How to Fixed / Lock Position of Background Image & Divs Containing Images
I have a map image (1080x1080px) I want this to be the the background of the body or a container div. I need the image to stay fixed in its place always, even when resizing the browser window.

I have divs inside of the main div container and these divs have images which are map markers that have been places at specific locations and they are toggled on and off as required.

Both the background image (map) and the markers need to stay in their position permanently.

How can I achieve this? What I have is not working...

body, html {
  height: 100%;
}

#bg {
  background-image: url(treasuremap_01.jpg);
  height: 100%;
  width: 100%;
  background-position: center;
  background-repeat: no-repeat;
  background-size: 1080px 1080px;
  position: relative;
  }

  #menu {
    display: block;
    width: 100px;
  }

  input:checked + .hidable {
    display: none;
  }

  input:not(:checked) + .showable {
    display: none;
  }

  #mark01 {
    position: absolute;
    top: 240px;
    right: 490px;
  }

  #mark02 {
    position: absolute;
    top: 480px;
    left: 460px;
  }

  #mark03 {
    position: absolute;
    bottom: 260px;
    right: 490px;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<title>Treasure Map</title>
</head>
<body>

  <div id="bg">
    <div id="menu">
      <input type="checkbox" /> Marker 1
      <div class="showable"><img id="mark01" src="xmark_01.png" alt="X Mark Red"></div>
      <input type="checkbox" /> Marker 2
      <div class="showable"><img id="mark02" src="xmark_02.png" alt="X Mark Green"></div>
      <input type="checkbox" /> Marker 3
      <div class="showable"><img id="mark03" src="xmark_03.png" alt="X Mark Magenta"></div>
    </div>
  </div>

</body>
</html></code>```

答:
div {
  width: 100%
  height: 90vh
  background-repeat: no-repeat
  background-position: center center
  background-size: cover
  background-attachment: fixed
} . End every of the sentence in an hyfin </p>

Body:
I have a map image (1080x1080px) I want this to be the the background of the body or a container div. I need the image to stay fixed in its place always, even when resizing the browser window.

I have divs inside of the main div container and these divs have images which are map markers that have been places at specific locations and they are toggled on and off as required.

Both the background image (map) and the markers need to stay in their position permanently.

How can I achieve this? What I have is not working...

body, html {
  height: 100%;
}

#bg {
  background-image: url(treasuremap_01.jpg);
  height: 100%;
  width: 100%;
  background-position: center;
  background-repeat: no-repeat;
  background-size: 1080px 1080px;
  position: relative;
  }

  #menu {
    display: block;
    width: 100px;
  }

  input:checked + .hidable {
    display: none;
  }

  input:not(:checked) + .showable {
    display: none;
  }

  #mark01 {
    position: absolute;
    top: 240px;
    right: 490px;
  }

  #mark02 {
    position: absolute;
    top: 480px;
    left: 460px;
  }

  #mark03 {
    position: absolute;
    bottom: 260px;
    right: 490px;
  }

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<title>Treasure Map</title>

      <input type="checkbox" /> Marker 1

      <input type="checkbox" /> Marker 2

      <input type="checkbox" /> Marker 3


问:
How to stop insert in a transaction in SQL Server?
Create query using BEGIN TRAN statement to insert two rows within BEGIN TRY if transaction count is greater than 1, catch error and rollback the transaction, otherwise print “transaction committed” (this is my teacher question the idea is that it should not insert more than 1 row by using the @@trancount is greater than one the transaction is rolled back)

This is the code that I wrote

```<code>BEGIN TRY
    BEGIN TRAN;

        INSERT INTO [Info].[Country]([name]) VALUES ('Italy');
        PRINT @@TRANCOUNT

        BEGIN TRAN
            INSERT INTO [Info].[Country]([name]) VALUES ('Jorden');
            PRINT @@TRANCOUNT

            IF @@TRANCOUNT > 1
                PRINT 'Rollback the transaction...';
            ELSE
                PRINT 'transaction succeeded';
END TRY
BEGIN CATCH
    ROLLBACK TRANSACTION
END CATCH;
</code>```

It keeps inserting the two rows even though the trans count is greater than 1

How can I fix this?!!

This is the result

答:
besides the other mentioned mistakes. I think your teacher wants you to make proper use of the try catch pattern. For this you need to know that the CATCH block is only executed when an error occurs inside of the try block.
See TRY...CATCH (Transact-SQL)

You can raise an error using the THROW statement
THROW (Transact-SQL)

IF @@ROWCOUNT > 1
 THROW 51000, 'row count greater 1.', 1;
```

Body:
Create query using BEGIN TRAN statement to insert two rows within BEGIN TRY if transaction count is greater than 1, catch error and rollback the transaction, otherwise print “transaction committed” (this is my teacher question the idea is that it should not insert more than 1 row by using the @@trancount is greater than one the transaction is rolled back)

This is the code that I wrote

BEGIN TRY
    BEGIN TRAN;

        INSERT INTO [Info].[Country]([name]) VALUES ('Italy');
        PRINT @@TRANCOUNT

        BEGIN TRAN
            INSERT INTO [Info].[Country]([name]) VALUES ('Jorden');
            PRINT @@TRANCOUNT

            IF @@TRANCOUNT > 1
                PRINT 'Rollback the transaction...';
            ELSE
                PRINT 'transaction succeeded';
END TRY
BEGIN CATCH
    ROLLBACK TRANSACTION
END CATCH;

It keeps inserting the two rows even though the trans count is greater than 1

How can I fix this?!!

This is the result


问:
Docker: cant install Tensorflow and numpy
How can I install Numpy and tensorflow inside a Docker image?

I'm trying to create a image of this simple Flask app:

```<code>import numpy as np
import tensorflow as tf

from flask import Flask, jsonify

print(tf.__version__)

with open('../assets/model/v1/model_architecture_V1.json', 'r') as f:
    model_json = f.read()

model = tf.keras.models.model_from_json(model_json)

model.load_weights("../assets/model/v1/model_weight_V1.h5")

app = Flask(__name__)

@app.route("/api/v1", methods=["GET"])
def getPrediction():

    prediction = model.predict()

    return jsonify({"Fe": 3123 })

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=4000, debug=True)
</code>```

This is my DockerFile

```<code>FROM alpine:3.10

RUN apk add --no-cache python3-dev \
    && pip3 install --upgrade pip

WORKDIR /app

COPY . /app

RUN pip3 --no-cache-dir install -r requirements.txt

CMD ["python3","src/app.py"]
</code>```

And this is my requirements.txt:

```<code>Flask==1.1.2
numpy==1.18.1
tensorflow==2.0.0
</code>```

When I build the image, Docker throws an error that says tensorflow and numpy cant be found.

Error:

答:
The issue here seems to be missing libraries to build the packages from .whl files.
When creating Docker images for python which includes heavy libraries like tensorflow, I would suggest you to use the official Debian images.

Please see below Dockerfile using Debian-Buster:

```<code>FROM python:3.7.5-buster
RUN echo \
   && apt-get update \
   && apt-get --yes install apt-file \
   && apt-file update
RUN echo \
   && apt-get --yes install build-essential
ARG USER=nobody
RUN usermod -aG sudo $USER
RUN pip3 install --upgrade pip
COPY . /app
WORKDIR /app
RUN pip3 --no-cache-dir install -r requirements.txt
USER $USER
# Using 4000 here as you used 4000 in the code. Flask has a default of 5000
EXPOSE 4000
ENTRYPOINT ["python"]
CMD ["app/app.py"]
</code>```

I used below commands to build and run the docker image, and got the result at http://0.0.0.0:4000/api/v1

```<code>docker build -t tfdocker:v1 .
docker run -p 4000:4000 -t tfdocker:v1
</code>```

For reference:
This was my directory structure:

```<code>├── Dockerfile
├── app
│   └── app.py
└── requirements.txt

1 directory, 3 files
</code>```

Content of requirements.txt were:

```<code>Flask==1.1.2
numpy==1.18.4
tensorflow==2.2.0
</code>```

Hope this helps!

Body:
How can I install Numpy and tensorflow inside a Docker image?

I'm trying to create a image of this simple Flask app:

import numpy as np
import tensorflow as tf

from flask import Flask, jsonify

print(tf.__version__)

with open('../assets/model/v1/model_architecture_V1.json', 'r') as f:
    model_json = f.read()

model = tf.keras.models.model_from_json(model_json)

model.load_weights("../assets/model/v1/model_weight_V1.h5")

app = Flask(__name__)

@app.route("/api/v1", methods=["GET"])
def getPrediction():

    prediction = model.predict()

    return jsonify({"Fe": 3123 })

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=4000, debug=True)

This is my DockerFile

FROM alpine:3.10

RUN apk add --no-cache python3-dev \
    && pip3 install --upgrade pip

WORKDIR /app

COPY . /app

RUN pip3 --no-cache-dir install -r requirements.txt

CMD ["python3","src/app.py"]

And this is my requirements.txt:

Flask==1.1.2
numpy==1.18.1
tensorflow==2.0.0

When I build the image, Docker throws an error that says tensorflow and numpy cant be found.

Error:

Body:
The issue here seems to be missing libraries to build the packages from .whl files.
When creating Docker images for python which includes heavy libraries like tensorflow, I would suggest you to use the official Debian images.

Please see below Dockerfile using Debian-Buster:

FROM python:3.7.5-buster
RUN echo \
   && apt-get update \
   && apt-get --yes install apt-file \
   && apt-file update
RUN echo \
   && apt-get --yes install build-essential
ARG USER=nobody
RUN usermod -aG sudo $USER
RUN pip3 install --upgrade pip
COPY . /app
WORKDIR /app
RUN pip3 --no-cache-dir install -r requirements.txt
USER $USER
# Using 4000 here as you used 4000 in the code. Flask has a default of 5000
EXPOSE 4000
ENTRYPOINT ["python"]
CMD ["app/app.py"]

I used below commands to build and run the docker image, and got the result at http://0.0.0.0:4000/api/v1

docker build -t tfdocker:v1 .
docker run -p 4000:4000 -t tfdocker:v1

For reference:
This was my directory structure:

├── Dockerfile
├── app
│   └── app.py
└── requirements.txt

1 directory, 3 files

Content of requirements.txt were:

Flask==1.1.2
numpy==1.18.4
tensorflow==2.2.0

Hope this helps!


答:
You need to set the #bg property of width and height the same as the background-image size.

body, html {
  height: 100%;
}

#bg {
  background-image: url(http://basicblue.biz/treasure/treasuremap_01.jpg);
  height: 1080px;
  width: 1080px;
  background-position: center;
  background-repeat: no-repeat;
  background-size: 1080px 1080px;
  position: relative;
  }

  #menu {
    display: block;
    width: 100px;
  }

  input:checked + .hidable {
    display: none;
  }

  input:not(:checked) + .showable {
    display: none;
  }

  #mark01 {
    position: absolute;
    top: 240px;
    right: 490px;
  }

  #mark02 {
    position: absolute;
    top: 480px;
    left: 460px;
  }

  #mark03 {
    position: absolute;
    bottom: 260px;
    right: 490px;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<title>Treasure Map</title>
</head>
<body>

  <div id="bg">
    <div id="menu">
      <input type="checkbox" /> Marker 1
      <div class="showable"><img id="mark01" src="http://basicblue.biz/treasure/xmark_01.png" alt="X Mark Red"></div>
      <input type="checkbox" /> Marker 2
      <div class="showable"><img id="mark02" src="http://basicblue.biz/treasure/xmark_02.png" alt="X Mark Green"></div>
      <input type="checkbox" /> Marker 3
      <div class="showable"><img id="mark03" src="http://basicblue.biz/treasure/xmark_03.png" alt="X Mark Magenta"></div>
    </div>
  </div>

</body>
</html></code>```

Title: How to Fixed / Lock Position of Background Image & Divs Containing Images

Body:
You need to set the #bg property of width and height the same as the background-image size.

body, html {
  height: 100%;
}

#bg {
  background-image: url(http://basicblue.biz/treasure/treasuremap_01.jpg);
  height: 1080px;
  width: 1080px;
  background-position: center;
  background-repeat: no-repeat;
  background-size: 1080px 1080px;
  position: relative;
  }

  #menu {
    display: block;
    width: 100px;
  }

  input:checked + .hidable {
    display: none;
  }

  input:not(:checked) + .showable {
    display: none;
  }

  #mark01 {
    position: absolute;
    top: 240px;
    right: 490px;
  }

  #mark02 {
    position: absolute;
    top: 480px;
    left: 460px;
  }

  #mark03 {
    position: absolute;
    bottom: 260px;
    right: 490px;
  }

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<title>Treasure Map</title>
</head>
<body>

  <div id="bg">
    <div id="menu">
      <input type="checkbox" /> Marker 1
      <div class="showable"><img id="mark01" src="http://basicblue.biz/treasure/xmark_01.png" alt="X Mark Red"></div>
      <input type="checkbox" /> Marker 2
      <div class="showable"><img id="mark02" src="http://basicblue.biz/treasure/xmark_02.png" alt="X Mark Green"></div>
      <input type="checkbox" /> Marker 3
      <div class="showable"><img id="mark03" src="http://basicblue.biz/treasure/xmark_03.png" alt="X Mark Magenta"></div>
    </div>
  </div>

</body>
</html>


问:
BehaviorSubject in shared service does not return updated value to Component
I have 2 components: TopBarComponent and UserDetailsComponent. TopBarComponent is common to all pages, so gets loaded along with UserDetailsComponent also. I have added a shared service named UserDetailsService.

UserDetailsService.ts:

```<code>import { Injectable } from '@angular/core';
import { BehaviorSubject } from "rxjs/BehaviorSubject";
import { Observable } from "rxjs/Observable";

@Injectable()
export class UserDetailsService {
  public userData = new BehaviorSubject({});

  public setUserDetails(data: any) {
    this.userData.next(data);
  }

  public getUserDetails(): Observable<any> {
    return this.userData.asObservable();
  }
}
</code>```

I'm setting the API response data in UserDetailsService from TopBarComponent

TopBarComponent.ts

```<code>//setting data in Shared Service

this.userDetailsService.setUserDetails(result.data);
</code>```

When I am subscribing to the getter method in the service, it always returning only initial value of BehaviorSubject.

UserDetailsComponent.ts

```<code>this.userDetailsService.getUserDetails().subscribe(
  data => {
    console.log(data);    //prints '{}' always.
  },
  error => this.error(error)
);
</code>```

While I'm getting updated value in UserDetailsService, I'm always getting initial value of BehaviorSubject.

Where I'm doing wrong? Any help will be appreciated.

答:
Try to mark the service to be global.

@Injectable({
    providedIn: 'root',
})
export class UserDetailsService
```

<p>This should solve the issue. If it does not then provide it in a module that imports all the components or their modules.</p>

<pre class="lang-js prettyprint-override"><code>providers: [UserDetailsService],
</code>```

Body:
I have 2 components: TopBarComponent and UserDetailsComponent. TopBarComponent is common to all pages, so gets loaded along with UserDetailsComponent also. I have added a shared service named UserDetailsService.

UserDetailsService.ts:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from "rxjs/BehaviorSubject";
import { Observable } from "rxjs/Observable";

@Injectable()
export class UserDetailsService {
  public userData = new BehaviorSubject({});

  public setUserDetails(data: any) {
    this.userData.next(data);
  }

  public getUserDetails(): Observable<any> {
    return this.userData.asObservable();
  }
}

I'm setting the API response data in UserDetailsService from TopBarComponent

TopBarComponent.ts

//setting data in Shared Service

this.userDetailsService.setUserDetails(result.data);

When I am subscribing to the getter method in the service, it always returning only initial value of BehaviorSubject.

UserDetailsComponent.ts

this.userDetailsService.getUserDetails().subscribe(
  data => {
    console.log(data);    //prints '{}' always.
  },
  error => this.error(error)
);

While I'm getting updated value in UserDetailsService, I'm always getting initial value of BehaviorSubject.

Where I'm doing wrong? Any help will be appreciated.

Body:
Try to mark the service to be global.

@Injectable({
    providedIn: 'root',
})
export class UserDetailsService

This should solve the issue. If it does not then provide it in a module that imports all the components or their modules.

providers: [UserDetailsService],


问:
Kivy: How to update popup Label Text without dismiss the popup
I want to open a popup and after 3 seconds change the text of popup label.

I try this code:

```<code>from kivy.app import App
from kivy.uix.popup import Popup
from kivy.lang import Builder
from kivy.uix.button import Button
import time

Builder.load_string('''
<SimpleButton>:
    on_press: self.fire_popup()
<SimplePopup>:
    id:pop
    size_hint: .4, .4
    auto_dismiss: True
    title: 'Hello world!!'
    Label:
        id: lbl_id
        text: 'Default Text'
''')

class SimplePopup(Popup):
    pass

class SimpleButton(Button):
    text = "Fire Popup !"

    def fire_popup(self):
        pop = SimplePopup()
        pop.open()

        time.sleep(3)
        pop.ids.lbl_id.text = "Changed Text"

class SampleApp(App):
    def build(self):
        return SimpleButton()

SampleApp().run()
</code>```

But BEFORE opening popup it sleeps for 3 seconds ,change the label text and then popup will open!!

What's the problem?

答:
Your code:

```<code>time.sleep(3)
</code>```

Is stopping the main thread, so nothing will happen with the GUI until that code finishes. You should schedule the text change using Clock.schedule_once() like this:

```<code>from kivy.app import App
from kivy.clock import Clock
from kivy.uix.popup import Popup
from kivy.lang import Builder
from kivy.uix.button import Button

Builder.load_string('''
<SimpleButton>:
    on_press: self.fire_popup()
<SimplePopup>:
    id:pop
    size_hint: .4, .4
    auto_dismiss: True
    title: 'Hello world!!'
    Label:
        id: lbl_id
        text: 'Default Text'
''')

class SimplePopup(Popup):
    pass

class SimpleButton(Button):
    text = "Fire Popup !"

    def fire_popup(self):
        self.pop = SimplePopup()
        self.pop.open()
        Clock.schedule_once(self.change_text, 3)

    def change_text(self, dt):
        self.pop.ids.lbl_id.text = "Changed Text"

class SampleApp(App):
    def build(self):
        return SimpleButton()

SampleApp().run()
</code>```

Body:
I want to open a popup and after 3 seconds change the text of popup label.

I try this code:

from kivy.app import App
from kivy.uix.popup import Popup
from kivy.lang import Builder
from kivy.uix.button import Button
import time

Builder.load_string('''
<SimpleButton>:
    on_press: self.fire_popup()
<SimplePopup>:
    id:pop
    size_hint: .4, .4
    auto_dismiss: True
    title: 'Hello world!!'
    Label:
        id: lbl_id
        text: 'Default Text'
''')

class SimplePopup(Popup):
    pass

class SimpleButton(Button):
    text = "Fire Popup !"

    def fire_popup(self):
        pop = SimplePopup()
        pop.open()

        time.sleep(3)
        pop.ids.lbl_id.text = "Changed Text"

class SampleApp(App):
    def build(self):
        return SimpleButton()

SampleApp().run()

But BEFORE opening popup it sleeps for 3 seconds ,change the label text and then popup will open!!

What's the problem?

Body:
Your code:

time.sleep(3)

Is stopping the main thread, so nothing will happen with the GUI until that code finishes. You should schedule the text change using Clock.schedule_once() like this:

from kivy.app import App
from kivy.clock import Clock
from kivy.uix.popup import Popup
from kivy.lang import Builder
from kivy.uix.button import Button

Builder.load_string('''
<SimpleButton>:
    on_press: self.fire_popup()
<SimplePopup>:
    id:pop
    size_hint: .4, .4
    auto_dismiss: True
    title: 'Hello world!!'
    Label:
        id: lbl_id
        text: 'Default Text'
''')

class SimplePopup(Popup):
    pass

class SimpleButton(Button):
    text = "Fire Popup !"

    def fire_popup(self):
        self.pop = SimplePopup()
        self.pop.open()
        Clock.schedule_once(self.change_text, 3)

    def change_text(self, dt):
        self.pop.ids.lbl_id.text = "Changed Text"

class SampleApp(App):
    def build(self):
        return SimpleButton()

SampleApp().run()


问:
Scala - ambiguous reference to overloaded definition -- with varargs

Possible Duplicate:

  How do I disambiguate in Scala between methods with vararg and without

I am currently porting part of an application to scala and it uses the Oval library.  The method is question is the Validator.validate method.  It has two signatures:

```<code>List<ConstraintViolation> validate(Object validatedObject)
List<ConstraintViolation> validate(Object validatedObject, String... profiles)
</code>```

The scala code looks generally like this:

```<code>def validate(toValidate: AnyRef) = {
  val validator = createValidator
  validator.validate(toValidate)
}
</code>```

And the error message:

```<code>error: ambiguous reference to overloaded definition,
[INFO] both method validate in class Validator of type (x$1: Any,x$2: <repeated...>[java.lang.String])java.util.List[net.sf.oval.ConstraintViolation]
[INFO] and  method validate in class Validator of type (x$1: Any)java.util.List[net.sf.oval.ConstraintViolation]
[INFO] match argument types (AnyRef)
[INFO]       this.validator.validate(toValidate)
</code>```

How can I get this be be unambiguous?

答:
The only way I know of is to use reflection:</p>

```<code>val ambiguous = validator.getClass.getMethods.filter(_.getName == "validate")
val wanted = ambiguous.find(_.getParameterTypes.length == 1).get
wanted.invoke(validator, toValidate).asInstanceOf[java.util.List[ConstraintViolation]]
</code>```

Body:
Possible Duplicate:

  How do I disambiguate in Scala between methods with vararg and without

I am currently porting part of an application to scala and it uses the Oval library.  The method is question is the Validator.validate method.  It has two signatures:

List<ConstraintViolation> validate(Object validatedObject)
List<ConstraintViolation> validate(Object validatedObject, String... profiles)

The scala code looks generally like this:

def validate(toValidate: AnyRef) = {
  val validator = createValidator
  validator.validate(toValidate)
}

And the error message:

error: ambiguous reference to overloaded definition,
[INFO] both method validate in class Validator of type (x$1: Any,x$2: <repeated...>[java.lang.String])java.util.List[net.sf.oval.ConstraintViolation]
[INFO] and  method validate in class Validator of type (x$1: Any)java.util.List[net.sf.oval.ConstraintViolation]
[INFO] match argument types (AnyRef)
[INFO]       this.validator.validate(toValidate)

How can I get this be be unambiguous?

Body:
The only way I know of is to use reflection:

val ambiguous = validator.getClass.getMethods.filter(_.getName == "validate")
val wanted = ambiguous.find(_.getParameterTypes.length == 1).get
wanted.invoke(validator, toValidate).asInstanceOf[java.util.List[ConstraintViolation]]


问:
How do i reduce padding space between UICollectionView cells in storyboard?
I want to have 3 cells in one row and I am only able to place 2 cells in the collection view</p>

答:
Modify minimumInteritemSpacingForSectionAt and minimumLineSpacingForSectionAt method of UICollectionViewDelegateFlowLayout to smaller value:

var reducedPadding: CGFloat = 8

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return reducedPadding
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return reducedPadding
}
```


问:
How to get count of icons in tray using pywinauto
I have an app which sits in tray when I click on .exe file.
I am unable click on my app which sit in system tray. Because it doesn't have class_name or id or anything when I inspect using inspector.exe. So I decided to click this using index of icon. As I am not sure how many icons sit in tray when I run this particular program. So I wanted to get the count of the icon before I click the .exe file. If the count is x then I can click index x icon after clicking the .exe which actually clicks on my desired icon.
Can any one help me in getting the count of the icons. I tried multiple times using child_window(class_name="") but it returned just an object instead of list.

Below is my code:

```<code>from pywinauto.application import Application
import time

app = Application(backend="uia").connect(path="explorer.exe")
st = app.window(class_name="Shell_TrayWnd")
t = st.child_window(title="Notification Chevron").wrapper_object()
t.click()

time.sleep(1)

list_box = Application(backend="uia").connect(class_name="NotifyIconOverflowWindow")
list_box_win = list_box.window(class_name="NotifyIconOverflowWindow")
list_box_win.wait('visible', timeout=30, retry_interval=3)
list_box_win.child_window(class_name="", found_index=x).click_input()
</code>```

Your help will be much appreciated :)

答:
This is not giving the count and do the required job.
The following code will loop through the apps available in the system tray and clicks on the desired app by checking its name.</p>

```<code>from pywinauto.application import Application
import time

app = Application(backend="uia").connect(path="explorer.exe")
taskBar = app.window(class_name='Shell_TrayWnd')
trayIcon = taskBar["Notification Chevron"].wrapper_object()
trayIcon.click()

time.sleep(0.25)

trayWindowContainer = Application(backend="uia").connect(class_name="NotifyIconOverflowWindow")
trayWindow = trayWindowContainer.window(class_name="NotifyIconOverflowWindow")
trayWindow.wait('visible', timeout=30, retry_interval=3)

breakLoop: bool = False
for notification_area in trayWindow.children():
    for app_in_tray in notification_area.children():
        if "<App_name>" in str(app_in_tray):
            app_in_tray.click_input()
            breakLoop = True
            break
            if breakLoop:
                break
</code>```

Body:
I have an app which sits in tray when I click on .exe file.
I am unable click on my app which sit in system tray. Because it doesn't have class_name or id or anything when I inspect using inspector.exe. So I decided to click this using index of icon. As I am not sure how many icons sit in tray when I run this particular program. So I wanted to get the count of the icon before I click the .exe file. If the count is x then I can click index x icon after clicking the .exe which actually clicks on my desired icon.
Can any one help me in getting the count of the icons. I tried multiple times using child_window(class_name="") but it returned just an object instead of list.

Below is my code:

from pywinauto.application import Application
import time

app = Application(backend="uia").connect(path="explorer.exe")
st = app.window(class_name="Shell_TrayWnd")
t = st.child_window(title="Notification Chevron").wrapper_object()
t.click()

time.sleep(1)

list_box = Application(backend="uia").connect(class_name="NotifyIconOverflowWindow")
list_box_win = list_box.window(class_name="NotifyIconOverflowWindow")
list_box_win.wait('visible', timeout=30, retry_interval=3)
list_box_win.child_window(class_name="", found_index=x).click_input()

Your help will be much appreciated :)

Body:
This is not giving the count and do the required job.
The following code will loop through the apps available in the system tray and clicks on the desired app by checking its name.

from pywinauto.application import Application
import time

app = Application(backend="uia").connect(path="explorer.exe")
taskBar = app.window(class_name='Shell_TrayWnd')
trayIcon = taskBar["Notification Chevron"].wrapper_object()
trayIcon.click()

time.sleep(0.25)

trayWindowContainer = Application(backend="uia").connect(class_name="NotifyIconOverflowWindow")
trayWindow = trayWindowContainer.window(class_name="NotifyIconOverflowWindow")
trayWindow.wait('visible', timeout=30, retry_interval=3)

breakLoop: bool = False
for notification_area in trayWindow.children():
    for app_in_tray in notification_area.children():
        if "<App_name>" in str(app_in_tray):
            app_in_tray.click_input()
            breakLoop = True
            break
            if breakLoop:
                break


问:
Docker compose extra_hosts does not change /etc/hosts file
I'm using the Nodejs app with docker to be deployed on AWS ecs.

The problem is that api call on private DNS record return
error: getaddrinfo enotfound request

From research error looks like to be connected with DNS lookup (please feel free to comment if you have other theory), so I decided to set DNS servers and µextra_hostsµ on compose.

Even though everything builds, when I cat /etc/hosts in Dockerfile it's not changed.

Questions are:

Should /etc/hosts be modified by extra_hosts.

Can there be other reason for error: getaddrinfo enotfound request? All other api calls work except internal DNS which works once and after returns error: getaddrinfo enotfound.

What's the best way to configure DNS and host with docker?

Why is it working once and stops after?

this is how my docker-compose file looks:

```<code>version: '3'
services:
  nodejs:
    extra_hosts:
      - "<name here>:<ip here>"
      - "<name here>:<ip here>"
    dns:
      - <ip here>
      - <ip here>
      - <ip here>
    network_mode: 'host'
    build:
      context: .
      dockerfile: Dockerfile
</code>```

Heres how docker file looks like

```<code>FROM alpine:latest
RUN apk add --update nodejs nodejs-npm && apk add g++ make python
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .

RUN cat /etc/hosts
EXPOSE 80
CMD npm start
</code>```

Here's the docker build output

```<code>Sending build context to Docker daemon  11.58MB
Step 1/11 : FROM alpine:latest
 ---> f70734b6a266
Step 2/11 : RUN apk add --update nodejs nodejs-npm && apk add g++ make python
 ---> Using cache
 ---> b173538c6ce5
Step 3/11 : WORKDIR /usr/src/app
 ---> Using cache
 ---> 0186bcca617d
Step 7/11 : RUN npm install
 ---> Using cache
 ---> 546f707d5fea
Step 8/11 : COPY . .
 ---> b66f4bec9d93
Step 9/11 : RUN cat /etc/hosts
 ---> Running in 1c48f0426713
127.0.0.1   localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.2  1c48f0426713
Removing intermediate container 1c48f0426713
 ---> 858735acc4a6
Step 10/11 : EXPOSE 80
 ---> Running in dd7a8ae0669a
Removing intermediate container dd7a8ae0669a
 ---> 907a3dafb4fc
Step 11/11 : CMD npm start
 ---> Running in a3dd69c6ec3b
Removing intermediate container a3dd69c6ec3b
 ---> cda2214b2761
Successfully built cda2214b2761
Successfully tagged test:latest

</code>```

答:
Turns out that aws fargate has only one network, which awsvpc and it does not allow modifications on host file or specification of dns server.

Worth mentioning that after tons of research we did not try this suggestion

Not sure if it works but still...

Body:
I'm using the Nodejs app with docker to be deployed on AWS ecs.

The problem is that api call on private DNS record return
error: getaddrinfo enotfound request

From research error looks like to be connected with DNS lookup (please feel free to comment if you have other theory), so I decided to set DNS servers and µextra_hostsµ on compose.

Even though everything builds, when I cat /etc/hosts in Dockerfile it's not changed.

Questions are:

Should /etc/hosts be modified by extra_hosts.

Can there be other reason for error: getaddrinfo enotfound request? All other api calls work except internal DNS which works once and after returns error: getaddrinfo enotfound.

What's the best way to configure DNS and host with docker?

Why is it working once and stops after?

this is how my docker-compose file looks:

version: '3'
services:
  nodejs:
    extra_hosts:
      - "<name here>:<ip here>"
      - "<name here>:<ip here>"
    dns:
      - <ip here>
      - <ip here>
      - <ip here>
    network_mode: 'host'
    build:
      context: .
      dockerfile: Dockerfile

Heres how docker file looks like

FROM alpine:latest
RUN apk add --update nodejs nodejs-npm && apk add g++ make python
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .

RUN cat /etc/hosts
EXPOSE 80
CMD npm start

Here's the docker build output

Sending build context to Docker daemon  11.58MB
Step 1/11 : FROM alpine:latest
 ---> f70734b6a266
Step 2/11 : RUN apk add --update nodejs nodejs-npm && apk add g++ make python
 ---> Using cache
 ---> b173538c6ce5
Step 3/11 : WORKDIR /usr/src/app
 ---> Using cache
 ---> 0186bcca617d
Step 7/11 : RUN npm install
 ---> Using cache
 ---> 546f707d5fea
Step 8/11 : COPY . .
 ---> b66f4bec9d93
Step 9/11 : RUN cat /etc/hosts
 ---> Running in 1c48f0426713
127.0.0.1   localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.2  1c48f0426713
Removing intermediate container 1c48f0426713
 ---> 858735acc4a6
Step 10/11 : EXPOSE 80
 ---> Running in dd7a8ae0669a
Removing intermediate container dd7a8ae0669a
 ---> 907a3dafb4fc
Step 11/11 : CMD npm start
 ---> Running in a3dd69c6ec3b
Removing intermediate container a3dd69c6ec3b
 ---> cda2214b2761
Successfully built cda2214b2761
Successfully tagged test:latest


问:
How to organize the data in application database?
My application should contain list of questions + user answers. How should I organize the database:

```<code>             question1   question2   question2   ...         questionN
user_id_1    yes         no          yes         ...         yes
user_id_2    no          no          yes         ...         no
...
user_id_N    yes         yes         yes         ...         yes
</code>```

Looks like I need to create separate table with questions and assign id to each question. How another table should look like (since number of columns is not fixed)? Or, should I have 2 more tables?

Later on I will also need to:

calculate how many users answered 'yes' on questionN;

how many friends (another table or json data) of *user_id_N* answered 'yes' on questionN.

Should I query database each for getting these numbers, or should I have separate database and keep counters there each time user answer (looks possible for item 1 only since friends list can be changed anytime).

答:
A standard way to do this is to store each answer as a separate entity - conceptually the same as you depict, but without the requirement to modify your structure as you add new questions. Here's an example set of model definitions that achieves this:</p>

```<code>class UserInfo(db.Model):
  # Anything you want to store about the user

class Question(db.Model):
  text = db.TextProperty(required=True)
  # Anything else you want to store about the question

class Answer(db.Model):
  user = db.ReferenceProperty(UserInfo, required=True)
  question = db.ReferenceProperty(Question, required=True)
  answer_text = db.TextProperty(required=True)
</code>```

Body:
My application should contain list of questions + user answers. How should I organize the database:

             question1   question2   question2   ...         questionN
user_id_1    yes         no          yes         ...         yes
user_id_2    no          no          yes         ...         no
...
user_id_N    yes         yes         yes         ...         yes

Looks like I need to create separate table with questions and assign id to each question. How another table should look like (since number of columns is not fixed)? Or, should I have 2 more tables?

Later on I will also need to:

calculate how many users answered 'yes' on questionN;

how many friends (another table or json data) of *user_id_N* answered 'yes' on questionN.

Should I query database each for getting these numbers, or should I have separate database and keep counters there each time user answer (looks possible for item 1 only since friends list can be changed anytime).

Body:
A standard way to do this is to store each answer as a separate entity - conceptually the same as you depict, but without the requirement to modify your structure as you add new questions. Here's an example set of model definitions that achieves this:

class UserInfo(db.Model):
  # Anything you want to store about the user

class Question(db.Model):
  text = db.TextProperty(required=True)
  # Anything else you want to store about the question

class Answer(db.Model):
  user = db.ReferenceProperty(UserInfo, required=True)
  question = db.ReferenceProperty(Question, required=True)
  answer_text = db.TextProperty(required=True)


问:
Python pymysql : cannot run multiple statements
I am working on a project which needs to read a input.sql file and source all the commands in it.
It was working fine for all other statements, but for procedures it is not working.

You can try to replicate it yourself using these inputs.

```<code>CREATE TABLE IF NOT EXISTS products(
Prod_id INT AUTO_INCREMENT PRIMARY KEY,
Name VARCHAR(255) NOT NULL,
Price INT NOT NULL,
 created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);

Insert into products(Name,Price) Values('soap',1);
Insert into products(Name,Price) Values('toilet paper',2);
Insert into products(Name,Price) Values('Choco taco',3);

CREATE PROCEDURE GetAllProducts()
BEGIN
SELECT * FROM products;
END;
</code>```

But while I am executing a create procedure and call statements, I am unable to do so. Can anyone please help me out?

a few statements as below but, it is not working

with connection.cursor() as cursor:

```<code>    for statement in script.split(';'):

        if len(statement) > 0:

            cursor.execute(statement + ';')
</code>```

I understand that the issue is because of the ; delimiter, But how can I make sure the whole procedure gets executed?

Cursor of pymysql seems to execute one statement at a time and doesn't allow multiple execution.?

答:
Because you are splitting on ;, the procedure gets executed as two separate statements:

```<code>BEGIN
SELECT * FROM products;
</code>```

and

END;

which are both invalid SQL.

Body:
I am working on a project which needs to read a input.sql file and source all the commands in it.
It was working fine for all other statements, but for procedures it is not working.

You can try to replicate it yourself using these inputs.

CREATE TABLE IF NOT EXISTS products(
Prod_id INT AUTO_INCREMENT PRIMARY KEY,
Name VARCHAR(255) NOT NULL,
Price INT NOT NULL,
 created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);

Insert into products(Name,Price) Values('soap',1);
Insert into products(Name,Price) Values('toilet paper',2);
Insert into products(Name,Price) Values('Choco taco',3);

CREATE PROCEDURE GetAllProducts()
BEGIN
SELECT * FROM products;
END;

But while I am executing a create procedure and call statements, I am unable to do so. Can anyone please help me out?

a few statements as below but, it is not working

with connection.cursor() as cursor:

    for statement in script.split(';'):

        if len(statement) > 0:

            cursor.execute(statement + ';')

I understand that the issue is because of the ; delimiter, But how can I make sure the whole procedure gets executed?

Cursor of pymysql seems to execute one statement at a time and doesn't allow multiple execution.?

Body:
Because you are splitting on ;, the procedure gets executed as two separate statements:

BEGIN
SELECT * FROM products;

and

END;

which are both invalid SQL.


问:
Syntax error on line 6 'if/elif statements' and 'and/or statements'
I am continually getting a syntax error on line 6 when trying to run this code. I've tried messing with the indentation and have browsed related questions on this site to no avail. Any help would be greatly appreciated! Thank you!

```<code>#program that reads month and day and outputs season
input_month = input()
input_day = int(input())

#input reading for spring
if ((input_month == 'March') and (20 <= input_day <= 31))
or ((input_month == 'June') and (1 <= input_day <= 20))
    print('Spring')

#input reading for summer
elif (input_month == 'June') and (21 <= input_day <= 30)
or (input_month == 'September') and (1 <= input_day <= 30)
    print('Summer')

#input reading for Autumn
elif (input_month == 'September') and (22 <= input_day <= 30)
or (input_month == 'December') and (1 <= input_day <= 20)
    print('Autumn')

#input reading for winter
elif (input_month == 'December') and (21 <= input_day <= 31)
or (input_month == 'January') and (1 <= input_day <= 31)
or (input_month == 'February') and (1 <= input_day <= 28)
or (input_month == 'March') and (1 <= input_day <= 19)
    print('Winter')
</code>```

Edit: the error reads 'EOL error' which has in the past meant that I didn't define a variable or didn't write the variable correctly. This doesn't seem to be the case though.

Thank you all for the help!!

Here's the updated, working code including all months:

```<code>#program that reads month and day and outputs season
input_month = input()
input_day = int(input())

#input reading for spring
if input_month == 'March' and 20 <= input_day <= 31\
or input_month == 'April' and 1 <= input_day <= 30\
or input_month == 'May' and 1 <= input_day <= 31\
or input_month == 'June' and 1 <= input_day <= 20:
    print('Spring')

#input reading for summer
elif input_month == 'June' and 21 <= input_day <= 30\
or input_month == 'July' and 1 <= input_day <= 31\
or input_month == 'August' and 1 <= input_day <= 31\
or input_month == 'September' and 1 <= input_day <= 30:
    print('Summer')

#input reading for Autumn
elif input_month == 'September' and 22 <= input_day <= 30\
or input_month == 'October' and 1 <= input_day <= 31\
or input_month == 'November' and 1 <= input_day <= 30\
or input_month == 'December' and 1 <= input_day <= 20:
    print('Autumn')

#input reading for winter
elif input_month == 'December' and 21 <= input_day <= 31\
or input_month == 'January' and 1 <= input_day <= 31\
or input_month == 'February' and 1 <= input_day <= 28\
or input_month == 'March' and 1 <= input_day <= 19:
    print('Winter')

#if input is not valid
else:
    print('Invalid')
</code>```

答:
This the correct and working code for your solution.</p>

```<code>input_month = input()
input_day = int(input())

# input reading for spring
if ((input_month == 'March') and (20 <= input_day <= 31)) or ((input_month == 'June') and (1 <= input_day <= 20)):
    print('Spring')

# input reading for summer
elif (input_month == 'June') and (21 <= input_day <= 30) or (input_month == 'September') and (1 <= input_day <= 30):
    print('Summer')

# input reading for Autumn
elif (input_month == 'September') and (22 <= input_day <= 30) or (input_month == 'December') and (1 <= input_day <= 20):
    print('Autumn')

# input reading for winter
elif (input_month == 'December') and (21 <= input_day <= 31) or (input_month == 'January') and (
        1 <= input_day <= 31) or (input_month == 'February') and (1 <= input_day <= 28) or (
        input_month == 'March') and (1 <= input_day <= 19):
    print('Winter')
</code>```

Body:
I am continually getting a syntax error on line 6 when trying to run this code. I've tried messing with the indentation and have browsed related questions on this site to no avail. Any help would be greatly appreciated! Thank you!

#program that reads month and day and outputs season
input_month = input()
input_day = int(input())

#input reading for spring
if ((input_month == 'March') and (20 <= input_day <= 31))
or ((input_month == 'June') and (1 <= input_day <= 20))
    print('Spring')

#input reading for summer
elif (input_month == 'June') and (21 <= input_day <= 30)
or (input_month == 'September') and (1 <= input_day <= 30)
    print('Summer')

#input reading for Autumn
elif (input_month == 'September') and (22 <= input_day <= 30)
or (input_month == 'December') and (1 <= input_day <= 20)
    print('Autumn')

#input reading for winter
elif (input_month == 'December') and (21 <= input_day <= 31)
or (input_month == 'January') and (1 <= input_day <= 31)
or (input_month == 'February') and (1 <= input_day <= 28)
or (input_month == 'March') and (1 <= input_day <= 19)
    print('Winter')

Edit: the error reads 'EOL error' which has in the past meant that I didn't define a variable or didn't write the variable correctly. This doesn't seem to be the case though.

Thank you all for the help!!

Here's the updated, working code including all months:

#program that reads month and day and outputs season
input_month = input()
input_day = int(input())

#input reading for spring
if input_month == 'March' and 20 <= input_day <= 31\
or input_month == 'April' and 1 <= input_day <= 30\
or input_month == 'May' and 1 <= input_day <= 31\
or input_month == 'June' and 1 <= input_day <= 20:
    print('Spring')

#input reading for summer
elif input_month == 'June' and 21 <= input_day <= 30\
or input_month == 'July' and 1 <= input_day <= 31\
or input_month == 'August' and 1 <= input_day <= 31\
or input_month == 'September' and 1 <= input_day <= 30:
    print('Summer')

#input reading for Autumn
elif input_month == 'September' and 22 <= input_day <= 30\
or input_month == 'October' and 1 <= input_day <= 31\
or input_month == 'November' and 1 <= input_day <= 30\
or input_month == 'December' and 1 <= input_day <= 20:
    print('Autumn')

#input reading for winter
elif input_month == 'December' and 21 <= input_day <= 31\
or input_month == 'January' and 1 <= input_day <= 31\
or input_month == 'February' and 1 <= input_day <= 28\
or input_month == 'March' and 1 <= input_day <= 19:
    print('Winter')

#if input is not valid
else:
    print('Invalid')

Body:
This the correct and working code for your solution.

input_month = input()
input_day = int(input())

# input reading for spring
if ((input_month == 'March') and (20 <= input_day <= 31)) or ((input_month == 'June') and (1 <= input_day <= 20)):
    print('Spring')

# input reading for summer
elif (input_month == 'June') and (21 <= input_day <= 30) or (input_month == 'September') and (1 <= input_day <= 30):
    print('Summer')

# input reading for Autumn
elif (input_month == 'September') and (22 <= input_day <= 30) or (input_month == 'December') and (1 <= input_day <= 20):
    print('Autumn')

# input reading for winter
elif (input_month == 'December') and (21 <= input_day <= 31) or (input_month == 'January') and (
        1 <= input_day <= 31) or (input_month == 'February') and (1 <= input_day <= 28) or (
        input_month == 'March') and (1 <= input_day <= 19):
    print('Winter')