问:
pyspark replace all values in dataframe with another values
I have 500 columns in my  pyspark data frame...Some are of string type,some int and some boolean(100 boolean columns ).
Now, all the boolean columns have two distinct levels - Yes and No and I want to convert those into 1/0

For string I have three values- passed, failed and null.
How do I replace those nulls with 0?
fillna(0) works only with integers

```<code> c1| c2 |    c3 |c4|c5..... |c500
yes| yes|passed |45....
No | Yes|failed |452....
Yes|No  |None   |32............
</code>```

when I do

```<code>df.replace(yes,1)
</code>```

I get following error:

```<code>ValueError: Mixed type replacements are not supported
</code>```

答:
You can use Koalas to do Pandas like operations in spark. However, you need to respect the schema of a give dataframe. Using Koalas you could do the following:

```<code>df = df.replace('yes','1')
</code>```

Once you replaces all strings to digits you can cast the column to int. If you want to replace certain empty values with NaNs I can recommend doing the following:

```<code>df = df .replace(['?'], None)
</code>```

Body:
I have 500 columns in my  pyspark data frame...Some are of string type,some int and some boolean(100 boolean columns ).
Now, all the boolean columns have two distinct levels - Yes and No and I want to convert those into 1/0

For string I have three values- passed, failed and null.
How do I replace those nulls with 0?
fillna(0) works only with integers

 c1| c2 |    c3 |c4|c5..... |c500
yes| yes|passed |45....
No | Yes|failed |452....
Yes|No  |None   |32............

when I do

df.replace(yes,1)

I get following error:

ValueError: Mixed type replacements are not supported

Body:
You can use Koalas to do Pandas like operations in spark. However, you need to respect the schema of a give dataframe. Using Koalas you could do the following:

df = df.replace('yes','1')

Once you replaces all strings to digits you can cast the column to int. If you want to replace certain empty values with NaNs I can recommend doing the following:

df = df .replace(['?'], None)


来源: stackexchange

问:
Boost MPL to generate code for object serialization?
I want to generate serialization/deserialization code for

```<code>class Object
{
    string a;
    int b;
    long c;
    char d;
};
</code>```

by looking at a mpl sequence, but I need to be able to identify object and retrieve it back as well, I can't figure out how would I get the names of it members, do I have to know it?

code should look like

```<code>void SerializeObject(ostream os)
{
   serialize(object.a, os);
   serialize(object.b, os);

   //serialize(object.member, os);
}
</code>```

I want to generate above code by user only defining a mpl sequence corresponding the object layout, is it doable, can you give me some hints?

my aim is:

User defines mpl::vector<String, int, long, char> for above object and my metaprogram can generate the coded needed.

答:
There are no ways to infer member names in templates.  You'll need to specify everything explicitly, like this:

```<code>template<typename ObjT, typename MemberT, MemberT ObjT::*Ptr>
struct member{};

mpl::vector
<
    member<Object, string, &Object::a>,
    member<Object, int, &Object::b>,
    member<Object, long, &Object::c>,
    member<Object, char, &Object::d>
>;
</code>```

Another option is to create functions to help generate member, define an operator>> for member that merges them into a member_vec, and an operator>> for member_vec that merges into a larger member_vec.  Since you're only using the type, the compiler can optimize away any actual function calls

Functions can use implicit template arguments, so it can make serializers take a bit less code to define:

```<code>auto serializer =
        mem(&Object::a) >>
        mem(&Object::b) >>
        mem(&Object::c) >>
        mem(&Object::d);
</code>```

I've made serializers myself, using both techniques.  The second one is what I'm most happy with.

ContentLicense: CC BY-SA 3.0

Body:
I want to generate serialization/deserialization code for

class Object
{
    string a;
    int b;
    long c;
    char d;
};

by looking at a mpl sequence, but I need to be able to identify object and retrieve it back as well, I can't figure out how would I get the names of it members, do I have to know it?

code should look like

void SerializeObject(ostream os)
{
   serialize(object.a, os);
   serialize(object.b, os);

   //serialize(object.member, os);
}

I want to generate above code by user only defining a mpl sequence corresponding the object layout, is it doable, can you give me some hints?

my aim is:

User defines mpl::vector<String, int, long, char> for above object and my metaprogram can generate the coded needed.

Body:
There are no ways to infer member names in templates.  You'll need to specify everything explicitly, like this:

template<typename ObjT, typename MemberT, MemberT ObjT::*Ptr>
struct member{};

mpl::vector
<
    member<Object, string, &Object::a>,
    member<Object, int, &Object::b>,
    member<Object, long, &Object::c>,
    member<Object, char, &Object::d>
>;

Another option is to create functions to help generate member, define an operator>> for member that merges them into a member_vec, and an operator>> for member_vec that merges into a larger member_vec.  Since you're only using the type, the compiler can optimize away any actual function calls

Functions can use implicit template arguments, so it can make serializers take a bit less code to define:

auto serializer =
        mem(&Object::a) >>
        mem(&Object::b) >>
        mem(&Object::c) >>
        mem(&Object::d);

I've made serializers myself, using both techniques.  The second one is what I'm most happy with.


问:
Running NPM scripts sequentially
Let's say I have

```<code>"scripts": {
    "pre-build": "echo \"Welcome\" && exit 1",
    "build_logic": "start cmd.exe @cmd /k \"yo esri-appbuilder-js:widget && exit 1\"",
    "post_build":  "start C:\\WebAppBuilderForArcGIS\\startupShortcut",
    "exit" : "start cmd.exe @cmd /k \"echo \"goodbye\" && exit 1\""
  },
</code>```

What NPM command can I run to let all of these scripts launch sequentially. When I use pre/post fixing they launch sequentially but they don't wait for the parent script to finish before executing. I am assuming the only solution is like: How do I get Gulp tasks to fire sequentially when firing shell commands in an async.series helper function? ? I know this can be done with Gulp but I would like to stick with NPM for now to explore its capabilities. Thanks for any help!

答:
you can try:</p>

```<code>
"scripts": {
  "clean-dist": "rm -f ./dist/*.js && rm -f ./dist/*.map",
  "build": "npm run clean-dist && parcel build ./packages/index.html"
},
</code>```

Title: Running NPM scripts sequentially

Body:
Let's say I have

"scripts": {
    "pre-build": "echo \"Welcome\" && exit 1",
    "build_logic": "start cmd.exe @cmd /k \"yo esri-appbuilder-js:widget && exit 1\"",
    "post_build":  "start C:\\WebAppBuilderForArcGIS\\startupShortcut",
    "exit" : "start cmd.exe @cmd /k \"echo \"goodbye\" && exit 1\""
  },

What NPM command can I run to let all of these scripts launch sequentially. When I use pre/post fixing they launch sequentially but they don't wait for the parent script to finish before executing. I am assuming the only solution is like: How do I get Gulp tasks to fire sequentially when firing shell commands in an async.series helper function? ? I know this can be done with Gulp but I would like to stick with NPM for now to explore its capabilities. Thanks for any help!

Body:
you can try:

"scripts": {
  "clean-dist": "rm -f ./dist/*.js && rm -f ./dist/*.map",
  "build": "npm run clean-dist && parcel build ./packages/index.html"
},

ContentLicense: CC BY-SA 4.0


问:
In JAGS, how does the stochastic node works?
...and what does the ~ sign mean compared to R in y[I] ~ dnorm(m[i],tau) vs y[I] <- dnorm(n,m[i],tau)?

Consider the two lines of code:

```<code>`for(I in 1:length(y)) {
y[i] ~ dnorm(m[i],tau)  #---> Jags code (stochastic node)
m[i] = alpha + beta*(x[i] - x_bar)
.
.
}
y[i] <- dnorm(n,m[i],tau)?) ---> R`
</code>```

In Jags, what will be the n values since it is not specified inside the dnorm function? (dnorm(m[i],tau))

For each i, does the dnorm function calculate the density values for each y value with respect to the mean m[I] which has a linear relationship determined by the deterministic node and tau(precision)?

In short, I wanna know what n values will be used by dnorm or any other density function for distributions(dgamma or dbeta).

答:
In this specific instance y is your response variable, m is your linear predictor, and tau is precision (the inverse of variance). Using ~ makes the relationship stochastic. Looking to the JAGS user manual...

"Relations can be of two types. A stochastic relation (~) defines a stochastic node, representing a random variable in the model. A deterministic relation (<-) defines a deterministic
node, the value of which is determined exactly by the values of its parents. The equals sign
(=) can be used for a deterministic relation in place of the left arrow (<-)."

So, in other words, you are assuming that the values in y are drawn from a normal distribution that are related to m and tau.

While dnorm in R calculates the density, JAGS calculates the log density (as per the user manual).  Effectively, this stochastic relationship allows you to use y and x to estimate alpha, beta, and tau, and you use dnorm in this case by making a distributional assumption about the data generating process.

Of course, as this is a Bayesian analysis, you'll need priors for your parameters. You can also deterministically calculate the standard deviation instead of precision. A full model would look something like...

```<code>model{
# likelihood
for(I in 1:length(y)) {
y[i] ~ dnorm(m[i],tau)
m[i] <- alpha + beta*(x[i] - x_bar)
}
# priors
tau ~ dgamma(0.001, 0.001)
sd <- 1/ sqrt(tau)
alpha ~ dnorm(0, 0.001)
beta ~ dnorm(0, 0.001)
}

</code>```

Body:
...and what does the ~ sign mean compared to R in y[I] ~ dnorm(m[i],tau) vs y[I] <- dnorm(n,m[i],tau)?

Consider the two lines of code:

`for(I in 1:length(y)) {
y[i] ~ dnorm(m[i],tau)  #---> Jags code (stochastic node)
m[i] = alpha + beta*(x[i] - x_bar)
.
.
}
y[i] <- dnorm(n,m[i],tau)?) ---> R`

In Jags, what will be the n values since it is not specified inside the dnorm function? (dnorm(m[i],tau))

For each i, does the dnorm function calculate the density values for each y value with respect to the mean m[I] which has a linear relationship determined by the deterministic node and tau(precision)?

In short, I wanna know what n values will be used by dnorm or any other density function for distributions(dgamma or dbeta).

Body:
In this specific instance y is your response variable, m is your linear predictor, and tau is precision (the inverse of variance). Using ~ makes the relationship stochastic. Looking to the JAGS user manual...

"Relations can be of two types. A stochastic relation (~) defines a stochastic node, representing a random variable in the model. A deterministic relation (<-) defines a deterministic
node, the value of which is determined exactly by the values of its parents. The equals sign
(=) can be used for a deterministic relation in place of the left arrow (<-)."

So, in other words, you are assuming that the values in y are drawn from a normal distribution that are related to m and tau.

While dnorm in R calculates the density, JAGS calculates the log density (as per the user manual).  Effectively, this stochastic relationship allows you to use y and x to estimate alpha, beta, and tau, and you use dnorm in this case by making a distributional assumption about the data generating process.

Of course, as this is a Bayesian analysis, you'll need priors for your parameters. You can also deterministically calculate the standard deviation instead of precision. A full model would look something like...

