问:
How to determine if a point is within a quadrilateral
Goal

I want to determine if a test point is within a defined quadrilateral. I'm probably going to implement the solution in Matlab so I only need pseudo-code.

Inputs

Corners of quadrilateral : (x1,y1) (x2,y2) (x3,y3) (x4,y4)

Test point : (xt, yt)

Output

1 - If within quadrilateral

0 - Otherwise

Update

It was pointed out that identifying the vertices of the quadrilateral is not enough to uniquely identify it. You can assume that the order of the points determines the sides of the quadrilateral (point 1 connects 2, 2 connects to 3, 3 connects to 4, 4 connects to 1)

答: The solution I used to solve this problem was to get the angle of P (in the diagrams the OP posted) for each of the 4 triangles it makes with each side of the quadrilateral. Add the angles together. If they equal (or nearly equal, depending on the error tolerance of the code) 360, the point is inside the quadrilateral. If the sum is less than 360, the point is outside. However, this might only work with convex quadrilaterals. </p>


来源: stackexchange

问:
What is the maximum amount of data i passed through querystring of jquery ajax?
What is the maximum amount of data i passed through querystring of jquery ajax?</p>

答:
Query strings form part of the URL for an HTTP GET request, so the main limit you'll hit is URL length.

Here's a question about that:
What is the maximum length of a URL in different browsers?

So for typical browsers stay inside of 2,000 characters in total. But keep in mind that other clients may not deal with URLs of this length (e.g. proxy / caching servers).

I'd recommend that staying under 500 characters you should be safe. Anything more and consider using a POST request instead.

ContentLicense: CC BY-SA 3.0


问:
Unable to execute NUnit Selenium tests through Jenkins - target machine actively refused connection
I am trying to execute Selenium tests written in C#.NET with NUnit through Jenkins, but the following error message is displayed:

-> error: Unexpected error. System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 127.0.0.1:13748
   at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
   at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)

My build configuration in Jenkins is as follows:

The solution appears to build successfully, but again, upon executing the tests I receive the above error message.

Note: I've checked my firewall settings and Jenkins is allowed through the firewall.

Any feedback would be greatly appreciated.

答: Selenium was instaniated before the test run (BeforeTestRun). This meant any subsequent test executed after the first one would have no reference to the instance of the WebDriver, as it was not re-instantiated at the start of a scenario. </p>

ContentLicense: CC BY-SA 4.0


问:
Initialize twig in constructor of class
I am trying to initialize Twig in the constructor but I run into the issue of:

Fatal error: Uncaught Twig\Error\SyntaxError: Unknown "for" tag. Did you mean "for"?

Here is what my class looks like:

```<code>require_once(__DIR__ . '/vendor/autoload.php');

class Test {

    public $loader;
    public $twig;

    public function __construct() {
        $this->loader = new Twig_Loader_Filesystem(__DIR__ . '/templates');

        $this->twig = new Twig_Environment($this->loader);

        $this->show_page();
     }

     public function show_page() {
         $results = get_results_from_db();

         $template = $this->twig->loadTemplate('results.twig');

         $template->render([
             'results' => $results,
         ]);
     }
}
</code>```

results.twig

```<code>{% for result in results %}
    <p>{{ result.name }}</p>
{% endfor %}
</code>```

Now if I remove the loader and the twig definitions outside of the constructor and put them in the show_page method, it works just fine but that is not how Twig is meant to be used.

答:
According to the twig documentation, you need to echo out the view when you render it. This should work fine:</p>

```<code>require_once('vendor/autoload.php');

class Test
{
    public $loader;
    public $twig;

    public function __construct()
    {
        $this->loader = new Twig_Loader_Filesystem(__DIR__ . '/templates');

        $this->twig = new Twig_Environment($this->loader);

        $this->show_page();
    }

     public function show_page()
     {
         $results = get_results_from_db();

        $template = $this->twig->loadTemplate('results.twig');

        echo $template->render([
            'results' => $results,
        ]);
     }
}
</code>```

Title: Initialize twig in constructor of class

Body:
I am trying to initialize Twig in the constructor but I run into the issue of:

Fatal error: Uncaught Twig\Error\SyntaxError: Unknown "for" tag. Did you mean "for"?

Here is what my class looks like:

require_once(__DIR__ . '/vendor/autoload.php');

class Test {

    public $loader;
    public $twig;

    public function __construct() {
        $this->loader = new Twig_Loader_Filesystem(__DIR__ . '/templates');

        $this->twig = new Twig_Environment($this->loader);

        $this->show_page();
     }

     public function show_page() {
         $results = get_results_from_db();

         $template = $this->twig->loadTemplate('results.twig');

         $template->render([
             'results' => $results,
         ]);
     }
}

results.twig

{% for result in results %}

{{ result.name }}

{% endfor %}

Now if I remove the loader and the twig definitions outside of the constructor and put them in the show_page method, it works just fine but that is not how Twig is meant to be used.

Body:
According to the twig documentation, you need to echo out the view when you render it. This should work fine:

require_once('vendor/autoload.php');

class Test
{
    public $loader;
    public $twig;

    public function __construct()
    {
        $this->loader = new Twig_Loader_Filesystem(__DIR__ . '/templates');

        $this->twig = new Twig_Environment($this->loader);

        $this->show_page();
    }

     public function show_page()
     {
         $results = get_results_from_db();

        $template = $this->twig->loadTemplate('results.twig');

        echo $template->render([
            'results' => $results,
        ]);
     }
}


问:
How to find the highest value of the each row with number of columns and print them?
I have a csv file that has over 1000 rows and 50 columns. Each row has values (i.e. 0.554562) and each column has the same type of values:

As an example of my csv file ():

```<code>       Albany  Ukraine  Germany  Swiss   England

kevin  0.5655  0.5777   0.3232   0.1212  0.9595

brayan 0.4655  0.2777   0.1232,  0.9212  0.5595

alex   0.1655  0.2777   0.3232   0.1212  0.9795

</code>```

Now I want to find the highest values in each row and create new column and added there like:

```<code>        Albany Ukraine Germany Swiss  England highest

kevin   0.5655 0.5777  0.3232  0.1212 0.9595  0.9595

brayan  0.4655 0.2777  0.1232  0.9212 0.5595  0.9212

alex    0.1655 0.2777  0.3232  0.1212 0.9795  0.9795

</code>```

I already checked a few posts here such as 1 2, but none of them helped me.

It would be great if you can provide your help with code that I can run in my side and learn. Thanks

Addition: Also is there any way to say like Kevin with the highest prob of [0.9595] is belong to England?

答:
Work on axis=1 (rows) and assign a new column using max

```<code>df["highest"] = df.max(axis=1)
</code>```

Using idxmax will tell you where the max lies

```<code>top_prob = df.idxmax(axis=1)
</code>```

Body:
I have a csv file that has over 1000 rows and 50 columns. Each row has values (i.e. 0.554562) and each column has the same type of values:

As an example of my csv file ():

       Albany  Ukraine  Germany  Swiss   England

kevin  0.5655  0.5777   0.3232   0.1212  0.9595

brayan 0.4655  0.2777   0.1232,  0.9212  0.5595

alex   0.1655  0.2777   0.3232   0.1212  0.9795

Now I want to find the highest values in each row and create new column and added there like:

        Albany Ukraine Germany Swiss  England highest

kevin   0.5655 0.5777  0.3232  0.1212 0.9595  0.9595

brayan  0.4655 0.2777  0.1232  0.9212 0.5595  0.9212

alex    0.1655 0.2777  0.3232  0.1212 0.9795  0.9795

I already checked a few posts here such as 1 2, but none of them helped me.

It would be great if you can provide your help with code that I can run in my side and learn. Thanks

Addition: Also is there any way to say like Kevin with the highest prob of [0.9595] is belong to England?

Body:
Work on axis=1 (rows) and assign a new column using max

df["highest"] = df.max(axis=1)

Using idxmax will tell you where the max lies

top_prob = df.idxmax(axis=1)


问:
Npm install from repo not running `prepare`
I have an npm package for common components hosted on an internal git server. For some reason when I call npm install in another project I want to consume this in it will not run the prepare hook. Obviously, this does not work since the npm package needs a /dist folder in node_modules to be able to consume the package.

I have already tried things such as using the deprecated prepublish hook and even that does not get called. I also tried to do postinstall to see if I could build after install, while that hook did get called it failed because the devDependencies were not installed

package.json

```<code>{
  "name": "common-components",
  "version": "0.1.0",
  "scripts": {
    "prepare": "npm run build",
    "build": "ng build",
    ...
  },
  "private": true,
  "dependencies": {
    ...
  },
  "devDependencies": {
    ...
  },
}
</code>```

command being used for install

```<code>npm install --save git+ssh://{URL-to-common-components-repo}}
</code>```

I have read through the npm-scripts documentation https://docs.npmjs.com/misc/scripts thoroughly and it seems like they insist that prepare hook should always be called for this exact use-case

Updated 5/6/2019

Just as a note I found this bug on NPM community https://npm.community/t/using-npm-ci-does-not-run-prepare-script-for-git-modules/632/4.

I am using npm 6.4.1 which should work according to the bug

答: For those that are wondering the status of this. I was unable to ever get it to work. What I ended up doing was hosting the components on a private npm registry and that works fine since the npm publish command will do the build and only publish the dist folder

Body:
I have an npm package for common components hosted on an internal git server. For some reason when I call npm install in another project I want to consume this in it will not run the prepare hook. Obviously, this does not work since the npm package needs a /dist folder in node_modules to be able to consume the package.

I have already tried things such as using the deprecated prepublish hook and even that does not get called. I also tried to do postinstall to see if I could build after install, while that hook did get called it failed because the devDependencies were not installed

package.json

{
  "name": "common-components",
  "version": "0.1.0",
  "scripts": {
    "prepare": "npm run build",
    "build": "ng build",
    ...
  },
  "private": true,
  "dependencies": {
    ...
  },
  "devDependencies": {
    ...
  },
}

command being used for install

npm install --save git+ssh://{URL-to-common-components-repo}}

I have read through the npm-scripts documentation https://docs.npmjs.com/misc/scripts thoroughly and it seems like they insist that prepare hook should always be called for this exact use-case

Updated 5/6/2019

Just as a note I found this bug on NPM community https://npm.community/t/using-npm-ci-does-not-run-prepare-script-for-git-modules/632/4.

I am using npm 6.4.1 which should work according to the bug


问:
In Springboot, how to serialize properties into objects when using @ConfigurationProperties and @PropertySource?
When using @ConfigurationProperties with @PropertySource(value = "myconfig.yml") Springboot doesn't serialize my properties into an object

If I put this same config in application.yml and remove the @PropertySource(value = "myconfig.yml"), then it works

```<code>---
testPrefix.simpleProperty: my.property.haha
testPrefix.complexProperties:
  -
    firstName: 'Clark'
    lastName: 'Ken'
  -
    firstName: 'Roger'
    lastName: 'Federer'
</code>```

```<code>@Configuration
@ConfigurationProperties(prefix = "testPrefix")
@PropertySource(value = "testConfigFile.yml")
public class MyTestProperties {
  private String simpleProperty;
  private List<Person> complexProperties;

getters

setters
</code>```