model{
# likelihood
for(I in 1:length(y)) {
y[i] ~ dnorm(m[i],tau)
m[i] <- alpha + beta*(x[i] - x_bar)
}
# priors
tau ~ dgamma(0.001, 0.001)
sd <- 1/ sqrt(tau)
alpha ~ dnorm(0, 0.001)
beta ~ dnorm(0, 0.001)
}


问:
Terraform resource inheritance
Is there a way to declare an abstract resource to inherit from?

Example:

```<code>resource "digitalocean_droplet" "worker_abstract" {
  abstract = true // ???

  name = "swarm-worker-${count.index}"
  tags = [
    "${digitalocean_tag.swarm_worker.id}"
  ]

  // other config stuff

  provisioner "remote-exec" {
    //...
  }
}
</code>```

And then use declared resource with overridden variables:

```<code>resource "worker_abstract" "worker_foo" {
  count = 2
  name = "swarm-worker-foo-${count.index}"
  tags = [
    "${digitalocean_tag.swarm_worker.id}",
    "${digitalocean_tag.foo.id}"
  ]
}

resource "worker_abstract" "worker_bar" {
  count = 5
  name = "swarm-worker-bar-${count.index}"
  tags = [
    "${digitalocean_tag.swarm_worker.id}"
    "${digitalocean_tag.bar.id}"
  ]
}
</code>```

答:
This might be a little more "verbose" of a solution than what you're proposing, but this sounds like a perfect use-case for modules in 0.12.

You could create a module, say in the file worker/main.tf

```<code>variable "instances" {
  type = number
}

variable "name" {
  type = string
}

variable "tags" {
  type    = list(string)
  default = []
}

resource "digitalocean_droplet" "worker" {
  count = var.instances

  name = "swarm-worker-${var.name}-${count.index}"
  tags = var.tags

  // other config stuff

  provisioner "remote-exec" {
    //...
  }
}
</code>```

then you could consume your module almost exactly like your example (let's say from the directory above worker)

```<code>module "worker_foo" {
  source = "./worker"

  instances = 2
  name = "foo"
  tags = [
    "${digitalocean_tag.swarm_worker.id}",
    "${digitalocean_tag.foo.id}"
  ]
}

module "worker_bar" {
  source = "./worker"

  instances = 5
  name = "bar"
  tags = [
    "${digitalocean_tag.swarm_worker.id}"
    "${digitalocean_tag.bar.id}"
  ]
}
</code>```

Title: Terraform resource inheritance

Body:
Is there a way to declare an abstract resource to inherit from?

Example:

resource "digitalocean_droplet" "worker_abstract" {
  abstract = true // ???

  name = "swarm-worker-${count.index}"
  tags = [
    "${digitalocean_tag.swarm_worker.id}"
  ]

  // other config stuff

  provisioner "remote-exec" {
    //...
  }
}

And then use declared resource with overridden variables:

resource "worker_abstract" "worker_foo" {
  count = 2
  name = "swarm-worker-foo-${count.index}"
  tags = [
    "${digitalocean_tag.swarm_worker.id}",
    "${digitalocean_tag.foo.id}"
  ]
}

resource "worker_abstract" "worker_bar" {
  count = 5
  name = "swarm-worker-bar-${count.index}"
  tags = [
    "${digitalocean_tag.swarm_worker.id}"
    "${digitalocean_tag.bar.id}"
  ]
}

Body:
This might be a little more "verbose" of a solution than what you're proposing, but this sounds like a perfect use-case for modules in 0.12.

You could create a module, say in the file worker/main.tf

variable "instances" {
  type = number
}

variable "name" {
  type = string
}

variable "tags" {
  type    = list(string)
  default = []
}

resource "digitalocean_droplet" "worker" {
  count = var.instances

  name = "swarm-worker-${var.name}-${count.index}"
  tags = var.tags

  // other config stuff

  provisioner "remote-exec" {
    //...
  }
}

then you could consume your module almost exactly like your example (let's say from the directory above worker)

module "worker_foo" {
  source = "./worker"

  instances = 2
  name = "foo"
  tags = [
    "${digitalocean_tag.swarm_worker.id}",
    "${digitalocean_tag.foo.id}"
  ]
}

module "worker_bar" {
  source = "./worker"

  instances = 5
  name = "bar"
  tags = [
    "${digitalocean_tag.swarm_worker.id}"
    "${digitalocean_tag.bar.id}"
  ]
}


问:
Convert seconds into minutes and seconds
How can I convert seconds into minutes and seconds?

I am aware that you can convert seconds to minutes like so, but I don't know how I can get the remainder of seconds...

```<code>int minutes = seconds / 60;
</code>```

答:
You can resolve this problem with NSMeasurement and NSUnitDuration. These classes require iOS 10.0+, tvOS 10.0+, macOS 10.12+ or watchOS 3.0+. The code below converts seconds to minutes and seconds.

```<code>int seconds = 230;
NSMeasurement* measurement = [[NSMeasurement alloc] initWithDoubleValue:seconds unit:NSUnitDuration.seconds];
NSMeasurement* measurementMinutes = [measurement measurementByConvertingToUnit:NSUnitDuration.minutes];
int minutes = floor(measurementMinutes.doubleValue);
NSMeasurement* measurementMinutesWithoutSeconds = [measurement measurementBySubtractingMeasurement:[[NSMeasurement alloc] initWithDoubleValue:minutes unit:NSUnitDuration.minutes]];
int secondsRemainder = floor([measurementMinutesWithoutSeconds measurementByConvertingToUnit:NSUnitDuration.seconds].doubleValue);
NSLog(@"%d %d", minutes, secondsRemainder); // 3 50
</code>```

Body:
How can I convert seconds into minutes and seconds?

I am aware that you can convert seconds to minutes like so, but I don't know how I can get the remainder of seconds...

int minutes = seconds / 60;

Body:
You can resolve this problem with NSMeasurement and NSUnitDuration. These classes require iOS 10.0+, tvOS 10.0+, macOS 10.12+ or watchOS 3.0+. The code below converts seconds to minutes and seconds.

int seconds = 230;
NSMeasurement* measurement = [[NSMeasurement alloc] initWithDoubleValue:seconds unit:NSUnitDuration.seconds];
NSMeasurement* measurementMinutes = [measurement measurementByConvertingToUnit:NSUnitDuration.minutes];
int minutes = floor(measurementMinutes.doubleValue);
NSMeasurement* measurementMinutesWithoutSeconds = [measurement measurementBySubtractingMeasurement:[[NSMeasurement alloc] initWithDoubleValue:minutes unit:NSUnitDuration.minutes]];
int secondsRemainder = floor([measurementMinutesWithoutSeconds measurementByConvertingToUnit:NSUnitDuration.seconds].doubleValue);
NSLog(@"%d %d", minutes, secondsRemainder); // 3 50


问:
How to execute tshark in python for every file in a folder
I have About 100 .pcap files which i want to analyze. I would like to use tshark for this. My idea is to use a python script to automate this task. It has to run the following command for every .pcap file in my Folder:

```<code>tshark -r filename1.pcap -q -z io,stat,1 >> outfile1.txt
</code>```

So for every filename.pcap I want to have an outfile.txt.

Here is my Approach:

```<code>import os
inputdir = "C:/testfolder"
command = "tshark -r *.pcap -q -z io,stat,1 >> outfile.txt"
for pcapFilename in os.listdir(inputdir):
       if not pcapFilename.endswith(".pcap"):
          continue
       os.system(command)
</code>```

I know this does not work. But at the moment i am a bit stuck.

答:
Why are you using Python if the only thing you want is run an external command? This would make more sense as a shell script or batch script. (I'll give you that Windows batch script sucks.)

import os
import subprocess

inputdir = "C:/testfolder"
with open("outfile.txt","w") as outfile:
    for pcapFilename in os.listdir(inputdir):
         if not pcapFilename.endswith(".pcap"):
            continue
         subprocess.run(["tshark", "-r",
             os.path.join(inputdir, pcapFilename),
             "-q", "-z", "io,stat,1"],
            stdout=outfile, check=True)
```

Body:
I have About 100 .pcap files which i want to analyze. I would like to use tshark for this. My idea is to use a python script to automate this task. It has to run the following command for every .pcap file in my Folder:

tshark -r filename1.pcap -q -z io,stat,1 >> outfile1.txt

So for every filename.pcap I want to have an outfile.txt.

Here is my Approach:

import os
inputdir = "C:/testfolder"
command = "tshark -r *.pcap -q -z io,stat,1 >> outfile.txt"
for pcapFilename in os.listdir(inputdir):
       if not pcapFilename.endswith(".pcap"):
          continue
       os.system(command)

I know this does not work. But at the moment i am a bit stuck.


问:
Making a Python test think an installed package is not available
I have a test that makes sure a specific (helpful) error message is raised, when a required package is not available.

def foo(caller):
    try:
        import pkg
    except ImportError:
        raise ImportError(f'Install "pkg" to use {caller}')
    pkg.bar()

with pytest.raises(ImportError, match='Install "pkg" to use test_function'):
   foo('test_function')
```

However, pkg is generally available, as other tests rely on it.
Currently, I set up an additional virtual env without pkg just for this test. This seems like overkill.

Is it possible to "hide" an installed package within a module or function?

答:
You can mock builtins.__import__.

```<code>from unittest import mock

import pytest

def foo(caller):
    try:
        import pkg
    except ImportError:
        raise ImportError(f'Install "pkg" to use {caller}')
    pkg.bar()

with mock.patch("builtins.__import__", side_effect=ImportError):
    with pytest.raises(ImportError, match='Install "pkg" to use test_function'):
        foo('test_function')
</code>```

Body:
I have a test that makes sure a specific (helpful) error message is raised, when a required package is not available.

def foo(caller):
    try:
        import pkg
    except ImportError:
        raise ImportError(f'Install "pkg" to use {caller}')
    pkg.bar()

with pytest.raises(ImportError, match='Install "pkg" to use test_function'):
   foo('test_function')

However, pkg is generally available, as other tests rely on it.
Currently, I set up an additional virtual env without pkg just for this test. This seems like overkill.

Is it possible to "hide" an installed package within a module or function?

Body:
You can mock builtins.__import__.

from unittest import mock

import pytest

def foo(caller):
    try:
        import pkg
    except ImportError:
        raise ImportError(f'Install "pkg" to use {caller}')
    pkg.bar()

with mock.patch("builtins.__import__", side_effect=ImportError):
    with pytest.raises(ImportError, match='Install "pkg" to use test_function'):
        foo('test_function')


问:
How to hide the bar at the top of "youtube" even when mouse hovers over it?
I am attempting to embed a youtube video, however, I have not discovered a way to keep the bar at the top from showing when the mouse hovers over it. For my purposes it is important that users are not able to have a direct link back to the original video where they can re-watch the video. The following link gives commands for embed features within youtube:

https://developers.google.com/youtube/player_parameters#Overview

I have used the controls and disablekb features to limit viewers ability to skip and replay the video, what I need now is to disable the bar which appears at the top of the video.

(Where I have gotten http://www.youtube.com/embed/bFEoMO0pc7k?controls=0&disablekb=1&egm=1)

答:
Since YouTube has deprecated the showinfo parameter you can trick the player. Youtube will always try to center its video but logo, title, watch later button etc.. will always stay at the left and right side respectively.

So what you can do is put your Youtube iframe inside some div:

```<code><div class="frame-container">
   <iframe></iframe>
</div>
</code>```

Then you can increase the size of frame-container to be out of browser window, while aligning it so that the iframe video comes to the center. Example:

```<code>.frame-container {
    position: relative;
    padding-bottom: 56.25%; /* 16:9 */
    padding-top: 25px;
    width: 300%; /* enlarge beyond browser width */
    left: -100%; /* center */
}

.frame-container iframe {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}
</code>```

Finnaly put everything inside a wrapper div to prevent page stretching due to 300% width:

```<code><div class="wrapper">
   <div class="frame-container">
      <iframe></iframe>
   </div>
</div>

.wrapper {
   overflow: hidden;
   max-width: 100%;
}
</code>```

Body:
Since YouTube has deprecated the showinfo parameter you can trick the player. Youtube will always try to center its video but logo, title, watch later button etc.. will always stay at the left and right side respectively.

So what you can do is put your Youtube iframe inside some div:

<div class="frame-container">
   <iframe></iframe>
</div>

Then you can increase the size of frame-container to be out of browser window, while aligning it so that the iframe video comes to the center. Example:

.frame-container {
    position: relative;
    padding-bottom: 56.25%; /* 16:9 */
    padding-top: 25px;
    width: 300%; /* enlarge beyond browser width */
    left: -100%; /* center */
}

.frame-container iframe {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

Finnaly put everything inside a wrapper div to prevent page stretching due to 300% width:

<div class="wrapper">
   <div class="frame-container">
      <iframe></iframe>
   </div>
</div>

.wrapper {
   overflow: hidden;
   max-width: 100%;
}


问:
How to print a message only once in a loop
I am using for loops combined with if statements to read integers from a text file into a two-dimensional array.

This is my code:

```<code>for (int i = 0; i < MAX_ROWS;i++) {
        for (int j = 0; j < MAX_COLUMNS; j++) {
            inFile >> ArrB[i][j];
            if (ArrB[i][j] == -1) {
                bad = true;
                cout << "The array does not have enough integers" << endl;
                break;
            }
            else {
                if (ArrB[i][j] < 1) {
                    invalidnum = true;
                }
            }

            if (invalidnum = true) {
                cout << *(*(ArrB + i) + j) << " ";
                cout << "There is/are negative number(s) or zero(s) in the array imported from your text file." << endl;

            }
        }
    }
</code>```

This code will read in the first 6 integers (max_row * max_column) from a text file into ArrB.

If  -1 exists in the first 6 integers, it will exit the loop and print out "The array does not have enough integers".

If there is no -1 in the first 6 integers, then it will check all 6 integers to see if there are any other negative numbers or zero.

If there are negative numbers or zero, I want it to still print out the array, then print out the error message (There is/are negative number(s) or zero(s) in the array imported from your text file) ONLY ONCE.

For example, this is my text file. As you can see, there is no -1 in the first 6 numbers, but there is a -7.

So, ideally, the result should be something like:

```<code>2 4 5 6 9 -7

There is/are negative number(s) or zero(s) in the array imported from your text file
</code>```

But this is what I am getting if I run my code above:

-------------------------------------UPDATE--------------------------------------

Figured it out based on @ZedLepplin 's comment

Here is the code:

```<code>for (int i = 0; i < MAX_ROWS;i++) {
        for (int j = 0; j < MAX_COLUMNS; j++) {
            inFile >> ArrB[i][j];
            if (ArrB[i][j] == -1) {
                bad = true;
                cout << "The array does not have enough integers" << endl;
                break;
            }
            else {
                if (ArrB[i][j] < 1) {
                    invalidnum = true;
                }
            }
            cout << *(*(ArrB + i) + j) << " ";
        }
    }
    if (invalidnum == true) {
        cout << "There is/are negative number(s) or zero(s) in the array imported from your text file." << endl;
    }
</code>```

答:
You could just set a counter, and put the message outside of the loop.
Something like :

```<code>int counter = 0;
for(int i = 0; i < MAX_ROWS ; i++) {
    if(myVector[i] == -1) {
        counter++;
    }
    else {
    // Do normal stuff
    }
}
if(counter > 0) {
    cout << "The array contained " << counter << "negative values" << endl;
}
</code>```

Ho, and I'd advise to avoid comparisons to "true". If myVar is a boolean alrady, I can just do if(myVar). No need to do if(myVar == true).
And doing if(myVar = true) is worse, as it sets myVar to true, regardless of its initial value. That's a common typo that can be hard to detect when proofreading code.

Edited version (to adapt to comments) :

```<code>bool earlyNegativeOneFound = false;
int otherNegativeCounter;

    for(int i = 0; i < MAX_ROWS ; i++) {
        if(i < 6 && myVector[i] == -1) {
            earlyNegativeOneFound = true;
            break;
        }
        else if(myVector[i] < 0) {
            cout << myVector[i] << endl;
            otherNegativeCounter++;
        }
        else {
        // Do normal stuff
        }
    }
    if(!earlyNegativeOneFound  && otherNegativeCounter> 0) {
        cout << "The array contained " << otherNegativeCounter << "negative values" << endl;
    }
</code>```

Body:
I am using for loops combined with if statements to read integers from a text file into a two-dimensional array.

This is my code:

for (int i = 0; i < MAX_ROWS;i++) {
        for (int j = 0; j < MAX_COLUMNS; j++) {
            inFile >> ArrB[i][j];
            if (ArrB[i][j] == -1) {
                bad = true;
                cout << "The array does not have enough integers" << endl;
                break;
            }
            else {
                if (ArrB[i][j] < 1) {
                    invalidnum = true;
                }
            }

            if (invalidnum = true) {
                cout << *(*(ArrB + i) + j) << " ";
                cout << "There is/are negative number(s) or zero(s) in the array imported from your text file." << endl;

            }
        }
    }

This code will read in the first 6 integers (max_row * max_column) from a text file into ArrB.

If  -1 exists in the first 6 integers, it will exit the loop and print out "The array does not have enough integers".

If there is no -1 in the first 6 integers, then it will check all 6 integers to see if there are any other negative numbers or zero.

If there are negative numbers or zero, I want it to still print out the array, then print out the error message (There is/are negative number(s) or zero(s) in the array imported from your text file) ONLY ONCE.

For example, this is my text file. As you can see, there is no -1 in the first 6 numbers, but there is a -7.

So, ideally, the result should be something like:

2 4 5 6 9 -7

There is/are negative number(s) or zero(s) in the array imported from your text file

But this is what I am getting if I run my code above:

-------------------------------------UPDATE--------------------------------------

Figured it out based on @ZedLepplin 's comment

Here is the code:

for (int i = 0; i < MAX_ROWS;i++) {
        for (int j = 0; j < MAX_COLUMNS; j++) {
            inFile >> ArrB[i][j];
            if (ArrB[i][j] == -1) {
                bad = true;
                cout << "The array does not have enough integers" << endl;
                break;
            }
            else {
                if (ArrB[i][j] < 1) {
                    invalidnum = true;
                }
            }
            cout << *(*(ArrB + i) + j) << " ";
        }
    }
    if (invalidnum == true) {
        cout << "There is/are negative number(s) or zero(s) in the array imported from your text file." << endl;
    }

Body:
You could just set a counter, and put the message outside of the loop.
Something like :

int counter = 0;
for(int i = 0; i < MAX_ROWS ; i++) {
    if(myVector[i] == -1) {
        counter++;
    }
    else {
    // Do normal stuff
    }
}
if(counter > 0) {
    cout << "The array contained " << counter << "negative values" << endl;
}

Ho, and I'd advise to avoid comparisons to "true". If myVar is a boolean alrady, I can just do if(myVar). No need to do if(myVar == true).
And doing if(myVar = true) is worse, as it sets myVar to true, regardless of its initial value. That's a common typo that can be hard to detect when proofreading code.

Edited version (to adapt to comments) :

bool earlyNegativeOneFound = false;
int otherNegativeCounter;

    for(int i = 0; i < MAX_ROWS ; i++) {
        if(i < 6 && myVector[i] == -1) {
            earlyNegativeOneFound = true;
            break;
        }
        else if(myVector[i] < 0) {
            cout << myVector[i] << endl;
            otherNegativeCounter++;
        }
        else {
        // Do normal stuff
        }
    }
    if(!earlyNegativeOneFound  && otherNegativeCounter> 0) {
        cout << "The array contained " << otherNegativeCounter << "negative values" << endl;
    }


问:
Material ui table not updating
I'm currently updating my react site to 16.8 and have stumbled into an issue with a material ui table. In my app users pick some options, a rest call is then made when a user clicks a button, and the result of said call is added to the table.

Currently the table stays blank even when a result is returned. I've created an example of the behaviour using the material ui table example. (Note that the table data is in the format the web service returns it in, and I have also tried moving the arr.map function into the handleClick function and setting that as Arr, and then simply putting arr inside TableBody)

Does anyone have any idea what I'm doing wrong?

```<code>//imports done above here
//example data used instead of performing rest call

var outRo = {
  id: 'Frozen yoghurt',
  calories: 159,
  fat: 6.0,
  carbs: 24,
  protein: 4.0,
};

export default function SimpleTable() {
  const [arr, setArr] = useState([]);

  function handleClick() {
    console.log('inside');
    //rest call gets data, stores into outRo

    setArr(Array.from(outRo));
  }

  return (
    <div>
      <Button onClick = {handleClick}> Add to Table </Button>
      <TableContainer component={Paper}>
        <Table className={'table'}>
          <TableHead>
            <TableRow>
              <TableCell>Dessert (100g serving)</TableCell>
              <TableCell>Calories</TableCell>
              <TableCell>Fat (g)</TableCell>
              <TableCell>Carbs (g)</TableCell>
              <TableCell>Protein (g)</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {arr.map(row => (
              <TableRow key={row.id}>
                <TableCell>
                  {row.id}
                </TableCell>
                <TableCell>{row.calories}</TableCell>
                <TableCell>{row.fat}</TableCell>
                <TableCell>{row.carbs}</TableCell>
                <TableCell>{row.protein}</TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </TableContainer>
    </div>
  );
}
</code>```

答:
Array.from(outRo) is returning an empty array,

var outRo = {
  id: "Frozen yoghurt",
  calories: 159,
  fat: 6.0,
  carbs: 24,
  protein: 4.0
};

console.log( Array.from(outRo) ); // []```
</div>
</div>
</p>

<p>to add the object to the array, do this :</p>

```function handleClick() {
  setArr([...arr, outRo]);
}
```

Title: Material ui table not updating

Body:
I'm currently updating my react site to 16.8 and have stumbled into an issue with a material ui table. In my app users pick some options, a rest call is then made when a user clicks a button, and the result of said call is added to the table.

Currently the table stays blank even when a result is returned. I've created an example of the behaviour using the material ui table example. (Note that the table data is in the format the web service returns it in, and I have also tried moving the arr.map function into the handleClick function and setting that as Arr, and then simply putting arr inside TableBody)

Does anyone have any idea what I'm doing wrong?

//imports done above here
//example data used instead of performing rest call

var outRo = {
  id: 'Frozen yoghurt',
  calories: 159,
  fat: 6.0,
  carbs: 24,
  protein: 4.0,
};

export default function SimpleTable() {
  const [arr, setArr] = useState([]);

  function handleClick() {
    console.log('inside');
    //rest call gets data, stores into outRo

    setArr(Array.from(outRo));
  }

  return (

      <Button onClick = {handleClick}> Add to Table </Button>
      <TableContainer component={Paper}>

          <TableHead>
            <TableRow>
              <TableCell>Dessert (100g serving)</TableCell>
              <TableCell>Calories</TableCell>
              <TableCell>Fat (g)</TableCell>
              <TableCell>Carbs (g)</TableCell>
              <TableCell>Protein (g)</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {arr.map(row => (
              <TableRow key={row.id}>
                <TableCell>
                  {row.id}
                </TableCell>
                <TableCell>{row.calories}</TableCell>
                <TableCell>{row.fat}</TableCell>
                <TableCell>{row.carbs}</TableCell>
                <TableCell>{row.protein}</TableCell>
              </TableRow>
            ))}
          </TableBody>

      </TableContainer>

  );
}

Body:
Array.from(outRo) is returning an empty array,

var outRo = {
  id: "Frozen yoghurt",
  calories: 159,
  fat: 6.0,
  carbs: 24,
  protein: 4.0
};

console.log( Array.from(outRo) ); // []

to add the object to the array, do this :

function handleClick() {
  setArr([...arr, outRo]);
}


Title: R: How to create a Date object using intervals?

Body:
I am trying to create a Date object with specific features. My original Data set the following:

Year Month Day FivMin   A   B   C   D
2000   1    1    1      1   2   3   4
2000   1    1    2      2   3   0   1
2000   1    1    3      3   4   1   2
2000   1    1    4      0   1   2   3
2000   1    2    1      1   2   3   4
2000   1    2    2      5   3   4   1
2000   1    2    3      3   0   1   2
2000   1    2    4      4   1   9   3
2000   1    3    1      1   2   3   4
2000   1    3    2      0   1   7   1
2000   1    3    3      3   4   1   2
2000   1    3    4      1   -2   2   3
2000   1    4    1      0   2   3   4
2000   1    4    2      2   1   4   1
2000   1    4    3      3   0   1   2
2000   1    4    4      0   2   2   3
2000   1    5    1      1   2   3   4
2000   1    5    2      2   3   4   1
2000   1    5    3      0   -1   1   2
2000   1    5    4      9   1   2   3

The variable FiveMin represents a time interval, it means that 1 is equal to 00:05, 2 is equal to 00:10, and so on. My first idea was to use

Date <- df%>%mutate(date = str_c(year,"/",month,"/",day,"/",fivemin),
         date = ymd_hm(date)%>%
         select(-c(1:8)))

But the result is the following

2020-09-07 01:01:00
2020-09-07 01:02:00
2020-09-07 01:02:00
2020-09-07 01:02:00
NA
NA
NA
NA
2020-09-07 04:01:00
2020-09-07 04:02:00
2020-09-07 04:02:00
2020-09-07 04:02:00
NA
NA
NA
NA

Is there a possibility to use a start for setting the initial hour and the time interval.

Thanks for your help.

Body:
Using base R, we can paste the components required to get date and time and then use as.POSIXct to convert it.

df$DateTime <- with(df, as.POSIXct(paste(Year, Month, Day, FivMin * 5),
                        format = "%Y %m %d %M", tz = "UTC"))
df$DateTime

#[1] "2000-01-01 00:05:00 UTC" "2000-01-01 00:10:00 UTC"
#[3] "2000-01-01 00:15:00 UTC" "2000-01-01 00:20:00 UTC"
#[5] "2000-01-02 00:05:00 UTC" "2000-01-02 00:10:00 UTC"
#[7] "2000-01-02 00:15:00 UTC" "2000-01-02 00:20:00 UTC"
#....

data

df <- structure(list(Year = c(2000L, 2000L, 2000L, 2000L, 2000L, 2000L,
2000L, 2000L, 2000L, 2000L, 2000L, 2000L, 2000L, 2000L, 2000L,
2000L, 2000L, 2000L, 2000L, 2000L), Month = c(1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L
), Day = c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 4L,
4L, 4L, 4L, 5L, 5L, 5L, 5L), FivMin = c(1L, 2L, 3L, 4L, 1L, 2L,
3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L), A = c(1L,
2L, 3L, 0L, 1L, 5L, 3L, 4L, 1L, 0L, 3L, 1L, 0L, 2L, 3L, 0L, 1L,
2L, 0L, 9L), B = c(2L, 3L, 4L, 1L, 2L, 3L, 0L, 1L, 2L, 1L, 4L,
-2L, 2L, 1L, 0L, 2L, 2L, 3L, -1L, 1L), C = c(3L, 0L, 1L, 2L,
3L, 4L, 1L, 9L, 3L, 7L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L
), D = c(4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L,
1L, 2L, 3L, 4L, 1L, 2L, 3L)), class = "data.frame", row.names = c(NA, -20L))


问:
Starting Visual Studio from a command prompt
I have three different versions of Visual Studio installed on my machine,
Visual Studio 2003, Visual Studio 2008, and VS2005.

How do I start a particular version of Visual Studio using a command prompt?

devenv.exe opens the latest version of Visual Studio. What should I do if I want to open Visual Studio 2003 using a command prompt?

答: Haven't tested on preceding versions - but to launch Visual Studio 2019 you can just enter start devenv to launch right away without entering into a path


问:
CRTP Singleton Incomplete type or Non-literal type
I'm trying to make a CRTP Singleton. There's a couple examples on here already. I'm not sure how mine is different or why it fails to compile. First attempt:

```<code>template<class Impl>
class Base
{
public:
  static const Impl& getInstance();
  static int foo(int x);
private:
  static const Impl impl{};
};
template<class Impl> inline
const Impl& Base<Impl>::getInstance()
{
  return impl;
}
template<class Impl> inline
int Base<Impl>::foo(int x)
{
  return impl.foo_impl(x);
}

class Derived1 : public Base<Derived1>
{
public:
  int foo_impl(int x) const;
};
int Derived1::foo_impl(int x) const
{
  return x + 3;
}

int main(int argc, char** argv)
{
  const Derived1& d = Derived1::getInstance();
  std::cout << Derived1::foo(3) << std::endl;
  return 0;
}
</code>```

g++ 7.4.0 tells me: error: in-class initialization of static data member ‘const Derived1 Base<Derived1>::impl’ of incomplete type.

Well. Ok then. Not sure why that type isn't complete. Try:

```<code> . . .
 private:
   static constexpr Impl impl{};
 };
</code>```

Now we fail at link time: undefined reference to 'Base<Derived1>::impl'
Really?! Looks defined and initialized to me... But even if it did link I have a Derived with a non-trivial destructor so then the compiler is going to bomb at compiletime complaining about a non-literal type used in constexpr.

Why isn't Derived1 complete? How can I build this?

答:
The incomplete type error comes from the fact that you use impl in getInstance before it exists.

One way to fix this is initializing impl outside the class definition and make sure it's initialized before being used:

```<code>template <class Impl>
const Impl Base<Impl>::impl {};
</code>```

Body:
I'm trying to make a CRTP Singleton. There's a couple examples on here already. I'm not sure how mine is different or why it fails to compile. First attempt:

template<class Impl>
class Base
{
public:
  static const Impl& getInstance();
  static int foo(int x);
private:
  static const Impl impl{};
};
template<class Impl> inline
const Impl& Base<Impl>::getInstance()
{
  return impl;
}
template<class Impl> inline
int Base<Impl>::foo(int x)
{
  return impl.foo_impl(x);
}

class Derived1 : public Base<Derived1>
{
public:
  int foo_impl(int x) const;
};
int Derived1::foo_impl(int x) const
{
  return x + 3;
}

int main(int argc, char** argv)
{
  const Derived1& d = Derived1::getInstance();
  std::cout << Derived1::foo(3) << std::endl;
  return 0;
}

g++ 7.4.0 tells me: error: in-class initialization of static data member ‘const Derived1 Base<Derived1>::impl’ of incomplete type.

Well. Ok then. Not sure why that type isn't complete. Try:

 . . .
 private:
   static constexpr Impl impl{};
 };

Now we fail at link time: undefined reference to 'Base<Derived1>::impl'
Really?! Looks defined and initialized to me... But even if it did link I have a Derived with a non-trivial destructor so then the compiler is going to bomb at compiletime complaining about a non-literal type used in constexpr.

Why isn't Derived1 complete? How can I build this?

Body:
The incomplete type error comes from the fact that you use impl in getInstance before it exists.

One way to fix this is initializing impl outside the class definition and make sure it's initialized before being used:

template <class Impl>
const Impl Base<Impl>::impl {};


问:
How can i generate a sequence of numbers as text in python
I need to generate a sequence of numbres, for example from 1 to 100 (this number could be much greater) in an array but as text like

```<code>[
    'one',
    'two',
    'three',
    ...
    'one hundred',
]
</code>```

is there a library that do this? or i have to do it manually? and if there is a way to do it in spanish will be a plus.

答:
use inflect:</p>

```<code>>>>import inflect
>>>p = inflect.engine()
>>>p.number_to_words(1234)
u'one thousand, two hundred and thirty-four'
</code>```

Body:
I need to generate a sequence of numbres, for example from 1 to 100 (this number could be much greater) in an array but as text like

[
    'one',
    'two',
    'three',
    ...
    'one hundred',
]

is there a library that do this? or i have to do it manually? and if there is a way to do it in spanish will be a plus.

Body:
use inflect:

>>>import inflect
>>>p = inflect.engine()
>>>p.number_to_words(1234)
u'one thousand, two hundred and thirty-four'


问:
Can joins effectively ignore field indexes if they are a constant?
It is much easier to explain this with an example.

Table A has PK on (store,line).

  Table B has PK on (id,store,line).

  [id] is int, [store] is nvarchar(100) and [line] is int in both cases.

If I run:

```<code>select *
from A inner join B
on A.store=B.store and A.line=B.line
where B.id=0
</code>```

will the engine be able to make a fast (i'm thinking merge) join? Or will it be helpful to add a dummy column id valued 0 in A?

答:
Your statement will work but if you do it like this the optimizer will be more effective:

```<code>select *
from A inner
join B on A.store=B.store and A.line=B.line and B.id=0
</code>```

Here is is able to exclude items where b.id does not equal zero before it does the merge.  Depending on table size topology etc this could be quite significant.

For example consider the case where you have 50 million rows shared across 5 nodes table b and 1 node for table a -- in your code all records would have to be moved to the node with the a table while with the code above only the records that have id = 0 would need to be moved.

This can be very non-intuitive when a is a small table (which are often only on one node.)

Body:
It is much easier to explain this with an example.

Table A has PK on (store,line).

  Table B has PK on (id,store,line).

  [id] is int, [store] is nvarchar(100) and [line] is int in both cases.

If I run:

select *
from A inner join B
on A.store=B.store and A.line=B.line
where B.id=0

will the engine be able to make a fast (i'm thinking merge) join? Or will it be helpful to add a dummy column id valued 0 in A?

Body:
Your statement will work but if you do it like this the optimizer will be more effective:

select *
from A inner
join B on A.store=B.store and A.line=B.line and B.id=0

Here is is able to exclude items where b.id does not equal zero before it does the merge.  Depending on table size topology etc this could be quite significant.

For example consider the case where you have 50 million rows shared across 5 nodes table b and 1 node for table a -- in your code all records would have to be moved to the node with the a table while with the code above only the records that have id = 0 would need to be moved.

This can be very non-intuitive when a is a small table (which are often only on one node.)


问:
How to avoid generated duplicade html code in javascript
Maybe this is a common question in javascript world, but i can't find any usefull keyword for a profitable search. Long story short:

I have html code generated server side, suppose something like this

```<code><div id="container">
    <div class="element">
        <!-- yadayada -->
    </div>

    <div class="element">
        <!-- yadayada -->
    </div>
</div>
</code>```

and a client script to add new elements without reloading the page

```<code><script>
    // do asynchronous server stuff, then add new div from json server output
    var string = "<div class=\"element\">\n" +
                 "    <!-- yadayada -->\n" +
                 "</div>";
    $("#container").prepend($(string));
</script>
</code>```

Well, if the  internal layout is changed in the server scripts, the javascript code must also be changed.

How can I avoid this ? how can I have only one maintainable source for the yadayada layout ?

答:
Clone the first of the elements and prepend it to the container like so:

$('.element:first').clone().prependTo('#container');
```

Body:
Maybe this is a common question in javascript world, but i can't find any usefull keyword for a profitable search. Long story short:

I have html code generated server side, suppose something like this

and a client script to add new elements without reloading the page

Well, if the  internal layout is changed in the server scripts, the javascript code must also be changed.

How can I avoid this ? how can I have only one maintainable source for the yadayada layout ?


问:
Elements keep going stale using PageFactory
I have a list of objects i want to confirm some attributes on, the issue is that they reload on the page around once a second.

Whenever I try to refer to any of the elements in the list i get a stale element exception.
I tried refreshing the elements just before checking but i still get the exception.

Is it possible to cache the elements when i initialize them?

This is how i get the elements:

```<code>            [FindsBy(How = How.XPath, Using = @"//*[@id='Log']/table/tbody/tr/td[4]")]
            public IList<IWebElement> logs;
</code>```

答:
You need to make use of CacheLookup, try once</p>

```<code>[FindsBy(How = How.XPath, Using = @"//*[@id='Log']/table/tbody/tr/td[4]")][CacheLookup]
public IList<IWebElement> logs;
</code>```

Body:
I have a list of objects i want to confirm some attributes on, the issue is that they reload on the page around once a second.

Whenever I try to refer to any of the elements in the list i get a stale element exception.
I tried refreshing the elements just before checking but i still get the exception.

Is it possible to cache the elements when i initialize them?

This is how i get the elements:

            [FindsBy(How = How.XPath, Using = @"//*[@id='Log']/table/tbody/tr/td[4]")]
            public IList<IWebElement> logs;

Body:
You need to make use of CacheLookup, try once

[FindsBy(How = How.XPath, Using = @"//*[@id='Log']/table/tbody/tr/td[4]")][CacheLookup]
public IList<IWebElement> logs;


问:
color switch after the 2nd button click
how can i use the "switch statement" to switch the colors from button 1 to button 2, after the 2nd click?
these are my 2 button clicks</p>

```<code>private int lCount = 0;
private int rCount = 0;
private int myCount = lCount & rCount;

final TextView countTextViewPlusL = (TextView) findViewById(R.id.TextViewCountL);
final Button countButtonPlusL = (Button) findViewById(R.id.ButtonCountPlusL);

countButtonPlusL.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
        myCount++;
          if(myCount%2 == 0){
             countTextViewPlusL.setBackgroundColor(0xffffffff);}
          else countTextViewPlusL.setBackgroundColor(0x00000000);
        lCount++;
        if (lCount >-1)
        countTextViewPlusL.setText("" + lCount);
    }
});

final TextView countTextViewPlusR = (TextView) findViewById(R.id.TextViewCountR);
final Button countButtonPlusR = (Button) findViewById(R.id.ButtonCountPlusR);

countButtonPlusR.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
        myCount++;
          if(myCount%2 == 0){
            countTextViewPlusR.setBackgroundColor(0xffffffff);}
          else countTextViewPlusR.setBackgroundColor(0x00000000);
        rCount++;
        if (rCount >-1)
        countTextViewPlusR.setText("" + rCount);
    }
});
</code>```

答: You are incrementing lCount and/or rCount in your listeners, but you are testing myCount for parity. That's why things don't change.

Title: color switch after the 2nd button click

Body:
how can i use the "switch statement" to switch the colors from button 1 to button 2, after the 2nd click?
these are my 2 button clicks

private int lCount = 0;
private int rCount = 0;
private int myCount = lCount & rCount;

final TextView countTextViewPlusL = (TextView) findViewById(R.id.TextViewCountL);
final Button countButtonPlusL = (Button) findViewById(R.id.ButtonCountPlusL);

countButtonPlusL.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
        myCount++;
          if(myCount%2 == 0){
             countTextViewPlusL.setBackgroundColor(0xffffffff);}
          else countTextViewPlusL.setBackgroundColor(0x00000000);
        lCount++;
        if (lCount >-1)
        countTextViewPlusL.setText("" + lCount);
    }
});

final TextView countTextViewPlusR = (TextView) findViewById(R.id.TextViewCountR);
final Button countButtonPlusR = (Button) findViewById(R.id.ButtonCountPlusR);

countButtonPlusR.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
        myCount++;
          if(myCount%2 == 0){
            countTextViewPlusR.setBackgroundColor(0xffffffff);}
          else countTextViewPlusR.setBackgroundColor(0x00000000);
        rCount++;
        if (rCount >-1)
        countTextViewPlusR.setText("" + rCount);
    }
});


问:
How can I implement Owl Carousel in react without use the Owl Carousel 2 component?
How can I implement Owl Carousel 2 in react, when I use the Owl Carousel 2 component needs updates:

react-dom.development.js:12357 Warning: componentWillReceiveProps has been renamed, and is not recommended for use. See fb.me/react-unsafe-component-lifecycles for details.

Move data fetching code or side effects to componentDidUpdate.

If you're updating state whenever props change, refactor your code to use memoization techniques or move it to static getDerivedStateFromProps. Learn more at: fb.me/react-derived-state

Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run npx react-codemod rename-unsafe-lifecycles in your project source folder.

Please update the following components: OwlCarousel

So, I wonder how can I implement the library in React without the component OwlCarousel2 .

Thanks.

答:
As per Owl Carousel's Github repo its deprecated.
https://github.com/OwlCarousel2/OwlCarousel2

They recommend to use following: https://github.com/ganlanyuan/tiny-slider


问:
Python subprocess command answering prompt
I am trying to call a command

```<code>ionic cordova prepare
</code>```

which prompts for a "Y/N" response. I always want this to be yes. When i tried using os.system it would hang at the last part and not move onto the rest of the script. Does anyone know the right way of writing this.

This is what i tried

```<code>foo_proc = Popen(['ionic', 'cordova', 'prepare'], stdin=PIPE, stdout=PIPE)
yes_proc = Popen(['yes', 'y'], stdout=foo_proc.stdin)
foo_proc.communicate()[0]
yes_proc.wait()
</code>```

But it just hangs on the command and doesn't seem to execute

答:
This work for me:

foo_proc = Popen(['ionic', 'cordova', 'prepare'], stdin=PIPE, stdout=PIPE)
foo_proc.stdin.write(b"y\n")
outputlog, errorlog = foo_proc.communicate()
foo_proc.stdin.close()
```