```<code>@SpringBootApplication
public class App implements CommandLineRunner {

  MyTestProperties myProperties;

  @Autowired
  public App(MyTestProperties properties) {
    this.properties = properties;
  }

  public static void main(String[] args) {
    SpringApplication app = new SpringApplication((App.class));
    app.run(args);
  }

  @Override
  public void run(String... args) throws Exception {
    System.out.println(myProperties.getSimpleProperty());
    myProperties.getComplexProperties.stream.forEach(System.out::println));
  }
}
</code>```

Output:

```<code>my.property.haha
</code>```

答:
You need to use jackson yaml dependency.

//pom.xml
<dependency>
  <groupId>com.fasterxml.jackson.dataformat</groupId>
  <artifactId>jackson-dataformat-yaml</artifactId>
</dependency>
```

<p>Then create a factory class for loading yaml files as property sources.  </p>

<pre class="lang-java prettyprint-override"><code>//YamlPropertySourceFactory.java

import java.io.IOException;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;

public class YamlPropertySourceFactory implements PropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(String s,
            EncodedResource encodedResource) throws IOException {
        YamlPropertiesFactoryBean bean = new YamlPropertiesFactoryBean();
        bean.setResources(encodedResource.getResource());
        return new PropertiesPropertySource(
                s != null ? s : encodedResource.getResource().getFilename(),
                bean.getObject());
    }

}

</code>```

Then use PropertySource annotation like this.

@PropertySource(factory = YamlPropertySourceFactory.class, value = "testConfigFile.yml")
public class MyTestProperties {
  private String simpleProperty;
  private List<Person> complexProperties;
```

Body:
When using @ConfigurationProperties with @PropertySource(value = "myconfig.yml") Springboot doesn't serialize my properties into an object

If I put this same config in application.yml and remove the @PropertySource(value = "myconfig.yml"), then it works

---
testPrefix.simpleProperty: my.property.haha
testPrefix.complexProperties:
  -
    firstName: 'Clark'
    lastName: 'Ken'
  -
    firstName: 'Roger'
    lastName: 'Federer'

@Configuration
@ConfigurationProperties(prefix = "testPrefix")
@PropertySource(value = "testConfigFile.yml")
public class MyTestProperties {
  private String simpleProperty;
  private List<Person> complexProperties;

getters

setters

@SpringBootApplication
public class App implements CommandLineRunner {

  MyTestProperties myProperties;

  @Autowired
  public App(MyTestProperties properties) {
    this.properties = properties;
  }

  public static void main(String[] args) {
    SpringApplication app = new SpringApplication((App.class));
    app.run(args);
  }

  @Override
  public void run(String... args) throws Exception {
    System.out.println(myProperties.getSimpleProperty());
    myProperties.getComplexProperties.stream.forEach(System.out::println));
  }
}

Output:

my.property.haha

Body:
You need to use jackson yaml dependency.

//pom.xml
<dependency>
  <groupId>com.fasterxml.jackson.dataformat</groupId>
  <artifactId>jackson-dataformat-yaml</artifactId>
</dependency>

Then create a factory class for loading yaml files as property sources.

//YamlPropertySourceFactory.java

import java.io.IOException;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;

public class YamlPropertySourceFactory implements PropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(String s,
            EncodedResource encodedResource) throws IOException {
        YamlPropertiesFactoryBean bean = new YamlPropertiesFactoryBean();
        bean.setResources(encodedResource.getResource());
        return new PropertiesPropertySource(
                s != null ? s : encodedResource.getResource().getFilename(),
                bean.getObject());
    }

}

Then use PropertySource annotation like this.

@PropertySource(factory = YamlPropertySourceFactory.class, value = "testConfigFile.yml")
public class MyTestProperties {
  private String simpleProperty;
  private List<Person> complexProperties;


问:
How to send parallel GET requests and wait for result responses?
I'm using apache http client within spring mvc 3.2.2 to send 5 get requests synchronously as illustrated.

How can I send all of these asynchronously (in parallel) and wait for the requests to return in order to return a parsed payload string from all GET requests?

```<code>public String myMVCControllerGETdataMethod()
{
   // Send 1st request
   HttpClient httpclient = new DefaultHttpClient();
   HttpGet httpget = new HttpGet("http://api/data?type=1");
   ResponseHandler<String> responseHandler = new BasicResponseHandler();
   String responseBody = httpclient.execute(httpget, responseHandler);

   // Send 2st request
   HttpClient httpclient2 = new DefaultHttpClient();
   HttpGet httpget2 = new HttpGet("http://api/data?type=2");
   ResponseHandler2<String> responseHandler2 = new BasicResponseHandler();
   String responseBody2 = httpclient.execute(httpget, responseHandler2);

   // o o o more gets here

   // Perform some work here...and wait for all requests to return
   // Parse info out of multiple requests and return
   String results = doWorkwithMultipleDataReturned();

   model.addAttribute(results, results);
   return "index";

}
</code>```

答:
Move your request code to separate method:

```<code>private String executeGet(String url){
   HttpClient httpclient = new DefaultHttpClient();
   HttpGet httpget = new HttpGet(url);
   ResponseHandler<String> responseHandler = new BasicResponseHandler();
   return httpclient.execute(httpget, responseHandler);
}
</code>```

And submit them to ExecutorService:

```<code>ExecutorService executorService = Executors.newCachedThreadPool();

Future<String> firstCallFuture = executorService.submit(() -> executeGet(url1));
Future<String> secondCallFuture = executorService.submit(() -> executeGet(url2));

String firstResponse = firstCallFuture.get();
String secondResponse = secondCallFuture.get();

executorService.shutdown();
</code>```

Or

```<code>Future<String> firstCallFuture = CompletableFuture.supplyAsync(() -> executeGet(url1));
Future<String> secondCallFuture = CompletableFuture.supplyAsync(() -> executeGet(url2));

String firstResponse = firstCallFuture.get();
String secondResponse = secondCallFuture.get();
</code>```

Or use RestTemplate as described in How to use Spring WebClient to make multiple calls simultaneously?

Body:
I'm using apache http client within spring mvc 3.2.2 to send 5 get requests synchronously as illustrated.

How can I send all of these asynchronously (in parallel) and wait for the requests to return in order to return a parsed payload string from all GET requests?

public String myMVCControllerGETdataMethod()
{
   // Send 1st request
   HttpClient httpclient = new DefaultHttpClient();
   HttpGet httpget = new HttpGet("http://api/data?type=1");
   ResponseHandler<String> responseHandler = new BasicResponseHandler();
   String responseBody = httpclient.execute(httpget, responseHandler);

   // Send 2st request
   HttpClient httpclient2 = new DefaultHttpClient();
   HttpGet httpget2 = new HttpGet("http://api/data?type=2");
   ResponseHandler2<String> responseHandler2 = new BasicResponseHandler();
   String responseBody2 = httpclient.execute(httpget, responseHandler2);

   // o o o more gets here

   // Perform some work here...and wait for all requests to return
   // Parse info out of multiple requests and return
   String results = doWorkwithMultipleDataReturned();

   model.addAttribute(results, results);
   return "index";

}

Body:
Move your request code to separate method:

private String executeGet(String url){
   HttpClient httpclient = new DefaultHttpClient();
   HttpGet httpget = new HttpGet(url);
   ResponseHandler<String> responseHandler = new BasicResponseHandler();
   return httpclient.execute(httpget, responseHandler);
}

And submit them to ExecutorService:

ExecutorService executorService = Executors.newCachedThreadPool();

Future<String> firstCallFuture = executorService.submit(() -> executeGet(url1));
Future<String> secondCallFuture = executorService.submit(() -> executeGet(url2));

String firstResponse = firstCallFuture.get();
String secondResponse = secondCallFuture.get();

executorService.shutdown();

Or

Future<String> firstCallFuture = CompletableFuture.supplyAsync(() -> executeGet(url1));
Future<String> secondCallFuture = CompletableFuture.supplyAsync(() -> executeGet(url2));

String firstResponse = firstCallFuture.get();
String secondResponse = secondCallFuture.get();

Or use RestTemplate as described in How to use Spring WebClient to make multiple calls simultaneously?


问:
DAX ISBLANK() Showing "False" for empty cells in Power Pivot
I'm looking to generate a calculated column based off of some other columns in a PowerPivot table.

The cells are blank - as in no discernible value - but when I reference them as BLANK(), my formula doesn't work.

ISBLANK() shows False when I reference those cells - but there is no data in the cells (that I can tell).

How can I A) get DAX to realize these really are BLANK(), or B) Figure out what in the world is in those cells to make them not be seen as blank.

The code is dead simple, just =ISBLANK([claim schdlng prvdr]) with the [claim schdlng prvdr] being empty/blank.

Not sure what the problem is. But the cell definitely has nothing in it.

答: My guess is that those cells contain the empty string "" which is sometimes treated differently than BLANK(). To test, try = ( [claim schdlng prvdr] = "" )


问:
What is the most EVIL code you have ever seen in a production enterprise environment?
What is the most evil or dangerous code fragment you have ever seen in a production environment at a company?  I've never encountered production code that I would consider to be deliberately malicious and evil, so I'm quite curious to see what others have found.

The most dangerous code I have ever seen was a stored procedure two linked-servers away from our core production database server.  The stored procedure accepted any NVARCHAR(8000) parameter and executed the parameter on the target production server via an double-jump sp_executeSQL command.  That is to say, the sp_executeSQL command executed another sp_executeSQL command in order to jump two linked servers.  Oh, and the linked server account had sysadmin rights on the target production server.

答:
I don't know if this is "evil" so much as misguided (I recently posted it on The Old New Thing):

I knew one guy who loved to store information as delimited strings. He was familiar with the concept of arrays, as shown when he used arrays of delimited strings, but the light bulb never lit up.

OwnerDisplayName: InnerJoin

LastEditorDisplayName: Noah

OwnerDisplayName: greg

ContentLicense: CC BY-SA 2.5


问:
C++ how to sort vector<class *> with operator <
i have

```<code> class c1{

public:
    int number;

    c1()
    {
        number=rand()%10;
    }

    bool operator < (c1 *w)
    {
        return number < w->number;
    }

};

vector<c1*> vec = { ... }
sort(vec.begin(),vec.end())
</code>```

why it dosent sort ?

but if we had

```<code> bool operator < (c1 w)
    {
        return number < w.number;
    }
</code>```

and

```<code>vector<c1> vec = { ... }
</code>```

it would have been sorted !

答:
And in your example, vector<c1*> is sorted.  Just not to the
criteria you seem to want: by default, sort uses
std::less<T> as the ordering criteria, and std::less<ci*>
compares the pointers (which is what you'd expect).  If you
don't want the default criteria, then you have to pass a third
argument to sort, a predicate defining the ordering you want.

And of course, your member operator<(c1*) will only be called
when you compare a c1 with a ci* (and only if the c1 is an
rvalue).  Such operators are very, very rare---normally, both
sides of a < operator should take the same type (and should be
const, since a < operator which modifies the values of the
objects it compares would be surprising, to say the least).

Body:
i have

 class c1{

public:
    int number;

    c1()
    {
        number=rand()%10;
    }

    bool operator < (c1 *w)
    {
        return number < w->number;
    }

};

vector<c1*> vec = { ... }
sort(vec.begin(),vec.end())

why it dosent sort ?

but if we had

 bool operator < (c1 w)
    {
        return number < w.number;
    }

and

vector<c1> vec = { ... }

it would have been sorted !


问:
How to add passive values to radio buttons
I want while the turtle radio button is selected for there to be a passive increase in strength like this:

Also on level up, I want it to add +1 to that value so when the turtle is level 2 the passive is +2 strength.

I'm mostly wondering how you do passive effects in HTML. Do radio buttons have the ability to passively modify variables when selected? My idea is similar to changing gear in an RPG. I would also like Cexp to go up 1 every second when the radio button is selected.

Here is my current code:

```<code>var Turtle = 1;
var Turtlelv = 1;
var TurtleCexp = 0;
var TurtleMexp = 100;
var NextMaxTurtleExp = TurtleMexp;
var Turtlestrength = 1 + Strength

function turtlepassive() {
    if (TurtleCexp < NextMaxTurtleExp) {
        TurtleCexp = TurtleCexp + 1;
        document.getElementById("TurtleCexp").innerHTML = TurtleCexp;
    } else {
        Turtlelv = Turtlelv + 1;
        TurtleCexp = 0;
        Turtle = Turtle + 1;
        Turtlestrength = Turtlestrength + 1;
        NextMaxTurtleExp = NextMaxTurtleExp * 1.5;
        document.getElementById("Strength").innerHTML = Strength;
        document.getElementById('TurtleMexp').innerHTML =
NextMaxTurtleExp;
        document.getElementById('Turtlelv').innerHTML = Turtlelv;
        document.getElementById('TurtleCexp').innerHTML = TurtleCexp;
        document.getElementById('Turtle').innerHTML = Turtle;
     }
}
</code>```

Html code:

```<code><div id="turtle" class="control">
    <label class="radio">
        <input type="radio" name="Pets">
    </label>
    <img src="turtle.png" alt="turtle" height="100" width="100">Lv <span id="Magiclv">1</span> <span id="MagicCexp">0</span> / <span id="MagicMexp">100</span>
</div>
</code>```

I expect while the turtle radio button is selected for exp to go up by 1 every second and to have a passive buff to strength by 1 at level 1 and 2 at level 2 and so on. But the actual result I can't get this to work properly.

答:
Radio buttons can't passively change a variable, but this can be done programmatically.

This is basic code (that you should remake for your program) demonstrating how you could have strength affected by whether or not the turtle is selected and the turtle's level. When the turtle is selected, it adds the amount to the variable, and when the turtle is deselected it removes the amount.

    <input type="radio" name="Pets" id="turtle-radio">
```

```document.getElementById("turtle-radio").addEventListener("change", () => {
  if (document.getElementById("turtle-radio").checked) {
    //increase strength by level
  } else {
    //decrease strength by level
  }
}
```

<p>As for updating the turtle's level over time, this can also be done. Let's assume that the turtle always needs 100xp to level up. Every second that the radio is checked, it will add 1xp to the turtle and set a <code>timeout</code> for another check. When the xp reaches 100, have the turtle level up. When the radio button isn't check, the <code>timeout</code> shouldn't refresh.</p>

```function turtleXpUp() {
  if (document.getElementById("turtle-radio").checked) {
    setTimeout(turtleXpUp, 1000)
    //turtle xp +1
  }
  if (/* xp == 100*/) {
    if (document.getElementById("turtle-radio").checked) {
      //increase strength by 1
      //increase level by 1
    }
  }
}
document.getElementById("turtle-radio").addEventListener("change", turtleXpUp)
```

Body:
I want while the turtle radio button is selected for there to be a passive increase in strength like this:

Also on level up, I want it to add +1 to that value so when the turtle is level 2 the passive is +2 strength.

I'm mostly wondering how you do passive effects in HTML. Do radio buttons have the ability to passively modify variables when selected? My idea is similar to changing gear in an RPG. I would also like Cexp to go up 1 every second when the radio button is selected.

Here is my current code:

var Turtle = 1;
var Turtlelv = 1;
var TurtleCexp = 0;
var TurtleMexp = 100;
var NextMaxTurtleExp = TurtleMexp;
var Turtlestrength = 1 + Strength

function turtlepassive() {
    if (TurtleCexp < NextMaxTurtleExp) {
        TurtleCexp = TurtleCexp + 1;
        document.getElementById("TurtleCexp").innerHTML = TurtleCexp;
    } else {
        Turtlelv = Turtlelv + 1;
        TurtleCexp = 0;
        Turtle = Turtle + 1;
        Turtlestrength = Turtlestrength + 1;
        NextMaxTurtleExp = NextMaxTurtleExp * 1.5;
        document.getElementById("Strength").innerHTML = Strength;
        document.getElementById('TurtleMexp').innerHTML =
NextMaxTurtleExp;
        document.getElementById('Turtlelv').innerHTML = Turtlelv;
        document.getElementById('TurtleCexp').innerHTML = TurtleCexp;
        document.getElementById('Turtle').innerHTML = Turtle;
     }
}

Html code:

        <input type="radio" name="Pets">

    Lv 1 0 / 100

I expect while the turtle radio button is selected for exp to go up by 1 every second and to have a passive buff to strength by 1 at level 1 and 2 at level 2 and so on. But the actual result I can't get this to work properly.

Body:
Radio buttons can't passively change a variable, but this can be done programmatically.

This is basic code (that you should remake for your program) demonstrating how you could have strength affected by whether or not the turtle is selected and the turtle's level. When the turtle is selected, it adds the amount to the variable, and when the turtle is deselected it removes the amount.

<div id="turtle" class="control">
  <label class="radio">
    <input type="radio" name="Pets" id="turtle-radio">

document.getElementById("turtle-radio").addEventListener("change", () => {
  if (document.getElementById("turtle-radio").checked) {
    //increase strength by level
  } else {
    //decrease strength by level
  }
}

As for updating the turtle's level over time, this can also be done. Let's assume that the turtle always needs 100xp to level up. Every second that the radio is checked, it will add 1xp to the turtle and set a timeout for another check. When the xp reaches 100, have the turtle level up. When the radio button isn't check, the timeout shouldn't refresh.

function turtleXpUp() {
  if (document.getElementById("turtle-radio").checked) {
    setTimeout(turtleXpUp, 1000)
    //turtle xp +1
  }
  if (/* xp == 100*/) {
    if (document.getElementById("turtle-radio").checked) {
      //increase strength by 1
      //increase level by 1
    }
  }
}
document.getElementById("turtle-radio").addEventListener("change", turtleXpUp)


问:
How to plot data per hour, grouped by days?
Background: from a large DataFrame I filtered out entries for year=2013, month=June, week of the 3rd - 9th (Monday to Sunday). Then, I grouped the data by day, hour, and user_type, and pivoted the table to get a DataFrame which looks like:

```<code>   Day  Hour  Casual  Registered  Casual_percentage
0  3    0     14      19          42.42
1  3    1     8       8           50.00
2  3    2     1       3           25.00
3  3    3     2       1           66.67
4  3    4     1       3           25.00
5  3    5     1       17          5.56
.  .    .     .       .           .
</code>```

For each day I have 24 hours so for day 4 (Tuesday), the data starts like:

```<code>.  .    .     .       .           .
21 3    21    32      88          26.67
22 3    22    26      64          28.89
23 3    23    23      30          43.40
24 4    0     10      11          47.62
25 4    1     1       5           16.67
26 4    2     1       1           50.00
.  .    .     .       .           .
</code>```

How can I plot Casual and Registered variables per Hour, for each of the 7 Days? Would I need to create 7 different plots and align them in 1 figure?

Current code. I feel I'm way off. I also tried to create a second x-axis (for Days) using the documentation.

def make_patch_spines_invisible(ax):
    ax.set_frame_on(True)
    ax.patch.set_visible(False)
    for sp in ax.spines.values():
        sp.set_visible(False)

fig, ax1 = plt.subplots(figsize=(10, 5))
ax1.set(xlabel='Hours', ylabel='Total # of trips started')

ax1.plot(data.Hour, data.Casual, color='g')
ax1.plot(data.Hour, data.Registered, color='b')

"""This part is trying to create the 2nd x-axis (Days)"""
ax2 = ax1.twinx()
#offset the bottom spine
ax2.spines['bottom'].set_position(('axes', -.5))
make_patch_spines_invisible(ax2)
#show bottomm spine
ax2.spines['bottom'].set_visible(True)
ax2.set_xlabel("Days")

plt.show()
```

Output:

End goal

答:
Assuming your data is ordered by index (e.g., 0 - 24 is day 3, 25 - 48 is day 4, etc.) you can plot the index values rather than hours in your code:

```<code>ax1.plot(data.index.values, df.Casual, color='g')
ax1.plot(data.index.values, df.Registered, color='b')
</code>```

This will yield a graph similar to what you're looking for as an end product (note I used fake data):

Body:
Background: from a large DataFrame I filtered out entries for year=2013, month=June, week of the 3rd - 9th (Monday to Sunday). Then, I grouped the data by day, hour, and user_type, and pivoted the table to get a DataFrame which looks like:

   Day  Hour  Casual  Registered  Casual_percentage
0  3    0     14      19          42.42
1  3    1     8       8           50.00
2  3    2     1       3           25.00
3  3    3     2       1           66.67
4  3    4     1       3           25.00
5  3    5     1       17          5.56
.  .    .     .       .           .

For each day I have 24 hours so for day 4 (Tuesday), the data starts like:

.  .    .     .       .           .
21 3    21    32      88          26.67
22 3    22    26      64          28.89
23 3    23    23      30          43.40
24 4    0     10      11          47.62
25 4    1     1       5           16.67
26 4    2     1       1           50.00
.  .    .     .       .           .

How can I plot Casual and Registered variables per Hour, for each of the 7 Days? Would I need to create 7 different plots and align them in 1 figure?

Current code. I feel I'm way off. I also tried to create a second x-axis (for Days) using the documentation.

def make_patch_spines_invisible(ax):
    ax.set_frame_on(True)
    ax.patch.set_visible(False)
    for sp in ax.spines.values():
        sp.set_visible(False)

fig, ax1 = plt.subplots(figsize=(10, 5))
ax1.set(xlabel='Hours', ylabel='Total # of trips started')

ax1.plot(data.Hour, data.Casual, color='g')
ax1.plot(data.Hour, data.Registered, color='b')

"""This part is trying to create the 2nd x-axis (Days)"""
ax2 = ax1.twinx()
#offset the bottom spine
ax2.spines['bottom'].set_position(('axes', -.5))
make_patch_spines_invisible(ax2)
#show bottomm spine
ax2.spines['bottom'].set_visible(True)
ax2.set_xlabel("Days")

plt.show()

Output:

End goal

Body:
Assuming your data is ordered by index (e.g., 0 - 24 is day 3, 25 - 48 is day 4, etc.) you can plot the index values rather than hours in your code:

ax1.plot(data.index.values, df.Casual, color='g')
ax1.plot(data.index.values, df.Registered, color='b')

This will yield a graph similar to what you're looking for as an end product (note I used fake data):


问:
Authenticate User In Django via Flutter App and JSON Web Token
How do I Authenticate User in Django-Rest-Framework via my Flutter App?
I did this in Postman before and this is how I did it:

Post Request to (IP:8000/get-token/) > Returns JSON Web Token

Get Request with Bearer Token to (IP:8000/database/exercises/) > Returns JSON file! - Note that if I don't use the token I will get nothing in return!

How do I replicate this via a Flutter http.post Request?

This is how I will do the signup process (In this case not with the token):

```<code>//text-field controllers
TextEditingController usernameController = TextEditingController();
TextEditingController passwordController = TextEditingController();

//post request
postRequest() async {
String _url = "IP:8000/get-token/";
var response = await http.post(
  Uri.encodeFull(_url),
  headers: { "Accept" : "application/json"},
  body: {
    "username": "${usernameController.text}",
    "password": "${passwordController.text}",
  },
  encoding: Encoding.getByName("utf-8"),
);

//Name TextField (Simplified Code)
Container(
  margin: EdgeInsets.only(bottom: 2, top: 25),
    child: TextField(
    controller: nameController,
      decoration: InputDecoration(
      hintText: "Name..."
      ))
)

//Password TextField (Simplified Code)
Container(
  margin: EdgeInsets.only(bottom: 2, top: 25),
    child: TextField(
    controller: passwordController,
      decoration: InputDecoration(
      hintText: "Password..."
      ))
)

//Simplified but you get what I mean
Inkwell(
  child: Container()
  onTap()
  {
    postRequest(),
    Navigator.push(Into-App)
  }
)
</code>```

My question is: How do I take the response from this request? (if username and password match the database).

And how do I use the token I get in response to do future request to get data inside the app?

The Django-Backend:

```<code>#urls
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('database/', include('PlanThatWorkout.urls')),
    path('get-token/', TokenObtainPairView.as_view()),
    path('refresh-token/', TokenRefreshView.as_view())
]

#settings
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES' : ('rest_framework.permissions.IsAuthenticated',),
'DEFAULT_AUTHENTICATION_CLASSES' : ('rest_framework_simplejwt.authentication.JWTAuthentication',),
}
</code>```

答:
You can get the token by decoding your response with dart:convert.

```<code>import 'dart:convert';
Map<String, dynamic> data = jsonDecode(reponse);
final jwt = data['jwt-key'];
</code>```

To persist your data, you can save this on disk writing in file with path_provider:

```<code>import 'dart:async';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart';

Future<File> write(String jwt) async {
    final directory = await getApplicationDocumentsDirectory();
    final path = directory.path;
    final file = File('$path/jwt.txt');
    return file.writeAsString('$jwt');
}

Future<String> read() async {
    try { in a file or using
      final directory = await getApplicationDocumentsDirectory();
      final path = directory.path;
      final file = File('$path/jwt.txt');
      String contents = await file.readAsString();
      return contents;
    } catch (e) {
      return '';
    }
  }
</code>```

or using shared_preferences.

Body:
How do I Authenticate User in Django-Rest-Framework via my Flutter App?
I did this in Postman before and this is how I did it:

Post Request to (IP:8000/get-token/) > Returns JSON Web Token

Get Request with Bearer Token to (IP:8000/database/exercises/) > Returns JSON file! - Note that if I don't use the token I will get nothing in return!

How do I replicate this via a Flutter http.post Request?

This is how I will do the signup process (In this case not with the token):

//text-field controllers
TextEditingController usernameController = TextEditingController();
TextEditingController passwordController = TextEditingController();

//post request
postRequest() async {
String _url = "IP:8000/get-token/";
var response = await http.post(
  Uri.encodeFull(_url),
  headers: { "Accept" : "application/json"},
  body: {
    "username": "${usernameController.text}",
    "password": "${passwordController.text}",
  },
  encoding: Encoding.getByName("utf-8"),
);

//Name TextField (Simplified Code)
Container(
  margin: EdgeInsets.only(bottom: 2, top: 25),
    child: TextField(
    controller: nameController,
      decoration: InputDecoration(
      hintText: "Name..."
      ))
)

//Password TextField (Simplified Code)
Container(
  margin: EdgeInsets.only(bottom: 2, top: 25),
    child: TextField(
    controller: passwordController,
      decoration: InputDecoration(
      hintText: "Password..."
      ))
)

//Simplified but you get what I mean
Inkwell(
  child: Container()
  onTap()
  {
    postRequest(),
    Navigator.push(Into-App)
  }
)

My question is: How do I take the response from this request? (if username and password match the database).

And how do I use the token I get in response to do future request to get data inside the app?

The Django-Backend:

#urls
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('database/', include('PlanThatWorkout.urls')),
    path('get-token/', TokenObtainPairView.as_view()),
    path('refresh-token/', TokenRefreshView.as_view())
]

#settings
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES' : ('rest_framework.permissions.IsAuthenticated',),
'DEFAULT_AUTHENTICATION_CLASSES' : ('rest_framework_simplejwt.authentication.JWTAuthentication',),
}

Body:
You can get the token by decoding your response with dart:convert.

import 'dart:convert';
Map<String, dynamic> data = jsonDecode(reponse);
final jwt = data['jwt-key'];

To persist your data, you can save this on disk writing in file with path_provider:

import 'dart:async';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart';

Future<File> write(String jwt) async {
    final directory = await getApplicationDocumentsDirectory();
    final path = directory.path;
    final file = File('$path/jwt.txt');
    return file.writeAsString('$jwt');
}

Future<String> read() async {
    try { in a file or using
      final directory = await getApplicationDocumentsDirectory();
      final path = directory.path;
      final file = File('$path/jwt.txt');
      String contents = await file.readAsString();
      return contents;
    } catch (e) {
      return '';
    }
  }

or using shared_preferences.


问:
java.sql.SQLException: no such column: after accepting sql query
I am developing a system that manages stock for a project and am trying to get a list of stock items that are close to their expiration date

This is what the table is created as:

```<code>Query_Statement.executeUpdate("CREATE TABLE STOCK_PURCHASE ( SP_ID INTEGER PRIMARY KEY AUTOINCREMENT,"
                    + "USER_ID INTEGER,STOCK_ID INTEGER,SUPPLIER_ID INTEGER,SP_ENTRY_DATE TEXT,"
                    + "SP_PURCHASE_PRICE REAL, SP_SELLBY_DATE TEXT, SP_QUANTITY REAL,"
                    + "FOREIGN KEY (USER_ID) REFERENCES USER (USER_ID),"
                    + "FOREIGN KEY (STOCK_ID) REFERENCES STOCK (STOCK_ID),"
                    + "FOREIGN KEY (SUPPLIER_ID) REFERENCES SUPPLIER (SUPPLIER_ID))");
</code>```

This is the function to get that I use:

```<code>public ArrayList<String> GetExpiredStock(){
    Connection dbConnection = null;
    ResultSet list = null;
    ArrayList<String> ls = new ArrayList<String>();

    LocalDate currentDate = LocalDate.now();
    //System.out.println(today);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");

    try {
        dbConnection = DriverManager.getConnection("jdbc:sqlite:"+dbName+".db");

        Statement Query_Statement = dbConnection.createStatement();
        Query_Statement.setQueryTimeout(10);

        list = Query_Statement.executeQuery("SELECT SP_ENTRY_DATE, STOCK_ID FROM STOCK_PURCHASE"); //this works

        while (list.next()) {
            try {
            LocalDate expDate = LocalDate.parse(list.getString("SP_SELLBY_DATE"), formatter);
            LocalDate monthAway = expDate.minusMonths(1);
            System.out.println(currentDate);
            if(currentDate.isAfter(monthAway)) {
                int id = list.getInt("STOCK_ID");
                ResultSet ids = Query_Statement.executeQuery("SELECT STOCK_NAME FROM STOCK WHERE STOCK_ID=" + id);

                ls.add(ids.getString("STOCK_NAME") + "\t\t" +
                        list.getString("SP_SELLBY_DATE") + getStockQuant(list.getInt("STOCK_ID"),
                                currentDate));

            }
            }catch(SQLException e) {
                System.err.println(e);
                continue;

            }
        }

    } catch (SQLException e) {
        System.err.println(e.getMessage());
    } finally {
        try {
            if (dbConnection != null)
                dbConnection.close();
        } catch (SQLException e) {
            System.err.println(e);
        }
    }

    return ls;
}
</code>```

I expect it to get the expiration date. However it keeps saying:

```<code>java.sql.SQLException: no such column: 'SP_SELLBY_DATE'
</code>```

Edit:

I changed the code to look like this:

```<code>    public ArrayList<String> GetExpiredStock(){
    Connection dbConnection = null;
    ResultSet list = null;
    ArrayList<String> ls = new ArrayList<String>();

    LocalDate currentDate = LocalDate.now();
    //System.out.println(today);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");

    try {
        dbConnection = DriverManager.getConnection("jdbc:sqlite:"+dbName+".db");

        Statement Query_Statement = dbConnection.createStatement();
        Query_Statement.setQueryTimeout(10);

        list = Query_Statement.executeQuery("SELECT SP_SELLBY_DATE, STOCK_ID FROM STOCK_PURCHASE"); //this works

        while (list.next()) {
            try {
            String da = list.getString("SP_SELLBY_DATE");
            int id = list.getInt("STOCK_ID");
            System.out.println("Executed on id = " + id);
            LocalDate expDate = LocalDate.parse(da, formatter);
            LocalDate monthAway = expDate.minusMonths(1);
            System.out.println(currentDate);
            if(currentDate.isAfter(monthAway)) {

                ResultSet ids = Query_Statement.executeQuery("SELECT STOCK_NAME FROM STOCK WHERE STOCK_ID=" + id);

                ls.add(ids.getString("STOCK_NAME") + "\t\t" +
                        da + "\t\t"+  getStockQuant(id,
                                currentDate));

            }
            }catch(SQLException e) {
                System.err.println(e);
                continue;

            }
        }

    } catch (SQLException e) {
        System.err.println(e.getMessage());
    } finally {
        try {
            if (dbConnection != null)
                dbConnection.close();
        } catch (SQLException e) {
            System.err.println(e);
        }
    }

    return ls;
</code>```

But it still fails after the first iteration

答: I believe you query it list.getString("SP_SELLBY_DATE") twice in your loop, that should be root cause. Instead, you should use a variable when you get it to avoid to call it again as cursor has changed.

Body:
I am developing a system that manages stock for a project and am trying to get a list of stock items that are close to their expiration date

This is what the table is created as:

Query_Statement.executeUpdate("CREATE TABLE STOCK_PURCHASE ( SP_ID INTEGER PRIMARY KEY AUTOINCREMENT,"
                    + "USER_ID INTEGER,STOCK_ID INTEGER,SUPPLIER_ID INTEGER,SP_ENTRY_DATE TEXT,"
                    + "SP_PURCHASE_PRICE REAL, SP_SELLBY_DATE TEXT, SP_QUANTITY REAL,"
                    + "FOREIGN KEY (USER_ID) REFERENCES USER (USER_ID),"
                    + "FOREIGN KEY (STOCK_ID) REFERENCES STOCK (STOCK_ID),"
                    + "FOREIGN KEY (SUPPLIER_ID) REFERENCES SUPPLIER (SUPPLIER_ID))");

This is the function to get that I use:

public ArrayList<String> GetExpiredStock(){
    Connection dbConnection = null;
    ResultSet list = null;
    ArrayList<String> ls = new ArrayList<String>();

    LocalDate currentDate = LocalDate.now();
    //System.out.println(today);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");

    try {
        dbConnection = DriverManager.getConnection("jdbc:sqlite:"+dbName+".db");

        Statement Query_Statement = dbConnection.createStatement();
        Query_Statement.setQueryTimeout(10);

        list = Query_Statement.executeQuery("SELECT SP_ENTRY_DATE, STOCK_ID FROM STOCK_PURCHASE"); //this works

        while (list.next()) {
            try {
            LocalDate expDate = LocalDate.parse(list.getString("SP_SELLBY_DATE"), formatter);
            LocalDate monthAway = expDate.minusMonths(1);
            System.out.println(currentDate);
            if(currentDate.isAfter(monthAway)) {
                int id = list.getInt("STOCK_ID");
                ResultSet ids = Query_Statement.executeQuery("SELECT STOCK_NAME FROM STOCK WHERE STOCK_ID=" + id);

                ls.add(ids.getString("STOCK_NAME") + "\t\t" +
                        list.getString("SP_SELLBY_DATE") + getStockQuant(list.getInt("STOCK_ID"),
                                currentDate));

            }
            }catch(SQLException e) {
                System.err.println(e);
                continue;

            }
        }

    } catch (SQLException e) {
        System.err.println(e.getMessage());
    } finally {
        try {
            if (dbConnection != null)
                dbConnection.close();
        } catch (SQLException e) {
            System.err.println(e);
        }
    }

    return ls;
}

I expect it to get the expiration date. However it keeps saying:

java.sql.SQLException: no such column: 'SP_SELLBY_DATE'

Edit:

I changed the code to look like this:

    public ArrayList<String> GetExpiredStock(){
    Connection dbConnection = null;
    ResultSet list = null;
    ArrayList<String> ls = new ArrayList<String>();

    LocalDate currentDate = LocalDate.now();
    //System.out.println(today);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");

    try {
        dbConnection = DriverManager.getConnection("jdbc:sqlite:"+dbName+".db");

        Statement Query_Statement = dbConnection.createStatement();
        Query_Statement.setQueryTimeout(10);

        list = Query_Statement.executeQuery("SELECT SP_SELLBY_DATE, STOCK_ID FROM STOCK_PURCHASE"); //this works

        while (list.next()) {
            try {
            String da = list.getString("SP_SELLBY_DATE");
            int id = list.getInt("STOCK_ID");
            System.out.println("Executed on id = " + id);
            LocalDate expDate = LocalDate.parse(da, formatter);
            LocalDate monthAway = expDate.minusMonths(1);
            System.out.println(currentDate);
            if(currentDate.isAfter(monthAway)) {

                ResultSet ids = Query_Statement.executeQuery("SELECT STOCK_NAME FROM STOCK WHERE STOCK_ID=" + id);

                ls.add(ids.getString("STOCK_NAME") + "\t\t" +
                        da + "\t\t"+  getStockQuant(id,
                                currentDate));

            }
            }catch(SQLException e) {
                System.err.println(e);
                continue;

            }
        }

    } catch (SQLException e) {
        System.err.println(e.getMessage());
    } finally {
        try {
            if (dbConnection != null)
                dbConnection.close();
        } catch (SQLException e) {
            System.err.println(e);
        }
    }

    return ls;

But it still fails after the first iteration


问:
How to fix this up? " Unknown action The action 'index' could not be found for UsersController"
When I go to my localhost:3000/users page, I get:

Unknown action

The action 'index' could not be found for UsersController.

答:
You need not define the default actions (assuming appropriate http method), all you need to do is add the following to your config/routes.rb</p>

```<code>resources :users
</code>```

Body:
You need not define the default actions (assuming appropriate http method), all you need to do is add the following to your config/routes.rb

resources :users


问:
Accessing field in document of Firestore rule is not working
I am writing Firestore rules for an android app I'm currently developing. I am having trouble writing security rules. I want to have a collection of editors where each document is named after a userId and stores the role of that userId in itself.

The path to the document for each editor is users/(userId of owner's data being accessed)/editors/(userId of accessing user). The field that contains the role is "Role" and currently the only role is "Owner". Thus it is shown in the database as Role: "Owner".

```<code>match /users/{userId} {
    allow read, write: if getUserData().Role == "Owner";
}

function isSignedIn() {
    return request.auth != null;
}

function getUserData()
{
    return get(/databases/$(database)/documents/users/$(userId)/editors/$(request.auth.uid)).data;
}
</code>```

Simulated read and writes are currently being denied.

答:
Given how your functions are scoped, you'll have to pass userId into the call to getUserData:

```<code>match /users/{userId} {
    allow read, write: if getUserData(userId).Role == "Owner";
}

function isSignedIn() {
    return request.auth != null;
}

function getUserData(userId)
{
    return get(/databases/$(database)/documents/users/$(userId)/editors/$(request.auth.uid)).data;
}
</code>```

Body:
I am writing Firestore rules for an android app I'm currently developing. I am having trouble writing security rules. I want to have a collection of editors where each document is named after a userId and stores the role of that userId in itself.

The path to the document for each editor is users/(userId of owner's data being accessed)/editors/(userId of accessing user). The field that contains the role is "Role" and currently the only role is "Owner". Thus it is shown in the database as Role: "Owner".

match /users/{userId} {
    allow read, write: if getUserData().Role == "Owner";
}

function isSignedIn() {
    return request.auth != null;
}

function getUserData()
{
    return get(/databases/$(database)/documents/users/$(userId)/editors/$(request.auth.uid)).data;
}

Simulated read and writes are currently being denied.

Body:
Given how your functions are scoped, you'll have to pass userId into the call to getUserData:

match /users/{userId} {
    allow read, write: if getUserData(userId).Role == "Owner";
}

function isSignedIn() {
    return request.auth != null;
}

function getUserData(userId)
{
    return get(/databases/$(database)/documents/users/$(userId)/editors/$(request.auth.uid)).data;
}


问:
Looping through linked lists
So basically, what I'm trying to do is going through all the nodes and verify if node.value is <= cost. If it is I need to remove that node and in the end I want to store the nodes that weren't remove in a new struct. I'm not sure how exactly am I suppose to do this.

This struct can be an example:

```<code>struct node {
    int value;
    node * next;
}
</code>```

I'm going through all the nodes and remove only the ones that doen't have the required.

```<code>node * verify_money(node * head, int cost)
{

    node * iterator = head;

    while(iterator != NULL){
       if(iterator.value <= cost) {
           /*remove this node*/
       }
       iterator = iterator.next;
    }

return /*struct without nodes removed/*

}
</code>```

I want to get the remaining nodes.

答:
What you are asking for really depends on your requirements, which you did not make clear enough.

If you are expected to modify the input list that is being verified, you can do something like this:

```<code>node * verify_money(node * head, int cost)
{
    node * iterator = head;
    node * previous = NULL;

    while (iterator) {
        node *next = iterator->next;

        if (iterator->value <= cost) {
            if (previous) previous->next = next;
            if (head == iterator) head = next;
            delete iterator;
        }
        else
            previous = iterator;

        iterator = next;
    }

    return head;
}
</code>```

If you are expected to return a new list without modifying the original list, you can do something like this instead:

```<code>node * verify_money(node * head, int cost)
{
    node * new_head = NULL;
    node ** new_node = &new_head;

    node * iterator = head;
    while (iterator) {
        if (iterator->value > cost) {
            *new_node = new node;
            (*new_node)->cost = value;
            (*new_node)->next = NULL;
            new_node = &((*new_node)->next);
        }
        iterator = iterator->next;
    }

    return new_head;
}
</code>```

Title: Looping through linked lists

Body:
So basically, what I'm trying to do is going through all the nodes and verify if node.value is <= cost. If it is I need to remove that node and in the end I want to store the nodes that weren't remove in a new struct. I'm not sure how exactly am I suppose to do this.

This struct can be an example:

struct node {
    int value;
    node * next;
}

I'm going through all the nodes and remove only the ones that doen't have the required.

node * verify_money(node * head, int cost)
{

    node * iterator = head;

    while(iterator != NULL){
       if(iterator.value <= cost) {
           /*remove this node*/
       }
       iterator = iterator.next;
    }

return /*struct without nodes removed/*

}

I want to get the remaining nodes.

Body:
What you are asking for really depends on your requirements, which you did not make clear enough.

If you are expected to modify the input list that is being verified, you can do something like this:

node * verify_money(node * head, int cost)
{
    node * iterator = head;
    node * previous = NULL;

    while (iterator) {
        node *next = iterator->next;

        if (iterator->value <= cost) {
            if (previous) previous->next = next;
            if (head == iterator) head = next;
            delete iterator;
        }
        else
            previous = iterator;

        iterator = next;
    }

    return head;
}

If you are expected to return a new list without modifying the original list, you can do something like this instead:

node * verify_money(node * head, int cost)
{
    node * new_head = NULL;
    node ** new_node = &new_head;

    node * iterator = head;
    while (iterator) {
        if (iterator->value > cost) {
            *new_node = new node;
            (*new_node)->cost = value;
            (*new_node)->next = NULL;
            new_node = &((*new_node)->next);
        }
        iterator = iterator->next;
    }

    return new_head;
}


问:
Cannot get checkboxes of component to render based off state of another component
In my component did update, I console.log this.state.checkedTeams and this.state.checked. These values are determined through the map in componentDidUpdate. They read as they should read.

However, when I console log the values in side the render, I get empty arrays.

When I try to set the state in componentDidUpdate, I exceed the maximum depth and throw an error.

The goal of this to be able to adjust this.state.checked based off of the state of a foreign component.

```<code>import React, { Component } from 'react'
import { Text, View } from 'react-native'
import { connect } from 'react-redux'
import { loadTeams, loadLeagues } from '../actions'
import Check from './CheckBox'

class TeamSelect extends Component {
    constructor(props) {
        super(props)
        this.state = {
            checked: [],
            checkedTeams: [],
            setOnce: 0
        }
    }

    componentDidUpdate() {

        this.state.checked.length = 0

            this.props.team.map(
                (v, i) => {
                    if(this.props.checkedLeagues.includes(v.league.acronym)){
                        this.state.checked.push(true)
                        this.state.checkedTeams.push(v.team_name)
                    } else{
                        this.state.checked.push(false)
                    }
                }
            )

        console.log('checkedTeams', this.state.checkedTeams)
        console.log('checked', this.state.checked)
    }

    // componentDidUpdate(){
    //     if(this.state.checked.length === 0) {
    //         this.props.team.map(
    //             (v, i) => {
    //                 if(this.props.checkedLeagues.includes(v.league.acronym)){
    //                     this.state.checked.push(true)
    //                     this.state.checkedTeams.push(v.team_name)
    //                 } else{
    //                     this.state.checked.push(false)
    //                 }
    //             }
    //         )
    //     }

    //     console.log('checked league', this.props.checkedLeagues)
    // }

    changeCheck = (index, name) => {

        firstString = []

        if(!this.state.checkedTeams.includes(name)) {
            firstString.push(name)
        } else {
            firstString.filter(v => { return v !== name})
        }

        this.state.checkedTeams.map(
            (v, i) => {
                if(v !== name) {
                    firstString.push(v)
                }
            }
        )

        if(name === this.state.checkedTeams[0] && firstString.length === 0) {
            this.setState({ checkMessage: `Don't you want something to look at?` })
        } else {
            if(!this.state.checkedTeams.includes(name)){
                this.state.checkedTeams.push(name)
            } else {
                this.setState({checkedTeams: this.state.checkedTeams.filter(v => { return v !== name})})
            }
            this.state.checked[index] = !this.state.checked[index]
            this.setState({ checked: this.state.checked })

            // queryString = []

            // firstString.map(
            //     (v, i) => {
            //         if (queryString.length < 1) {
            //             queryString.push(`?league=${v}`)
            //         } else if (queryString.length >= 1 ) {
            //             queryString.push(`&league=${v}`)
            //         }
            //     }
            // )
            // axios.get(`http://localhost:4000/reports${queryString.join('')}`)
            //         .then(response => {
            //             this.props.loadCards(response.data)
            //         })
        }
                // console.log('first string', firstString)
                // console.log('in function', this.state.checkedTeams)
    }

    render() {console.log('in render - checkedTeams', this.state.checkedTeams)
    console.log('in render - checked', this.state.checked)

        return(
          <View>
              {
                  this.props.team === null ?'' : this.props.team.map(
                      (v, i) => {
                         return(
                            <View key={i}>
                                <Check
                                    checked={this.state.checked[i]}
                                    index={i}
                                    value={v.team_name}
                                    changeCheck={this.changeCheck}
                                />

                               { v.team_name === undefined ? null :
                                <Text>{v.team_name}</Text>}
                            </View>

                            )
                      }
                  )
             }
          </View>
        )
    }
}

function mapStateToProps(state) {
    return {
      team: state.team.team,
      checkedLeagues: state.league.checkedLeagues
     }
   }

export default connect(mapStateToProps)(TeamSelect)
</code>```

答:
You are mutating state directly in several places (very bad). You have to use this.setState(new_state) or react looses track of what is changing. In order to change the state of one component based on the value of another, you need to have the dependent component as a child of the control component so it can receive the value as a prop or you need to pass a state changing function to the controlling element that is bound to the dependent element.
Read the official react docs on how state works and lifting state for more info.
https://reactjs.org/docs/faq-state.html

https://reactjs.org/docs/lifting-state-up.html

Body:
In my component did update, I console.log this.state.checkedTeams and this.state.checked. These values are determined through the map in componentDidUpdate. They read as they should read.

However, when I console log the values in side the render, I get empty arrays.

When I try to set the state in componentDidUpdate, I exceed the maximum depth and throw an error.

The goal of this to be able to adjust this.state.checked based off of the state of a foreign component.

import React, { Component } from 'react'
import { Text, View } from 'react-native'
import { connect } from 'react-redux'
import { loadTeams, loadLeagues } from '../actions'
import Check from './CheckBox'

class TeamSelect extends Component {
    constructor(props) {
        super(props)
        this.state = {
            checked: [],
            checkedTeams: [],
            setOnce: 0
        }
    }

    componentDidUpdate() {

        this.state.checked.length = 0

            this.props.team.map(
                (v, i) => {
                    if(this.props.checkedLeagues.includes(v.league.acronym)){
                        this.state.checked.push(true)
                        this.state.checkedTeams.push(v.team_name)
                    } else{
                        this.state.checked.push(false)
                    }
                }
            )

        console.log('checkedTeams', this.state.checkedTeams)
        console.log('checked', this.state.checked)
    }

    // componentDidUpdate(){
    //     if(this.state.checked.length === 0) {
    //         this.props.team.map(
    //             (v, i) => {
    //                 if(this.props.checkedLeagues.includes(v.league.acronym)){
    //                     this.state.checked.push(true)
    //                     this.state.checkedTeams.push(v.team_name)
    //                 } else{
    //                     this.state.checked.push(false)
    //                 }
    //             }
    //         )
    //     }

    //     console.log('checked league', this.props.checkedLeagues)
    // }

    changeCheck = (index, name) => {

        firstString = []

        if(!this.state.checkedTeams.includes(name)) {
            firstString.push(name)
        } else {
            firstString.filter(v => { return v !== name})
        }

        this.state.checkedTeams.map(
            (v, i) => {
                if(v !== name) {
                    firstString.push(v)
                }
            }
        )

        if(name === this.state.checkedTeams[0] && firstString.length === 0) {
            this.setState({ checkMessage: `Don't you want something to look at?` })
        } else {
            if(!this.state.checkedTeams.includes(name)){
                this.state.checkedTeams.push(name)
            } else {
                this.setState({checkedTeams: this.state.checkedTeams.filter(v => { return v !== name})})
            }
            this.state.checked[index] = !this.state.checked[index]
            this.setState({ checked: this.state.checked })

            // queryString = []

            // firstString.map(
            //     (v, i) => {
            //         if (queryString.length < 1) {
            //             queryString.push(`?league=${v}`)
            //         } else if (queryString.length >= 1 ) {
            //             queryString.push(`&league=${v}`)
            //         }
            //     }
            // )
            // axios.get(`http://localhost:4000/reports${queryString.join('')}`)
            //         .then(response => {
            //             this.props.loadCards(response.data)
            //         })
        }
                // console.log('first string', firstString)
                // console.log('in function', this.state.checkedTeams)
    }

    render() {console.log('in render - checkedTeams', this.state.checkedTeams)
    console.log('in render - checked', this.state.checked)

        return(
          <View>
              {
                  this.props.team === null ?'' : this.props.team.map(
                      (v, i) => {
                         return(
                            <View key={i}>
                                <Check
                                    checked={this.state.checked[i]}
                                    index={i}
                                    value={v.team_name}
                                    changeCheck={this.changeCheck}
                                />

                               { v.team_name === undefined ? null :
                                <Text>{v.team_name}</Text>}
                            </View>

                            )
                      }
                  )
             }
          </View>
        )
    }
}

function mapStateToProps(state) {
    return {
      team: state.team.team,
      checkedLeagues: state.league.checkedLeagues
     }
   }

export default connect(mapStateToProps)(TeamSelect)


问:
What are effective ways to implement "difficulty" levels to an AI in Tic Tac Toe?
I am developing a simple Tic Tac Toe android app that supports 1 or 2 players. I have implemented an AI for 1 player mode which uses the minimax algorithm to play perfectly (either wins or ties). I want to allow for easy, medium, and hard difficulties the user can switch between. What are some ways I can achieve this?

My first thought was randomly choosing between making a random move or a perfect move. The probability for making a perfect move would be 60% for medium and 10% for easy. Any other ideas or modifications?

答:
You have a few ways you can adjust strength, although the level of granularity is not great for a game as simple as tic-tac-toe.

Limit your search depth. For example: if the AI only looks 1-2 turns ahead, it's possible to use a strategy to trap it into an unavoidable losing state, while a deeper tree could predict well enough to counter every strategy and always force a draw.

Weaken your evaluation function. This is a bit difficult to do meaningfully in tic-tac-toe, but you might be able to come up with something. If the AI undervalues or overvalues something, it will play worse.

Add noise. Give your program a random chance to select a suboptimal move.

Bias suboptimal decisions. Make the AI less likely to lead the first move with a corner spot, for example.

You will need to experiment to find out what feels right.


问:
How to implement google place picker using Google's new Place SDK 1.0 latest
How to implement Google map place picker in android studio using google new place sdk library</p>

答:
You just cannot use PlacePicker anymore starting 29 july 2019 .

Notice: The Place Picker (Android, iOS) is deprecated as of January 29, 2019. This feature will be turned off on July 29, 2019, and will no longer be available after that date.

You should build you own UI based on the new Google places SDK

Here you can learn more about it


问:
Assign nil value to double in Objective-C
In my iOS iPhone app I have this method:

```<code>-(id)initWithLocationName:(NSString *)locatNm latitude:(double)lati longitude:(double)longi xCoord:(double)xco yCoord:(double)yco;
</code>```

In this method I need to assign nil value to xCoord & yCoord.

How can I assign nil to double?

答:
nil is for Objective-C objects, and double is a primitive data type (i.e., it isn’t an Objective-C object), hence you cannot assign nil to a double variable.

If 0.0 is not an option to represent the absence of value, you can use NAN and isnan instead. For instance:

```<code>#include <math.h>

double x = 0.0;
double y = NAN;

if (isnan(x)) NSLog(@"x is not a number"); // this won't be logged
if (isnan(y)) NSLog(@"y is not a number"); // this will be logged
</code>```

Body:
In my iOS iPhone app I have this method:

-(id)initWithLocationName:(NSString *)locatNm latitude:(double)lati longitude:(double)longi xCoord:(double)xco yCoord:(double)yco;

In this method I need to assign nil value to xCoord & yCoord.

How can I assign nil to double?

Body:
nil is for Objective-C objects, and double is a primitive data type (i.e., it isn’t an Objective-C object), hence you cannot assign nil to a double variable.

If 0.0 is not an option to represent the absence of value, you can use NAN and isnan instead. For instance:

#include <math.h>

double x = 0.0;
double y = NAN;

if (isnan(x)) NSLog(@"x is not a number"); // this won't be logged
if (isnan(y)) NSLog(@"y is not a number"); // this will be logged


问:
Implementing MATLAB Code in Java- Illumination Invariant
I have the following code written in MATLAB, taken from this paper on page 3:

```<code>function [ ii_image ] = RGB2IlluminationInvariant( image, alpha )
ii_image = 0.5 + log(image(:,:,2)) - alpha*log(image(:,:,3)) - (1-alpha)*log(image(:,:,1));
</code>```

This code should convert a 3-channel RGB image into its illumination invariant. I would like to know what the code is doing so that I can implement it in Java.

From what I can gather, it's calculating the logarithm of each red/green/blue pixel, and subtracting the values from each other, but the result isn't be an integer, so I can't apply it to Java's BufferedImage class when changing the RGB values. How can I emulate this function in Java?

答:
It's not so difficult to convert the function to JAVA.

The following code sample is a MATLAB implementation that is kind of straight forward to convert to JAVA.

You should pay attention to the range and type of the input and output elements, and to the memory ordering.

Read the comments in the following code:

%function [ ii_image ] = RGB2IlluminationInvariant( image, alpha )

%Initialize input (for executing the example):
image = imread('peppers.png');
image = max(image, 1); %Replace zero values with 1, because log(0) is -Inf
image = double(image)/255; %Convert image to double in range [1/255, 1]. In JAVA, you should use double(pix)/255 if pix is a byte in range [0, 255].
alpha = 0.9;

ii_image = 0.5 + log(image(:,:,2)) - alpha*log(image(:,:,3)) - (1-alpha)*log(image(:,:,1));

%Assume elements in JAVA are stored in three 2D arrays (3 planes): R, G, B
%For example: double[][] R = new double[384][512];
%In Matlab 3 planes are:
R = image(:,:,1);
G = image(:,:,2);
B = image(:,:,3);
%II_image = 0.5 + log(G) - alpha*log(B) - (1-alpha)*log(R);
II_image = zeros(size(R));

%Equivalent for loop (simple to implement in JAVA):
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
image_width = size(image, 2);
image_height = size(image, 1);
for y = 1:image_height %Iterate rows, In JAVA: for(y = 0; y < image_height; y++)
    for x = 1:image_width %Iterate columns, In JAVA: for(x = 0; x < image_width; x++)
        r = R(y, x); %In JAVA: double r = R[y][x];
        g = G(y, x);
        b = B(y, x);

        p = 0.5 + log(g) - alpha*log(b) - (1.0-alpha)*log(r);

        II_image(y, x) = p;
    end
end

%Display ii_image
figure;imshow(ii_image, []);impixelinfo;title('ii\_image');

%Show difference (for debugging):
%figure;imshow(ii_image - II_image, []);impixelinfo

%Display minimum and maximum - values are not valid as pixel values in JAVA.
disp(['min(ii_image) = ', num2str(min(ii_image(:)))]);
disp(['max(ii_image) = ', num2str(max(ii_image(:)))]);

%Convert II_image range to [0, 1]
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Find minimum and maximum (in JAVA you can do it inside the loop).
lo = min(II_image(:));
hi = max(II_image(:));

%Apply linear transformation:
II_image = (II_image - lo) / (hi - lo);

figure;imshow(II_image, []);impixelinfo;title('II\_image');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
```

I hope it helps you in the JAVA implementation.

Body:
I have the following code written in MATLAB, taken from this paper on page 3:

function [ ii_image ] = RGB2IlluminationInvariant( image, alpha )
ii_image = 0.5 + log(image(:,:,2)) - alpha*log(image(:,:,3)) - (1-alpha)*log(image(:,:,1));

This code should convert a 3-channel RGB image into its illumination invariant. I would like to know what the code is doing so that I can implement it in Java.

From what I can gather, it's calculating the logarithm of each red/green/blue pixel, and subtracting the values from each other, but the result isn't be an integer, so I can't apply it to Java's BufferedImage class when changing the RGB values. How can I emulate this function in Java?

Body:
It's not so difficult to convert the function to JAVA.

The following code sample is a MATLAB implementation that is kind of straight forward to convert to JAVA.

You should pay attention to the range and type of the input and output elements, and to the memory ordering.

Read the comments in the following code:

%function [ ii_image ] = RGB2IlluminationInvariant( image, alpha )

%Initialize input (for executing the example):
image = imread('peppers.png');
image = max(image, 1); %Replace zero values with 1, because log(0) is -Inf
image = double(image)/255; %Convert image to double in range [1/255, 1]. In JAVA, you should use double(pix)/255 if pix is a byte in range [0, 255].
alpha = 0.9;

ii_image = 0.5 + log(image(:,:,2)) - alpha*log(image(:,:,3)) - (1-alpha)*log(image(:,:,1));

%Assume elements in JAVA are stored in three 2D arrays (3 planes): R, G, B
%For example: double[][] R = new double[384][512];
%In Matlab 3 planes are:
R = image(:,:,1);
G = image(:,:,2);
B = image(:,:,3);
%II_image = 0.5 + log(G) - alpha*log(B) - (1-alpha)*log(R);
II_image = zeros(size(R));

%Equivalent for loop (simple to implement in JAVA):
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
image_width = size(image, 2);
image_height = size(image, 1);
for y = 1:image_height %Iterate rows, In JAVA: for(y = 0; y < image_height; y++)
    for x = 1:image_width %Iterate columns, In JAVA: for(x = 0; x < image_width; x++)
        r = R(y, x); %In JAVA: double r = R[y][x];
        g = G(y, x);
        b = B(y, x);

        p = 0.5 + log(g) - alpha*log(b) - (1.0-alpha)*log(r);

        II_image(y, x) = p;
    end
end

%Display ii_image
figure;imshow(ii_image, []);impixelinfo;title('ii\_image');

%Show difference (for debugging):
%figure;imshow(ii_image - II_image, []);impixelinfo

%Display minimum and maximum - values are not valid as pixel values in JAVA.
disp(['min(ii_image) = ', num2str(min(ii_image(:)))]);
disp(['max(ii_image) = ', num2str(max(ii_image(:)))]);

%Convert II_image range to [0, 1]
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Find minimum and maximum (in JAVA you can do it inside the loop).
lo = min(II_image(:));
hi = max(II_image(:));

%Apply linear transformation:
II_image = (II_image - lo) / (hi - lo);

figure;imshow(II_image, []);impixelinfo;title('II\_image');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

I hope it helps you in the JAVA implementation.


问:
How to convert a series of tuples to DataFrame?
I'm trying to add some extra data in additional columns to a data frame.

Consider this example code:

```<code>import pandas
import numpy

def more_data(d):
    return 1, 2

df = pandas.DataFrame({"A":[1, 2, 3], "B":[17, 16, 15]})

x = df.apply(more_data, axis=1)
df1 = pandas.DataFrame(x)
df2 = pandas.concat([df, df1], axis=1)

print(df2)
</code>```

The output is:

```<code>A  B       0
0  1  17  (1, 2)
1  2  16  (1, 2)
2  3  15  (1, 2)
</code>```

No surprise because apply() returns a sequence of tuples, which is faithfully added as a column of tuples to the data frame. What I want, however, is two more columns with the values returned in the tuples. How would that work?

答:
You were quite close with your own solution, if you convert your dataframe to a list, then construct it as a dataframe again defining the columns, it works:

```<code>def more_data(d):
    return 1, 2

df = pd.DataFrame({"A":[1, 2, 3], "B":[17, 16, 15]})

x = df.apply(more_data, axis=1)
df1 = pd.DataFrame(x.tolist(), columns=['Col1', 'Col2']) # <-- line which is different
df2 = pd.concat([df, df1], axis=1)
</code>```

```<code>   A   B  Col1  Col2
0  1  17     1     2
1  2  16     1     2
2  3  15     1     2
</code>```

Body:
I'm trying to add some extra data in additional columns to a data frame.

Consider this example code:

import pandas
import numpy

def more_data(d):
    return 1, 2

df = pandas.DataFrame({"A":[1, 2, 3], "B":[17, 16, 15]})

x = df.apply(more_data, axis=1)
df1 = pandas.DataFrame(x)
df2 = pandas.concat([df, df1], axis=1)

print(df2)

The output is:

A  B       0
0  1  17  (1, 2)
1  2  16  (1, 2)
2  3  15  (1, 2)

No surprise because apply() returns a sequence of tuples, which is faithfully added as a column of tuples to the data frame. What I want, however, is two more columns with the values returned in the tuples. How would that work?

Body:
You were quite close with your own solution, if you convert your dataframe to a list, then construct it as a dataframe again defining the columns, it works:

def more_data(d):
    return 1, 2

df = pd.DataFrame({"A":[1, 2, 3], "B":[17, 16, 15]})

x = df.apply(more_data, axis=1)
df1 = pd.DataFrame(x.tolist(), columns=['Col1', 'Col2']) # <-- line which is different
df2 = pd.concat([df, df1], axis=1)

   A   B  Col1  Col2
0  1  17     1     2
1  2  16     1     2
2  3  15     1     2


问:
How I can play audio in C# console application?
I would like to know if it possible just play some kind of audio file in C# Console Application.

I don't find any answer on this question.

Many Thanks

答:
In command prompt you can play an audio file by typing it's name  from location folder:

```<code>c:\my_Music>track1.mp3
</code>```

This opens the file with the format's associated progam so there will be a pop-up of an external program. Set program by using right-click on a file and choose "Open With".

I've not tested this in a console app. But you should be able to type a String into the console app and then trigger an ENTER press event.

Option 2:

Use SoundPlayer class.
A good tutorial for beginners.
Also can check this: Playing sounds on Console.

Body:
In command prompt you can play an audio file by typing it's name  from location folder:

c:\my_Music>track1.mp3

This opens the file with the format's associated progam so there will be a pop-up of an external program. Set program by using right-click on a file and choose "Open With".

I've not tested this in a console app. But you should be able to type a String into the console app and then trigger an ENTER press event.

Option 2:

Use SoundPlayer class.
A good tutorial for beginners.
Also can check this: Playing sounds on Console.


问:
why package.json need main and start java script
in package.json, if main is defined and pointing to a java script file, what is the purpose of start within scripts attribute. Can I remove either java script ?</p>

```<code>"main": "xyz.js",
"scripts": {
"star":"node your-script.js"
}
</code>```

答:
The start script is used to run your project for example using npm start.

But the main field is an indicator of the entry point for your project that is used to load you module when you're building a module/library to be used in other projects.

Here's a link to the documentation:
https://docs.npmjs.com/files/package.json#main

Body:
in package.json, if main is defined and pointing to a java script file, what is the purpose of start within scripts attribute. Can I remove either java script ?

"main": "xyz.js",
"scripts": {
"star":"node your-script.js"
}


问:
How do I activate the click event for a button on Android?
How do I activate the click event for a button on Android?</p>

答:
I'm not sure if you want to "click" the button via java or listen for the click event.

The listening is descirbed correctly by Graham

To automaticly click the Button you could call

```<code>Button b= (Button) findViewById(R.id.button1);
</code>```

b.performClick();

Body:
I'm not sure if you want to "click" the button via java or listen for the click event.

The listening is descirbed correctly by Graham

To automaticly click the Button you could call

Button b= (Button) findViewById(R.id.button1);

b.performClick();


问:
How to select a value from a DataFrame (even if there is no entry)
I'm trying to select an entry from a DataFrame structure based on some conditions. It works - as long as there is an entry that fits to the query (first example in code shown below)

But sometimes, there is no proper entry, so the return value should be an empty string (not an error message). This I cannot achieve.

```<code>from pandas import DataFrame

data = {'ID': [1, 1, 2, 2],
        'Key': ['Key1','Key2','Key1','Key2'],
        'Value': ['Value1', 'Value2', 'Value3', 'Value4']
        }

df = DataFrame(data,columns= ['ID', 'Key','Value'])

print(df.loc[(df['ID']==1) & (df['Key'] == 'Key2')].iloc[-1,-1])
# shows "Value2" (correct)

print(df.loc[(df['ID']==1) & (df['Key'] == 'Key3')].iloc[-1,-1])
# should show "" (desired output)
</code>```

Thanks in advance.

答:
The following does what you are looking for:</p>

```<code>keyname = 'Key2' # Key3
try:
    print(df.loc[(df['ID']==1) & (df['Key'] == keyname)].iloc[-1,-1])
except IndexError:
    print("")
</code>```

Body:
I'm trying to select an entry from a DataFrame structure based on some conditions. It works - as long as there is an entry that fits to the query (first example in code shown below)

But sometimes, there is no proper entry, so the return value should be an empty string (not an error message). This I cannot achieve.

from pandas import DataFrame

data = {'ID': [1, 1, 2, 2],
        'Key': ['Key1','Key2','Key1','Key2'],
        'Value': ['Value1', 'Value2', 'Value3', 'Value4']
        }

df = DataFrame(data,columns= ['ID', 'Key','Value'])

print(df.loc[(df['ID']==1) & (df['Key'] == 'Key2')].iloc[-1,-1])
# shows "Value2" (correct)

print(df.loc[(df['ID']==1) & (df['Key'] == 'Key3')].iloc[-1,-1])
# should show "" (desired output)

Thanks in advance.

Body:
The following does what you are looking for:

keyname = 'Key2' # Key3
try:
    print(df.loc[(df['ID']==1) & (df['Key'] == keyname)].iloc[-1,-1])
except IndexError:
    print("")


问:
Error with moment js in angular 7 library
Error while trying to use the moment js in angular 7 library (Same is working in normal angular app)

Steps to replicate:

Create angular library

```<code>ng generate library my-lib
npm install moment --save
</code>```

in a component try using below code

```<code>import * as moment from 'moment';

export interface CalendarDate {
  mDate: moment.Moment;
}

export class CalenderComponent implements OnInit {
  currentDate = moment();
...
</code>```

When we try ng build my-lib --watch It will fail with below error

```<code>Building Angular Package
Building entry point 'student'
Compiling TypeScript sources through ngc
Bundling to FESM2015

BUILD ERROR
Cannot call a namespace ('moment')
Error: Cannot call a namespace ('moment')
    at error (D:\Eschool\homework\student\node_modules\rollup\dist\rollup.js:346
0:30)
    at Module.error (D:\Eschool\homework\student\node_modules\rollup\dist\rollup
.js:13349:9)
    at CallExpression.bind (D:\Eschool\homework\student\node_modules\rollup\dist
\rollup.js:10228:30)
    at AssignmentExpression.NodeBase.bind (D:\Eschool\homework\student\node_modu
les\rollup\dist\rollup.js:9183:23)
    at AssignmentExpression.bind (D:\Eschool\homework\student\node_modules\rollu
p\dist\rollup.js:9919:31)
    at ExpressionStatement$$1.NodeBase.bind (D:\Eschool\homework\student\node_mo
dules\rollup\dist\rollup.js:9183:23)
    at BlockStatement$$1.NodeBase.bind (D:\Eschool\homework\student\node_modules
\rollup\dist\rollup.js:9179:31)
    at FunctionExpression.NodeBase.bind (D:\Eschool\homework\student\node_module
s\rollup\dist\rollup.js:9183:23)
    at MethodDefinition.NodeBase.bind (D:\Eschool\homework\student\node_modules\
rollup\dist\rollup.js:9183:23)
    at ClassBody.NodeBase.bind (D:\Eschool\homework\student\node_modules\rollup\
dist\rollup.js:9179:31)
    at ClassDeclaration$$1.NodeBase.bind (D:\Eschool\homework\student\node_modul
es\rollup\dist\rollup.js:9183:23)
    at ExportNamedDeclaration.bind (D:\Eschool\homework\student\node_modules\rol
lup\dist\rollup.js:10641:30)
    at Program.NodeBase.bind (D:\Eschool\homework\student\node_modules\rollup\di
st\rollup.js:9179:31)
    at Module.bindReferences (D:\Eschool\homework\student\node_modules\rollup\di
st\rollup.js:13303:18)
    at Graph.link (D:\Eschool\homework\student\node_modules\rollup\dist\rollup.j
s:21489:20)
    at D:\Eschool\homework\student\node_modules\rollup\dist\rollup.js:21584:19

Compilation failed. Watching for file changes...
</code>```

答: I had the same issue before. To fix it, use moment-es6 in your library instead of moment. Then it'll work.</p>

Body:
Error while trying to use the moment js in angular 7 library (Same is working in normal angular app)

Steps to replicate:

Create angular library

ng generate library my-lib
npm install moment --save

in a component try using below code

import * as moment from 'moment';

export interface CalendarDate {
  mDate: moment.Moment;
}

export class CalenderComponent implements OnInit {
  currentDate = moment();
...

When we try ng build my-lib --watch It will fail with below error

Building Angular Package
Building entry point 'student'
Compiling TypeScript sources through ngc
Bundling to FESM2015

BUILD ERROR
Cannot call a namespace ('moment')
Error: Cannot call a namespace ('moment')
    at error (D:\Eschool\homework\student\node_modules\rollup\dist\rollup.js:346
0:30)
    at Module.error (D:\Eschool\homework\student\node_modules\rollup\dist\rollup
.js:13349:9)
    at CallExpression.bind (D:\Eschool\homework\student\node_modules\rollup\dist
\rollup.js:10228:30)
    at AssignmentExpression.NodeBase.bind (D:\Eschool\homework\student\node_modu
les\rollup\dist\rollup.js:9183:23)
    at AssignmentExpression.bind (D:\Eschool\homework\student\node_modules\rollu
p\dist\rollup.js:9919:31)
    at ExpressionStatement$$1.NodeBase.bind (D:\Eschool\homework\student\node_mo
dules\rollup\dist\rollup.js:9183:23)
    at BlockStatement$$1.NodeBase.bind (D:\Eschool\homework\student\node_modules
\rollup\dist\rollup.js:9179:31)
    at FunctionExpression.NodeBase.bind (D:\Eschool\homework\student\node_module
s\rollup\dist\rollup.js:9183:23)
    at MethodDefinition.NodeBase.bind (D:\Eschool\homework\student\node_modules\
rollup\dist\rollup.js:9183:23)
    at ClassBody.NodeBase.bind (D:\Eschool\homework\student\node_modules\rollup\
dist\rollup.js:9179:31)
    at ClassDeclaration$$1.NodeBase.bind (D:\Eschool\homework\student\node_modul
es\rollup\dist\rollup.js:9183:23)
    at ExportNamedDeclaration.bind (D:\Eschool\homework\student\node_modules\rol
lup\dist\rollup.js:10641:30)
    at Program.NodeBase.bind (D:\Eschool\homework\student\node_modules\rollup\di
st\rollup.js:9179:31)
    at Module.bindReferences (D:\Eschool\homework\student\node_modules\rollup\di
st\rollup.js:13303:18)
    at Graph.link (D:\Eschool\homework\student\node_modules\rollup\dist\rollup.j
s:21489:20)
    at D:\Eschool\homework\student\node_modules\rollup\dist\rollup.js:21584:19

Compilation failed. Watching for file changes...


问:
JavaScript: filter() Method Returning Back Original Array and Not Filtering
I have the following code below using the filter() array function.

arr = [12, 5, 8, 130, 44]

function test(arr) {
  return arr.filter((element) => {
    return element >= 10
  });
}

console.log(test(arr))```

My code is returning the original array ([ 12, 5, 8, 130, 44 ]) and not filtering at all.  What am I doing wrong?

Note: I want to use the filter() method for this.

答: You code is missing a few things, but you are on the right track. Array.filter doesn't change the original array. Set a variable,var filter, and set it equal to the function test. Then console.log(filter(arr))

Body:
I have the following code below using the filter() array function.

arr = [12, 5, 8, 130, 44]

function test(arr) {
  return arr.filter((element) => {
    return element >= 10
  });
}

console.log(test(arr))

My code is returning the original array ([ 12, 5, 8, 130, 44 ]) and not filtering at all.  What am I doing wrong?

Note: I want to use the filter() method for this.


问:
LinkedIn V2 api full profile
I am using linked in V1 api to fetch information about the authenticated user. my app have r_fullprofile permission.

https://api.linkedin.com/v1/people~:(id,first-name,last-name,headline,picture-url,pictureUrls::(original),email-address,public-profile-url,industry,summary,specialties,phone-numbers,main-address,location:(name,country:(code)),positions:(id,title,summary,start-date,end-date,is-current,company:(id,name,type,size,industry,ticker)),educations:(id,school-name,field-of-study,start-date,end-date,degree,activities,notes,grade),associations,interests,num-recommenders,date-of-birth,publications:(id,title,publisher:(name),authors:(id,name,person),date,url,summary),patents:(id,title,summary,number,status:(id,name),office:(name),inventors:(id,name,person),date,url),languages:(id,language:(name),proficiency:(level,name)),skills:(id,skill:(name)),certifications:(id,name,authority:(name),number,start-date,end-date),courses:(id,name,number,occupation),recommendations-received:(id,recommendation-type,recommendation-text,recommender),honors-awards,three-current-positions,three-past-positions,volunteer).

Now, i am migrating to V2 API i cannot able to fetch all profile information.

when i make request to https://api.linkedin.com/v2/me

I get very few information like FirstName, LastName, profilePicture,id

I also tried to get information using

https://api.linkedin.com/v2/me?fields=id,firstName,lastName,email-address

with above endpoint can able to access id,firstname and lastname not email.

https://api.linkedin.com/v2/me?projection=(id,firstName,lastName,skills) -with this endpoint i can access id,firstname and lastname, not skills

答:
LinkedIn's v2 APIs return a reduced "Lite" Profile by default. Access to the Full Profile requires a Partnership with LinkedIn.

This API will only recognize a new “Lite Profile” permission, which supports a reduced set of member profile fields. See the documentation for more details.

source: https://engineering.linkedin.com/blog/2018/12/developer-program-updates

Title: LinkedIn V2 api full profile


问:
How to check if a Perl scalar can be treated as a subroutine?
I have an API that originally took just a plain constant integer, but I am extending it so it can instead be computed when used by passing a subroutine reference instead. To keep backwards compatibility, I'm testing if it's a code reference:

```<code>'CODE' eq ref($var)
    ? $var->()
    : $var;
</code>```

but I realized that excludes objects that act as subroutines. Something like this:

```<code>package Foo {
    sub new { bless {}, 'Foo' }
    use overload '&{}' => sub { sub { "Hello, world." } };
}
</code>```

I could just try to call it inside an eval block, but then would have to carefully check $@ to determine if it failed because it wasn't a subroutine reference (thus falling back to it being a simple scalar) vs. the called subroutine failed for some reason (error should be propagated).

In this case, of course, since the old value was a non-reference, I could just presume any reference is callable, but I'd like a general solution (as I've used this approach before when it used to be a hashref). Is there a simple and reliable way to test if a scalar is “executable”?

答:
You can check by attempting to dereference it, but not run it, as a subroutine.

```<code>my $is_code = ref $ref && do { local $@; eval { $ref = \&$ref; 1 } };
</code>```

In this case you don't care what the error is, just whether one occurred. \&$ref is sufficient, but by assigning the result back to $ref you can avoid invoking the overload a second time when you call that coderef. Localizing $@ is just for politeness.

As used in my Autoload::AUTOCAN module, with original credit to haarg.

Body:
I have an API that originally took just a plain constant integer, but I am extending it so it can instead be computed when used by passing a subroutine reference instead. To keep backwards compatibility, I'm testing if it's a code reference:

'CODE' eq ref($var)
    ? $var->()
    : $var;

but I realized that excludes objects that act as subroutines. Something like this:

package Foo {
    sub new { bless {}, 'Foo' }
    use overload '&{}' => sub { sub { "Hello, world." } };
}

I could just try to call it inside an eval block, but then would have to carefully check $@ to determine if it failed because it wasn't a subroutine reference (thus falling back to it being a simple scalar) vs. the called subroutine failed for some reason (error should be propagated).

In this case, of course, since the old value was a non-reference, I could just presume any reference is callable, but I'd like a general solution (as I've used this approach before when it used to be a hashref). Is there a simple and reliable way to test if a scalar is “executable”?

Body:
You can check by attempting to dereference it, but not run it, as a subroutine.

my $is_code = ref $ref && do { local $@; eval { $ref = \&$ref; 1 } };

In this case you don't care what the error is, just whether one occurred. \&$ref is sufficient, but by assigning the result back to $ref you can avoid invoking the overload a second time when you call that coderef. Localizing $@ is just for politeness.

As used in my Autoload::AUTOCAN module, with original credit to haarg.