Body:
I am trying to call a command

ionic cordova prepare

which prompts for a "Y/N" response. I always want this to be yes. When i tried using os.system it would hang at the last part and not move onto the rest of the script. Does anyone know the right way of writing this.

This is what i tried

foo_proc = Popen(['ionic', 'cordova', 'prepare'], stdin=PIPE, stdout=PIPE)
yes_proc = Popen(['yes', 'y'], stdout=foo_proc.stdin)
foo_proc.communicate()[0]
yes_proc.wait()

But it just hangs on the command and doesn't seem to execute


问:
How to push a json object into array using R
I have tried several technics to push json object into an array and to save in the same format of the below example, but without success.

Is anyone has a solution to do it in R ?

Thanks you

EDIT :

I found the solution.

```<code>library(jsonlite)

#Set an empty list
list1 <- vector(mode = 'list', length = 2)

# data example
json_data <- list(object1 = list(birthday = '2000-02-14', Age = '20'),
              object2 = list(Candidate_Number = '1999283', first_attempt = TRUE),
              object3 = list(name = 'John E.', result = list(), study_hours = 150, GPA = 3.8, exam_infos = list(cost = 800, location = 'F3C6V9', past_exams = list(list(exam_name = 'Science', score = 'passed'), list(exam_name = 'Geometric', score = 'passed')))),
              object4 = list(study_manual_used = 'Physics Theory', version_found = list(Digital = '1999-01-01', Paper = '1999-01-01')))

# append data into json
for(i in length(list1)){

  list1[[i]] <- json_data

}

# Write to json on his home
write(toJSON(list1, auto_unbox = TRUE, pretty = TRUE), file.path(Sys.getenv()['USERPROFILE'], 'file.json'))
</code>```

答:
To save object as JSON you can use package rjson.

```<code>library("rjson")

# example data
list1 <- list()
list1[[1]] <- c(created_at="1910-02-03", id="212", field="1")
list1[[2]] <- c(created_at="1910-01-02", id="218", field="3")

# to json
toJSON(list1)
</code>```

and

```<code>write(toJSON(list1), "file.json")
</code>```

If the issue is that you created data.frame and need to make it back into json. You have to make it a list by row as:

```<code># example data
dta <- as.data.frame(rbind(c(created_at="1910-02-03", id="212", field="1"), c(created_at="1910-01-02", id="218", field="3")))

# to json
toJSON(list(dta[1,],dta[2,]))
</code>```

Body:
I have tried several technics to push json object into an array and to save in the same format of the below example, but without success.

Is anyone has a solution to do it in R ?

Thanks you

EDIT :

I found the solution.

library(jsonlite)

#Set an empty list
list1 <- vector(mode = 'list', length = 2)

# data example
json_data <- list(object1 = list(birthday = '2000-02-14', Age = '20'),
              object2 = list(Candidate_Number = '1999283', first_attempt = TRUE),
              object3 = list(name = 'John E.', result = list(), study_hours = 150, GPA = 3.8, exam_infos = list(cost = 800, location = 'F3C6V9', past_exams = list(list(exam_name = 'Science', score = 'passed'), list(exam_name = 'Geometric', score = 'passed')))),
              object4 = list(study_manual_used = 'Physics Theory', version_found = list(Digital = '1999-01-01', Paper = '1999-01-01')))

# append data into json
for(i in length(list1)){

  list1[[i]] <- json_data

}

# Write to json on his home
write(toJSON(list1, auto_unbox = TRUE, pretty = TRUE), file.path(Sys.getenv()['USERPROFILE'], 'file.json'))

Body:
To save object as JSON you can use package rjson.

library("rjson")

# example data
list1 <- list()
list1[[1]] <- c(created_at="1910-02-03", id="212", field="1")
list1[[2]] <- c(created_at="1910-01-02", id="218", field="3")

# to json
toJSON(list1)

and

write(toJSON(list1), "file.json")

If the issue is that you created data.frame and need to make it back into json. You have to make it a list by row as:

# example data
dta <- as.data.frame(rbind(c(created_at="1910-02-03", id="212", field="1"), c(created_at="1910-01-02", id="218", field="3")))

# to json
toJSON(list(dta[1,],dta[2,]))


问:
JS onclick image redirect to same image html
I'm not really sure how to explain this, but what I'm trying to do is: when you click a certain image on the page, have it redirect you to another page, where there's basically the same picture, only the page/link is a html one, not only the path to the image, like this: "file:///C:/Users/x/Desktop/report/img/3.jpg".

The code I've seen around is this:

```<code>
   img.onclick = function(event) {
        window.location.href = this.src + '.html';
    }

</code>```

Everything is generated from JS, so I have no HTML code hard coded.

The above code works if I scratch the '.html' part, but like I've said earlier, it only redirects me to the jpg, or, if I leave the '.html' bit in too, it just goes like this "file:///C:/Users/x/Desktop/report/.html" and nothing shows up.

What I'd like to have is a new html page so I can later add other things/info around my image.

I'm new to programming so I am not really sure how/ if this is possible. Any help is appreciated, thanks!

答:
You first have an img tag with the onClick property as follows:

Then write script :

```<code><script>
        function GetImage(imageAddress) {
            window.open(imageAddress);
        }
</script>
</code>```

Body:
I'm not really sure how to explain this, but what I'm trying to do is: when you click a certain image on the page, have it redirect you to another page, where there's basically the same picture, only the page/link is a html one, not only the path to the image, like this: "file:///C:/Users/x/Desktop/report/img/3.jpg".

The code I've seen around is this:

   img.onclick = function(event) {
        window.location.href = this.src + '.html';
    }

Everything is generated from JS, so I have no HTML code hard coded.

The above code works if I scratch the '.html' part, but like I've said earlier, it only redirects me to the jpg, or, if I leave the '.html' bit in too, it just goes like this "file:///C:/Users/x/Desktop/report/.html" and nothing shows up.

What I'd like to have is a new html page so I can later add other things/info around my image.

I'm new to programming so I am not really sure how/ if this is possible. Any help is appreciated, thanks!

Body:
You first have an img tag with the onClick property as follows:

<div class="col-12 col-md-4 col-lg-3">
      <img onclick="GetImage(@ImageAddress)"/>
</div>

Then write script :

<script>
        function GetImage(imageAddress) {
            window.open(imageAddress);
        }
</script>


问:
How to open Facebook / Twitter app from my iOS app in Xamarin?
I'm developing an iOS app with Xamarin, in C#.

I have a "contact" UIViewController, with some buttons, including Facebook and Twitter.

I need to open the Facebook and Twitter App with a specific Facebook Page and Twitter profile from my app.

What is the best way to do this?

答: For those arriving at this page after me, the Device class has been deprecated. You should now use the Launcher class from the Xamarin.Essentials package.</p>


问:
Wait for Facebook Pixel Load
I want to detect in my JavaScript code that the load of a Facebook pixel has been completed. Is this possible?

For reference here is the Facebook Pixel Tracking code:

```<code><script>
!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;
n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;
t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,
document,'script','//connect.facebook.net/en_US/fbevents.js');
// Insert Your Facebook Pixel ID below.
fbq('init', 'FB_PIXEL_ID');
fbq('track', 'PageView');
</script>
<!-- Insert Your Facebook Pixel ID below. -->
<noscript><img height="1" width="1" style="display:none"
src="https://www.facebook.com/tr?id=FB_PIXEL_ID&ev=PageView&noscript=1"
/></noscript>
</code>```

Breaking it down, it seems that fbq('init', ...) causes a script tag to be added with the async attribute set and src set to //connect.facebook.net/en_US/fbevents.js.

Subsequently the call to fbq('track', ...) somehow causes an HTTP GET to an image via one redirect.

How to detect that all the steps are complete, especially that the final image load is complete?

答:
So Kelly Seldens solution looks great but didnt work for me due to facebook changing their library. My solution is derived from Kelly Seldens and is as follows (applicable to facebook 2.9.15). I offer it up for other people looking for solutions to firing off actions based on facebook pixel being loaded.

In my case, I have Mautic loading the fb pixel on its own. I needed a way to detect when this occured so that I could fire off a conversion event (fb - track lead).

The changes I made to Kelly's code reflects 2 things:

First I added in the condition checking if fbq is defined. Before doing this I was getting console errors that fbq was undefined each time the timeout executed.

Second, I removed the fbq.on statement simple because it doesnt exist anymore in the 2.9.15 version of the pixel being loaded by Mautic.

The final code I ended up with is:

```<code>(function wait() {
    //first check if the fbq object is defined, then check the version (probably not needed but for good measure

    if ((typeof fbq !== 'undefined') && (fbq.version > '2.9')) {
        //fire off the call back / tracking event
        myCallBack(); //fbq('track', 'Lead');
    }
else
  setTimeout(wait, 10);
})();
</code>```

Title: Wait for Facebook Pixel Load

Body:
I want to detect in my JavaScript code that the load of a Facebook pixel has been completed. Is this possible?

For reference here is the Facebook Pixel Tracking code:

Breaking it down, it seems that fbq('init', ...) causes a script tag to be added with the async attribute set and src set to //connect.facebook.net/en_US/fbevents.js.

Subsequently the call to fbq('track', ...) somehow causes an HTTP GET to an image via one redirect.

How to detect that all the steps are complete, especially that the final image load is complete?

Body:
So Kelly Seldens solution looks great but didnt work for me due to facebook changing their library. My solution is derived from Kelly Seldens and is as follows (applicable to facebook 2.9.15). I offer it up for other people looking for solutions to firing off actions based on facebook pixel being loaded.

In my case, I have Mautic loading the fb pixel on its own. I needed a way to detect when this occured so that I could fire off a conversion event (fb - track lead).

The changes I made to Kelly's code reflects 2 things:

First I added in the condition checking if fbq is defined. Before doing this I was getting console errors that fbq was undefined each time the timeout executed.

Second, I removed the fbq.on statement simple because it doesnt exist anymore in the 2.9.15 version of the pixel being loaded by Mautic.

The final code I ended up with is:

(function wait() {
    //first check if the fbq object is defined, then check the version (probably not needed but for good measure

    if ((typeof fbq !== 'undefined') && (fbq.version > '2.9')) {
        //fire off the call back / tracking event
        myCallBack(); //fbq('track', 'Lead');
    }
else
  setTimeout(wait, 10);
})();


问:
`javac` doesn't see Android support library when building Android application manually
I build Android application manually from command line. I use javac to compile it. Everything is OK when I don't use Android Support V4 library. For any reason, javac doesn't see this jar file.

My command line follows:

"c:\Program Files\Java\bin\javac.exe" -deprecation -Xlint:-options -source 1.7 -target 1.7 -d classes -cp "C:\Users\Developer\Android\sdk\platforms\android-23\android.jar";"C:\Users\Developer\Android\sdk\extras\android\m2repository\com\android\support\support-v4\23.4.0\support-v4-23.4.0-sources.jar";"C:\Users\Developer\Android\sdk\platforms\android-23\optional\org.apache.http.legacy.jar";classes -sourcepath java @fileslist.txt

Here I put reference to "C:\Users\Developer\Android\sdk\extras\android\m2repository\com\android\support\support-v4\23.4.0\support-v4-23.4.0-sources.jar", it is path to Android Support v4 library. The jar file exists, and when I open it with Java decompiler, I see that it contains android.support.v4.app.FragmentActivity class definition. However, javac doesn't see it, and I receive following error:

error: package android.support.v4.app does not exist

What is the reason? Has javac any limits on jar files count, or on command line length, etc?

答:
I'm investigating a similar but different issue. I wish to but not need to point to the entire support folder. My APK compiled but breaks down with AppCompatActivity but runs fine with Activity.

On the other hand, you need to copy your jars to your project's "libs" directory, then add the extdirs option when running the java compiler. To that option add the "libs" directory, like so;

```<code>copy C:\...\support-v4-23.4.0-sources.jar <path to project>\libs\support-v4-23.4.0-sources.jar

javac @normal_options -extdir <path to project>\libs\ @sources
</code>```

Your project should compile OK. But you may be in the same predicament as I am in. I am unsure if the support library has wide spanning dependencies. Copying the one jar left me in my current predicament.

Body:
I'm investigating a similar but different issue. I wish to but not need to point to the entire support folder. My APK compiled but breaks down with AppCompatActivity but runs fine with Activity.

On the other hand, you need to copy your jars to your project's "libs" directory, then add the extdirs option when running the java compiler. To that option add the "libs" directory, like so;

copy C:\...\support-v4-23.4.0-sources.jar <path to project>\libs\support-v4-23.4.0-sources.jar

javac @normal_options -extdir <path to project>\libs\ @sources

Your project should compile OK. But you may be in the same predicament as I am in. I am unsure if the support library has wide spanning dependencies. Copying the one jar left me in my current predicament.


问:
oracle pl-sql find the 3rd wednesday of a given date
Currently I have a process which takes a date variable EG: '01-MAR-2026', it then iterates over this date checking if the day is wednesday. If so then increment a counter else add 1 day and check again.
This exits when the wednesday count is = 3.

```<code>IF (to_char(v_Date,'dy') = 'wed') THEN
        v_NumWed := v_NumWed + 1;
END IF;

WHILE (v_NumWed != 3) LOOP
    v_Date := v_Date + interval '1' day;
    IF (to_char(v_Date, 'dy') = 'wed') THEN
        v_NumWed := v_NumWed + 1;
    END IF;
END LOOP;
</code>```

However I have a feeling there is a simpler way to achieve this maybe via a query or something not using a loop EG: use an input date and query to find the first wednesday then + 14 days?

Any suggestions would be great, thanks in advance :)

EDIT: I have something like this which appears to work, also considers if the first day is a wednesday itself.

```<code>select next_day(trunc(v_date, 'MM') - 1, 'WED'), next_day(trunc(v_date, 'MM') - 1, 'WED') + 14 into v_first, v_third from dual;
</code>```

SOLVED: thanks for the help folks, got a few possible solutions now in the comments!

答:
I know you already solved the issue, just wanted to show you another example:

```<code>DECLARE
        dStartDate DATE := SYSDATE;
        dNextWednesDay DATE;
BEGIN
        FOR n IN 1..3 LOOP
                dNextWednesDay := NEXT_DAY(dStartDate, 'WEDNESDAY');
                DBMS_OUTPUT.PUT_LINE(dNextWednesDay);

                dStartDate := dNextWednesDay +1;
        END LOOP;
END;
/
</code>```

Output:

```<code>2020-02-19 15:33:58
2020-02-26 15:33:58
2020-03-04 15:33:58
</code>```

Body:
Currently I have a process which takes a date variable EG: '01-MAR-2026', it then iterates over this date checking if the day is wednesday. If so then increment a counter else add 1 day and check again.
This exits when the wednesday count is = 3.

IF (to_char(v_Date,'dy') = 'wed') THEN
        v_NumWed := v_NumWed + 1;
END IF;

WHILE (v_NumWed != 3) LOOP
    v_Date := v_Date + interval '1' day;
    IF (to_char(v_Date, 'dy') = 'wed') THEN
        v_NumWed := v_NumWed + 1;
    END IF;
END LOOP;

However I have a feeling there is a simpler way to achieve this maybe via a query or something not using a loop EG: use an input date and query to find the first wednesday then + 14 days?

Any suggestions would be great, thanks in advance :)

EDIT: I have something like this which appears to work, also considers if the first day is a wednesday itself.

select next_day(trunc(v_date, 'MM') - 1, 'WED'), next_day(trunc(v_date, 'MM') - 1, 'WED') + 14 into v_first, v_third from dual;

SOLVED: thanks for the help folks, got a few possible solutions now in the comments!

Body:
I know you already solved the issue, just wanted to show you another example:

DECLARE
        dStartDate DATE := SYSDATE;
        dNextWednesDay DATE;
BEGIN
        FOR n IN 1..3 LOOP
                dNextWednesDay := NEXT_DAY(dStartDate, 'WEDNESDAY');
                DBMS_OUTPUT.PUT_LINE(dNextWednesDay);

                dStartDate := dNextWednesDay +1;
        END LOOP;
END;
/

Output:

2020-02-19 15:33:58
2020-02-26 15:33:58
2020-03-04 15:33:58


问:
HTML binding in Angular 8
I am unable to display html content to Angular 8.

**Note: I am receiving html template which I need to display on Angular is coming from database as a JSON, which I am fetching it and saving it to a variable (e.g, plot) and then passing that variable to this.myTemplate = this.sanitizer.bypassSecurityTrustHtml(this.plot)

For demo purpose I put a sample html template similar to my data which I am getting it from database.

HTML:

```<code><div [innerHTML]="myTemplate"></div>
</code>```

app.component.ts:

```<code>import { Component, OnInit} from '@angular/core';
import { DomSanitizer, SafeHtml} from '@angular/platform-browser';

@Component({
  selector: 'app-data-decomposition',
  templateUrl: './data-decomposition.component.html',
  styleUrls: ['./data-decomposition.component.css']

})

export class DataDecompositionComponent implements OnInit {

myTemplate:SafeHtml;

constructor(private sanitizer: DomSanitizer) { }

this.myTemplate = this.sanitizer.bypassSecurityTrustHtml(`<html>
  <head>
    <!-- Load plotly.js into the DOM -->
    <script src='https://cdn.plot.ly/plotly-latest.min.js'></script>
</head>

<body>
<p>plot come below...</>
    <div id='myDiv'><!-- Plotly chart will be drawn inside this DIV --></div>

  <script type="text/javascript">
  var data = [
    {
      x: ['giraffes', 'orangutans', 'monkeys'],
      y: [20, 14, 23],
      type: 'bar'
    }
  ];

  Plotly.newPlot('myDiv', data);

  </script>
  </body>
  </html>`);

}
</code>```

When I run the code only the
 tag content "Plot come below.." is displaying to the Angular front-end but the Plotly chart which is inside

答:
Take your scripts tags to index.html. In your component, you can't reach script tags.Also don't forget to close
 tag correctly :)

```<code><script src='https://cdn.plot.ly/plotly-latest.min.js'></script>
<script type="text/javascript">
  var data = [
    {
      x: ['giraffes', 'orangutans', 'monkeys'],
      y: [20, 14, 23],
      type: 'bar'
    }
  ];

  Plotly.newPlot('myDiv', data);

  </script>
</code>```

Example: https://stackblitz.com/edit/angular-83tffr

Title: HTML binding in Angular 8

Body:
I am unable to display html content to Angular 8.

**Note: I am receiving html template which I need to display on Angular is coming from database as a JSON, which I am fetching it and saving it to a variable (e.g, plot) and then passing that variable to this.myTemplate = this.sanitizer.bypassSecurityTrustHtml(this.plot)

For demo purpose I put a sample html template similar to my data which I am getting it from database.

HTML:

app.component.ts:

import { Component, OnInit} from '@angular/core';
import { DomSanitizer, SafeHtml} from '@angular/platform-browser';

@Component({
  selector: 'app-data-decomposition',
  templateUrl: './data-decomposition.component.html',
  styleUrls: ['./data-decomposition.component.css']

})

export class DataDecompositionComponent implements OnInit {

myTemplate:SafeHtml;

constructor(private sanitizer: DomSanitizer) { }

this.myTemplate = this.sanitizer.bypassSecurityTrustHtml(`

plot come below...</>

  `);

}

When I run the code only the
 tag content "Plot come below.." is displaying to the Angular front-end but the Plotly chart which is inside

Body:
Take your scripts tags to index.html. In your component, you can't reach script tags.Also don't forget to close
 tag correctly :)

<script src='https://cdn.plot.ly/plotly-latest.min.js'></script>
<script type="text/javascript">
  var data = [
    {
      x: ['giraffes', 'orangutans', 'monkeys'],
      y: [20, 14, 23],
      type: 'bar'
    }
  ];

  Plotly.newPlot('myDiv', data);

  </script>

Example: https://stackblitz.com/edit/angular-83tffr


问:
How to select the inside of jQuery variable
I have some HTML in a jQuery object:

```<code>var $div = $(`
  <div class="myDiv">
    <p class="name"></p>
    <p class="data"></p>
  </div>`);
</code>```

I want to change the content of the
 elements, so I tried like this but in vain:

```<code>// Attempt #1
$div.".name".html("name here");

// Attempt #2
$div."> P".html("name here");
</code>```

How can I use a selector to get the inside of jQuery variable?

答:
Just as you would do when the elements are in the DOM, you need to use find() to retrieve elements within the object. Try this:

var $div = $(`

`);

$div.find('p').text('name here');
$div.appendTo('body');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>```

Body:
I have some HTML in a jQuery object:

var $div = $(`

`);

I want to change the content of the
 elements, so I tried like this but in vain:

// Attempt #1
$div.".name".html("name here");

// Attempt #2
$div."> P".html("name here");

How can I use a selector to get the inside of jQuery variable?

Body:
Just as you would do when the elements are in the DOM, you need to use find() to retrieve elements within the object. Try this:

var $div = $(`<div class="myDiv">
  <p class="name"></p>
  <p class="data"></p>
</div>`);

$div.find('p').text('name here');
$div.appendTo('body');

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


问:
Get IServiceCollection in Service?
Is there a way to get the IServiceCollection we use at Startup in a Service?
I want to get a list of all current services.
Taking a dependency on it does not work, as the servicecollection is not registered in the DI</p>

```<code>public class Test
{
    public Test(IServiceCollection collection)
    {
        this.services=collection;
    }
}
</code>```

答: No, it isn't, because IServiceCollection is not registered on the DI. You can, however, inject the IServiceProvider itself, from which you can obtain any service.

Title: Get IServiceCollection in Service?

Body:
Is there a way to get the IServiceCollection we use at Startup in a Service?
I want to get a list of all current services.
Taking a dependency on it does not work, as the servicecollection is not registered in the DI

public class Test
{
    public Test(IServiceCollection collection)
    {
        this.services=collection;
    }
}


问:
Toast.makeText and Log not showing for Location Service
Currently making a Location Service for an app I'm currently building. I'm trying to print the obtained latitude and longitude through a Log and through a Toast.makeText from a broadcast receiver but nothing is showing when I run. Was hoping if you guys could see any faults.

LocationService.java

```<code>import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;

public class LocationService extends Service {

FusedLocationProviderClient fusedLocationProviderClient;
LocationCallback locationCallback;

@Override
public IBinder onBind(Intent intent) {
return null;
}

@Override
public void onCreate() {
    super.onCreate();
    fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
    locationCallback = new LocationCallback(){

        // Whenever there is a Location Update, this method is where it occurs
        @Override
        public void onLocationResult(LocationResult locationResult) {
            super.onLocationResult(locationResult);
            // Log Result for Longitude and Latitude, call method to receive elsewhere
            Log.d("Location Log", "Latitude is: " + locationResult.getLastLocation().getLatitude() +
                    "Longitude is: " + locationResult.getLastLocation().getLongitude());
            Intent intent = new Intent("ACT_LOC");
            intent.putExtra("Latitude", locationResult.getLastLocation().getLatitude());
            intent.putExtra("Longitude", locationResult.getLastLocation().getLongitude());
            sendBroadcast(intent);
        }
    };
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    requestLocation();
    return super.onStartCommand(intent, flags, startId);
}

// Method to request the Location every 3 seconds
private void requestLocation(){
    LocationRequest locationRequest = new LocationRequest();
    locationRequest.setInterval(3000);
    fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback,
    Looper.myLooper());
}
}
</code>```

MainActivity.java

```<code>import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.widget.Toast;

import com.google.android.gms.location.LocationServices;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if(Build.VERSION.SDK_INT >= 23){
        // If the permission Access Fine Location is not granted
        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) !=
            PackageManager.PERMISSION_GRANTED){
            // Request Location
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
        }
        else{
            // Request Location Permission
            startService();
        }
    }
    else{
        // Start Location Service
        startService();
    }
}

// Start the service with a new intent for the MainActivity and Location Services
// Register Broadcast Receiver with intent action from LocationService.java
void startService(){
    LocationBroadcastReceiver receiver = new LocationBroadcastReceiver();
    IntentFilter filter = new IntentFilter("ACT_LOC");
    Intent intent = new Intent(MainActivity.this, LocationServices.class);
    startService(intent);
    registerReceiver(receiver, filter);
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch(requestCode){
        case 1:
            if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
                startService();
            }
            else{
                Toast.makeText(this, "Give me permissions", Toast.LENGTH_LONG).show();
            }
    }
}

public class LocationBroadcastReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        // check if action is required or not
        if(intent.getAction().equals("ACT_LOC")){
            double lat = intent.getDoubleExtra("Latitude", 0f);
            double lng = intent.getDoubleExtra("Longitude", 0f);
            Toast.makeText(MainActivity.this, "Latitude is: " + lat + ", Longitude is: " + lng, Toast.LENGTH_LONG).show();
        }
    }
}
}
</code>```

AndroidManifest

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.anongeolocation">

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <category android:name="android.intent.category.LAUNCHER"/>
                <action android:name="android.intent.action.MAIN"/>
            </intent-filter>
        </activity>
        <service android:name=".LocationService"/>
    </application>

</manifest>
</code>```

Any help would be greatly appreciated. Thanks in advance.

答: If log or toast doesnt run it could only have one reason.the compiler doesnt get into their methods somehow.i suggest you log everywhere compiler can  go from on create of main activity and follow logs one by one to find out where exactly compiler is!</p>

Body:
Currently making a Location Service for an app I'm currently building. I'm trying to print the obtained latitude and longitude through a Log and through a Toast.makeText from a broadcast receiver but nothing is showing when I run. Was hoping if you guys could see any faults.

LocationService.java

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;

public class LocationService extends Service {

FusedLocationProviderClient fusedLocationProviderClient;
LocationCallback locationCallback;

@Override
public IBinder onBind(Intent intent) {
return null;
}

@Override
public void onCreate() {
    super.onCreate();
    fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
    locationCallback = new LocationCallback(){

        // Whenever there is a Location Update, this method is where it occurs
        @Override
        public void onLocationResult(LocationResult locationResult) {
            super.onLocationResult(locationResult);
            // Log Result for Longitude and Latitude, call method to receive elsewhere
            Log.d("Location Log", "Latitude is: " + locationResult.getLastLocation().getLatitude() +
                    "Longitude is: " + locationResult.getLastLocation().getLongitude());
            Intent intent = new Intent("ACT_LOC");
            intent.putExtra("Latitude", locationResult.getLastLocation().getLatitude());
            intent.putExtra("Longitude", locationResult.getLastLocation().getLongitude());
            sendBroadcast(intent);
        }
    };
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    requestLocation();
    return super.onStartCommand(intent, flags, startId);
}

// Method to request the Location every 3 seconds
private void requestLocation(){
    LocationRequest locationRequest = new LocationRequest();
    locationRequest.setInterval(3000);
    fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback,
    Looper.myLooper());
}
}

MainActivity.java

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.widget.Toast;

import com.google.android.gms.location.LocationServices;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if(Build.VERSION.SDK_INT >= 23){
        // If the permission Access Fine Location is not granted
        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) !=
            PackageManager.PERMISSION_GRANTED){
            // Request Location
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
        }
        else{
            // Request Location Permission
            startService();
        }
    }
    else{
        // Start Location Service
        startService();
    }
}

// Start the service with a new intent for the MainActivity and Location Services
// Register Broadcast Receiver with intent action from LocationService.java
void startService(){
    LocationBroadcastReceiver receiver = new LocationBroadcastReceiver();
    IntentFilter filter = new IntentFilter("ACT_LOC");
    Intent intent = new Intent(MainActivity.this, LocationServices.class);
    startService(intent);
    registerReceiver(receiver, filter);
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch(requestCode){
        case 1:
            if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
                startService();
            }
            else{
                Toast.makeText(this, "Give me permissions", Toast.LENGTH_LONG).show();
            }
    }
}

public class LocationBroadcastReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        // check if action is required or not
        if(intent.getAction().equals("ACT_LOC")){
            double lat = intent.getDoubleExtra("Latitude", 0f);
            double lng = intent.getDoubleExtra("Longitude", 0f);
            Toast.makeText(MainActivity.this, "Latitude is: " + lat + ", Longitude is: " + lng, Toast.LENGTH_LONG).show();
        }
    }
}
}

AndroidManifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.anongeolocation">

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <category android:name="android.intent.category.LAUNCHER"/>
                <action android:name="android.intent.action.MAIN"/>
            </intent-filter>
        </activity>
        <service android:name=".LocationService"/>
    </application>

</manifest>

Any help would be greatly appreciated. Thanks in advance.


问:
Python: Removing list element while iterating over list
I'm iterating over a list of elements in Python, do some action on it, and then remove them if they meet certain criteria.

```<code>for element in somelist:
    do_action(element)
    if check(element):
        remove_element_from_list
</code>```

What should I use in place of remove_element?
I have seen similar questions asked, but notice the presence of the do_action part that is to be executed for all elements and thus eliminates the solution of using filters.

答:
Why not rewrite it to be

```<code>for element in somelist:
   do_action(element)

if check(element):
    remove_element_from_list
</code>```

See this question for how to remove from the list, though it looks like you've already seen that
Remove items from a list while iterating

Another option is to do this if you really want to keep this the same

```<code>newlist = []
for element in somelist:
   do_action(element)

   if not check(element):
      newlst.append(element)
</code>```

Body:
I'm iterating over a list of elements in Python, do some action on it, and then remove them if they meet certain criteria.

for element in somelist:
    do_action(element)
    if check(element):
        remove_element_from_list

What should I use in place of remove_element?
I have seen similar questions asked, but notice the presence of the do_action part that is to be executed for all elements and thus eliminates the solution of using filters.

Body:
Why not rewrite it to be

for element in somelist:
   do_action(element)

if check(element):
    remove_element_from_list

See this question for how to remove from the list, though it looks like you've already seen that
Remove items from a list while iterating

Another option is to do this if you really want to keep this the same

newlist = []
for element in somelist:
   do_action(element)

   if not check(element):
      newlst.append(element)


问:
How universal is exif data in mobile phones?
I am making an app that uses exif.js https://github.com/exif-js/exif-js to read some exif data from the image the camera captures. The specific fields that I want is ImageWidth, ImageHeight, FocalLength, FocalLengthIn35mmFilm and Orientation. But I want to use the app on any phone. Does anyone know how universal this is? Does all phones camera put in this data? I tested on a samsung note 4 and it was able to get these data.

Thanks

答:
Most cameras put EXIF in the photos and there's a spec (EXIF 2.2 or TIFF6.0) for defining the default tags. Manufacturers always use the standard tags (ImageWidth, ISO, FocalLength, Orientation, etc...) and only add their own for additional data that doesn't fit any standard tags but. You don't need to worry that they would use proprietary tag instead of one already covered in the EXIF standard. I.e., if you can't find ImageWidth, don't worry about looking for PhotoWidth or anything else. The width info just isn't in the photo in this case.

You can also encounter some data stored in different data structures entirely - such as XMP (XML format, mostly used in panoramas or drone photos), ICC (color profiles), IPTC (descriptions, author info, copyright, etc...)

Also. I'd like to offer alternative library exifr. I've written it because exif-js is pretty much dead now (left unmaintained for over 2 years now) and it's ineffective. Whereas exifr was built to be super efficient, supports all the aforementioned data segments, the new HEIC file format, and more...

You can also try out the library's playground and experiment with images and their output, or check out the repository and docs.


问:
How to solve SassError: Invalid parent selector "*"?
I have an Angular 9 app and when I use this snippet SCSS it returns this error:

```<code>SassError: Invalid parent selector "*"
   ╷
52 │         &#{$value} {
   │         ^^^^^^^^^^^^^^^
   ╵
</code>```

This is the snippet:

```<code>$values: (
  "":"",
  one: one,
  two: two,
);

@mixin gen() {
  @each $value, $key in $values {
    @media (min-width: 300px) {
      &#{$value} {
        @content
      }
    }
  }
}

@mixin display {
  display: block;
}

.display > * {
  @include gen() {
    @include display();
  }
}
</code>```

I want in output classes for each value like: display > *, display-one > *, display-two > *and so on.

答:
1. You want to select * after the value >, means you should add it in the mixin

2. You want select -#{$value} and not just &#{$value}. So A- you have to add the -, and B- for $value="" the - is not exist. so probably you should give it special attention.

Shortly, change the scss to

$values: (
        one: one,
        two: two,
);

@mixin gen() {
  @media (min-width: 300px) {
    > * {
      @content
    }
  }
  @each $value, $key in $values {
    @media (min-width: 300px) {
      &-#{$value} > * {
        @content
      }
    }
  }
}

@mixin display {
  display: block;
}

.display {
  @include gen() {
    @include display();
  }
}```
</div>
</div>
</p>

<p>Output:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>@media (min-width: 300px) {
  .display > * {
    display: block;
  }
}
@media (min-width: 300px) {
  .display-one > * {
    display: block;
  }
}
@media (min-width: 300px) {
  .display-two > * {
    display: block;
  }
}</code>```

Body:
I have an Angular 9 app and when I use this snippet SCSS it returns this error:

SassError: Invalid parent selector "*"
   ╷
52 │         &#{$value} {
   │         ^^^^^^^^^^^^^^^
   ╵

This is the snippet:

$values: (
  "":"",
  one: one,
  two: two,
);

@mixin gen() {
  @each $value, $key in $values {
    @media (min-width: 300px) {
      &#{$value} {
        @content
      }
    }
  }
}

@mixin display {
  display: block;
}

.display > * {
  @include gen() {
    @include display();
  }
}

I want in output classes for each value like: display > *, display-one > *, display-two > *and so on.

Body:
1. You want to select * after the value >, means you should add it in the mixin

2. You want select -#{$value} and not just &#{$value}. So A- you have to add the -, and B- for $value="" the - is not exist. so probably you should give it special attention.

Shortly, change the scss to

$values: (
        one: one,
        two: two,
);

@mixin gen() {
  @media (min-width: 300px) {
    > * {
      @content
    }
  }
  @each $value, $key in $values {
    @media (min-width: 300px) {
      &-#{$value} > * {
        @content
      }
    }
  }
}

@mixin display {
  display: block;
}

.display {
  @include gen() {
    @include display();
  }
}

Output:

@media (min-width: 300px) {
  .display > * {
    display: block;
  }
}
@media (min-width: 300px) {
  .display-one > * {
    display: block;
  }
}
@media (min-width: 300px) {
  .display-two > * {
    display: block;
  }
}


问:
Jenkins neo.sh not found error while using SAP Project Piper Library
I am  setting up a CI/CD pipeline scenario for SCP NEO environment based on the prebuilt pipeline on Project Piper. I tried to execute a pre-built library called Project Piper for Jenkins and I got the following error.The error seems neo.sh is not found. But I downloaded neo SDK and placed it in the neo-sdk folder. Also neo.sh is available inside /opt/sap/neo-sdk/neo-java-web-sdk-3.39.10/tools folder in linux

Please see error in Jenkins

please see .pipeline/config file where that location is referenced

Docker is not used and I set-up Jenkins in ubuntu inside Vmware virtual machine.If the docker is not available,the library is capable of running locally in Jenkins server.
I am keeping neo-sdk tool in a local folder which contain neo.sh which is used to deploy application to SAP Cloud Platform.I am not writing any script my own as everything is prebuilt scripts from Project piper

答:
Issue is solved and thanks both of you for the same. I used envInjecter Plugin in Jenkins. Then go to manage jenkins->Configure->Set environment variables and set path as in

For more detail see the comment from XP84 in this StackOverflow link