问:
how to set soap header using php for my xml content
```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xxxxx="xxxxx" xmlns:tem="http://tempuri.org/">
   <soapenv:Header>
      <Auth>
         <!--Optional:-->
         <xxxxx:id></xxxxx:id>
         <!--Optional:-->
         <xxxxx:Login></xxxxx:Login>
         <!--Optional:-->
         <xxxxx:pass></xxxxx:pass>
      </Auth>
   </soapenv:Header>
   <soapenv:Body>
      <tem:test>
         <!--Optional:-->
         <tem:test>test</tem:test>
      </tem:test>
   </soapenv:Body>
</soapenv:Envelope>
</code>```

php

```<code><?php

try {
    $client = new SoapClient(self::$url, array());
    $header = new SoapHeader("xxxxx", "Auth", $header_data, false);

    $client->__setSoapHeaders([$header]);

    $result = $client->ProcessarIntegracao($header, $test);
}
catch (Exception $e) {
    return 'soap error: ' . $e->getMessage();
}
</code>```

I tried lots of methods to send request, but it always return

soap header not found

答:
```<code><?php
error_reporting(-1);
ini_set('error_reporting', E_ALL);
ini_set("soap.wsdl_cache_enabled", "0");
ini_set('display_errors', 1);

//Generating a header

$client = new soapClient("https://secure.payzen.eu/vads-ws/v5?wsdl", $options = array(
    'trace'      => 1,
    'exceptions' => 0,
    'encoding'   => 'UTF-8',
    'soapaction' => '')
);

//Calculating values transmitted in the header

$ns        = 'http://v5.ws.vads.lyra.com/Header/';
$shopId    = "12345678";
$requestId = gen_uuid();
$timestamp = gmdate("Y-m-d\TH:i:s\Z");
$mode      = "TEST";
$key       = "123";
$authToken = base64_encode(hash_hmac('sha256', $requestId . $timestamp, $key, true));

//Creating the shopId, requestId, timestamp, mode et authToken headers

$headerShopId    = new SOAPHeader($ns, 'shopId', $shopId);
$headerRequestId = new SOAPHeader($ns, 'requestId', $requestId);
$headerTimestamp = new SOAPHeader($ns, 'timestamp', $timestamp);
$headerMode      = new SOAPHeader($ns, 'mode', $mode);
$headerAuthToken = new SOAPHeader($ns, 'authToken', $authToken);

//Adding headers into the SOAP Header

$headers = array(
    $headerShopId,
    $headerRequestId,
    $headerTimestamp,
    $headerMode,
    $headerAuthToken,
);

$client->__setSoapHeaders($headers);

function gen_uuid()
{
    return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        mt_rand(0, 0xffff), mt_rand(0, 0xffff),
        mt_rand(0, 0xffff),
        mt_rand(0, 0x0fff) | 0x4000,
        mt_rand(0, 0x3fff) | 0x8000,
        mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
    );
}
</code>```

Body:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xxxxx="xxxxx" xmlns:tem="http://tempuri.org/">
   <soapenv:Header>
      <Auth>

         <xxxxx:id></xxxxx:id>

         <xxxxx:Login></xxxxx:Login>

         <xxxxx:pass></xxxxx:pass>
      </Auth>
   </soapenv:Header>
   <soapenv:Body>
      <tem:test>

         <tem:test>test</tem:test>
      </tem:test>
   </soapenv:Body>
</soapenv:Envelope>

php

<?php

try {
    $client = new SoapClient(self::$url, array());
    $header = new SoapHeader("xxxxx", "Auth", $header_data, false);

    $client->__setSoapHeaders([$header]);

    $result = $client->ProcessarIntegracao($header, $test);
}
catch (Exception $e) {
    return 'soap error: ' . $e->getMessage();
}

I tried lots of methods to send request, but it always return

soap header not found


来源: stackexchange

问:
Comparison in for loop
I am fairly new to java and came across a problem while working on a project where i need to extract some data by comparing each result that i get out of a for loop with the other.

The forloop is to get results out of an sql query & the code for the forloop is as following:

```<code>      for (Map<String, Object> row : results) {
            String data= row.get("getdata").toString();
            }
</code>```

The data recieved out of this when the loop runs 2 times is somewhat like:

a12:1:123;b23:2:234;c24:3:344

a12:1:123;b23:2:234;c24:4:345

when, in the above data for the same first vale, the second value after ":" is different, I  want to get the third value, for example between c24:3:344 & c24:4:345 the second value is different i.e. 3 and 4 so I need to get 344 and 345.
similarly I need to find any such data in the results received by the for loop.

All you help is greatly appreciated and thanks in advance.

答:
Break it down a bit.

You have a loop, you're iterating over a structure and you need to compare every row with the previous row. Each iteration you will get the current row and compare it to the previous row, then set the previous row to the current row for the next iteration.

```<code>prevRowData = null;
for(Map<String, Object> row : results) {
    String currRowData = row.get("getdata").toString();
    if(prevRowData != null) {
        compareRows(currRowData, prevRowData);
    }
    prevRowData = currRowData;
}

private void compareRows(String currRowData, String prevRowData) {
    // split the row data into an array on the colon/semi-colon delimiter
    // to make it easier to compare each portion
    String[] currRow = currRowData.split(":|;");
    String[] prevRow = prevRowData.split(":|;");

    // if the first part is equal and the second part is not equal
    if(currRow[0].equals(prevRow[0] && !currRow[1].equals(prevRow[1])) {
        // print out the third part of each row (or return it or whatever)
        System.out.printf("currRow: %s, prevRow: %s", currRow[2], prevRow[2]);
    }
}
</code>```

This is pretty rough and you should do some validation and tailor it to your needs but I hope I have illustrated the basic idea.

ContentLicense: CC BY-SA 3.0

Title: Comparison in for loop

Body:
I am fairly new to java and came across a problem while working on a project where i need to extract some data by comparing each result that i get out of a for loop with the other.

The forloop is to get results out of an sql query & the code for the forloop is as following:

      for (Map<String, Object> row : results) {
            String data= row.get("getdata").toString();
            }

The data recieved out of this when the loop runs 2 times is somewhat like:

a12:1:123;b23:2:234;c24:3:344

a12:1:123;b23:2:234;c24:4:345

when, in the above data for the same first vale, the second value after ":" is different, I  want to get the third value, for example between c24:3:344 & c24:4:345 the second value is different i.e. 3 and 4 so I need to get 344 and 345.
similarly I need to find any such data in the results received by the for loop.

All you help is greatly appreciated and thanks in advance.

Body:
Break it down a bit.

You have a loop, you're iterating over a structure and you need to compare every row with the previous row. Each iteration you will get the current row and compare it to the previous row, then set the previous row to the current row for the next iteration.

prevRowData = null;
for(Map<String, Object> row : results) {
    String currRowData = row.get("getdata").toString();
    if(prevRowData != null) {
        compareRows(currRowData, prevRowData);
    }
    prevRowData = currRowData;
}

private void compareRows(String currRowData, String prevRowData) {
    // split the row data into an array on the colon/semi-colon delimiter
    // to make it easier to compare each portion
    String[] currRow = currRowData.split(":|;");
    String[] prevRow = prevRowData.split(":|;");

    // if the first part is equal and the second part is not equal
    if(currRow[0].equals(prevRow[0] && !currRow[1].equals(prevRow[1])) {
        // print out the third part of each row (or return it or whatever)
        System.out.printf("currRow: %s, prevRow: %s", currRow[2], prevRow[2]);
    }
}

This is pretty rough and you should do some validation and tailor it to your needs but I hope I have illustrated the basic idea.


问:
Passing JSON objects to jq arguments
Data sample - sample.json (full sample: https://pastebin.com/KFkVmc2M)

```<code>    {
      "ip": 3301234701,
      "_shodan": {
        "options": {
          "referrer": "7ae15507-f5cc-4353-b72e-5cc0b1c34c5e"
        },
      },
      "hash": -1056085507,
      "os": null,
      "title": "WHM Login",
      "opts": {
        "vulns": ["!CVE-2014-0160"],
        "heartbleed": "2017/08/29 09:57:30 196.196.216.13:2087 - SAFE\
        }
      },
      "isp": "Fiber Grid Inc",
      "http": {
        "redirects": [],
        "title": "WHM Login",
        "robots": null,
        "favicon": null,
        "host": "196.196.216.13",
        "html":
}
</code>```

Script using jq which I hoped would work and haven't found a another solution yet.

```<code>   cat sample.json | jq \
   --arg key0   'Host' \
   --arg value0 '.host' \
   --arg key1   'Vulnerability' \
   --arg value1 '.opts.vulns[0]' \
   --arg key2   'ISP' \
   --arg value2 '.isp' \
   '. | .[$key0]= $value0 | .[$key1]=$value1 | .[$key2]=$value2' \
   <<<'{}'
</code>```

The end result I hoped, but not getting:

```<code>{
  "Host": "196.196.216.13",
  "Vulnerability": "!CVE-2014-0160",
  "ISP": "Fiber Grid Inc"
}
</code>```

Right now it just returns the object as a string and I've tried a lot of different ways to approach the problem. I am quite new to working with JSON and jq but based on what I've read so far, the solution might not be as simple as I'm wishing?

Simply put, why isn't the object being returned as a value of the sample.json object and what do I have to do, to make it work?

Thanks!

to: chepner

```<code>{
  "196.196.216.13":[
  "AS63119",
  "Fiber Grid Inc",
  "2017-08-29T06:57:22.546423",
  "!CVE-2014-0160"
],
"196.196.216.14":[
  "AS63119",
  "Fiber Grid Inc",
  "2017-08-29T06:57:22.546423",
  "!CVE-2014-0160"
]
}
</code>```

答:
In response to the supplementary question ("to: chepner"):

The pastebin data does not contain "196.196.216.14" so the supplementary question is unclear, but you will probably want to start with:

```<code>jq '{(.ip_str): [.asn, .isp, .timestamp, opts.vulns[0] ]}' pastebin.json
</code>```

This produces:

```<code>{
  "196.196.216.13": [
    "AS63119",
    "Fiber Grid Inc",
    "2017-08-29T06:57:22.546423",
    "!CVE-2014-0160"
  ]
}
</code>```

The key point here is the pair of parentheses around .ip_str.

As mentioned elsewhere, the jq query is again so simple and straightforward that it seems doubtful that a parameterized version will offer any advantage.

Title: Passing JSON objects to jq arguments

Body:
Data sample - sample.json (full sample: https://pastebin.com/KFkVmc2M)

    {
      "ip": 3301234701,
      "_shodan": {
        "options": {
          "referrer": "7ae15507-f5cc-4353-b72e-5cc0b1c34c5e"
        },
      },
      "hash": -1056085507,
      "os": null,
      "title": "WHM Login",
      "opts": {
        "vulns": ["!CVE-2014-0160"],
        "heartbleed": "2017/08/29 09:57:30 196.196.216.13:2087 - SAFE\
        }
      },
      "isp": "Fiber Grid Inc",
      "http": {
        "redirects": [],
        "title": "WHM Login",
        "robots": null,
        "favicon": null,
        "host": "196.196.216.13",
        "html":
}

Script using jq which I hoped would work and haven't found a another solution yet.

   cat sample.json | jq \
   --arg key0   'Host' \
   --arg value0 '.host' \
   --arg key1   'Vulnerability' \
   --arg value1 '.opts.vulns[0]' \
   --arg key2   'ISP' \
   --arg value2 '.isp' \
   '. | .[$key0]= $value0 | .[$key1]=$value1 | .[$key2]=$value2' \
   <<<'{}'

The end result I hoped, but not getting:

{
  "Host": "196.196.216.13",
  "Vulnerability": "!CVE-2014-0160",
  "ISP": "Fiber Grid Inc"
}

Right now it just returns the object as a string and I've tried a lot of different ways to approach the problem. I am quite new to working with JSON and jq but based on what I've read so far, the solution might not be as simple as I'm wishing?

Simply put, why isn't the object being returned as a value of the sample.json object and what do I have to do, to make it work?

Thanks!

to: chepner

{
  "196.196.216.13":[
  "AS63119",
  "Fiber Grid Inc",
  "2017-08-29T06:57:22.546423",
  "!CVE-2014-0160"
],
"196.196.216.14":[
  "AS63119",
  "Fiber Grid Inc",
  "2017-08-29T06:57:22.546423",
  "!CVE-2014-0160"
]
}

Body:
In response to the supplementary question ("to: chepner"):

The pastebin data does not contain "196.196.216.14" so the supplementary question is unclear, but you will probably want to start with:

jq '{(.ip_str): [.asn, .isp, .timestamp, opts.vulns[0] ]}' pastebin.json

This produces:

{
  "196.196.216.13": [
    "AS63119",
    "Fiber Grid Inc",
    "2017-08-29T06:57:22.546423",
    "!CVE-2014-0160"
  ]
}

The key point here is the pair of parentheses around .ip_str.

As mentioned elsewhere, the jq query is again so simple and straightforward that it seems doubtful that a parameterized version will offer any advantage.


问:
Spring boot like module maven project change parent
I have project

```<code>-MyProject
    main.pom
  - spring-boot
    spring-boot.pom
  - maven module
    module.pom
  - maven module2
    module2.pom
</code>```

MyProject is parent with vwrsions in property.
module and module2 chields and has parnet - MyProject

For example in main pom:

```<code><properties>
    <spring.ws.version>3.0.0.RELEASE</spring.ws.version>
    ....
  </properties>
</code>```

and in module and module2 pom:

```<code><dependency>
            <groupId>org.springframework.ws</groupId>
            <artifactId>spring-ws-core</artifactId>
            <version>${spring.ws.version}</version>
        </dependency>
</code>```

Because:

```<code><parent>
        <artifactId>main.project</artifactId>
        <groupId>a.project</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
</code>```

But in spring boot module already parent:

```<code><parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.M6</version>
        <relativePath/>
    </parent>
</code>```

How can I change parent to MyProject and use spring boot?

答:
You can put the Spring Boot parent pom definition in the dependency management section of your parent pom instead.

```<code><dependencyManagement>
     <dependencies>
        <dependency>
            <!-- Import dependency management from Spring Boot -->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>1.5.8.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
</code>```

Details: https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-build-systems.html#using-boot-maven-without-a-parent

Body:
I have project

-MyProject
    main.pom
  - spring-boot
    spring-boot.pom
  - maven module
    module.pom
  - maven module2
    module2.pom

MyProject is parent with vwrsions in property.
module and module2 chields and has parnet - MyProject

For example in main pom:

<properties>
    <spring.ws.version>3.0.0.RELEASE</spring.ws.version>
    ....
  </properties>

and in module and module2 pom:

<dependency>
            <groupId>org.springframework.ws</groupId>
            <artifactId>spring-ws-core</artifactId>
            <version>${spring.ws.version}</version>
        </dependency>

Because:

<parent>
        <artifactId>main.project</artifactId>
        <groupId>a.project</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>

But in spring boot module already parent:

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.M6</version>
        <relativePath/>
    </parent>

How can I change parent to MyProject and use spring boot?

Body:
You can put the Spring Boot parent pom definition in the dependency management section of your parent pom instead.

<dependencyManagement>
     <dependencies>
        <dependency>
            <!-- Import dependency management from Spring Boot -->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>1.5.8.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

Details: https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-build-systems.html#using-boot-maven-without-a-parent


问:
What is wrong with using 'Not In' in this SQL query?
I have table called BST as shown below:

Here N is value of node of Binary Tree and P is its Parent node. I have to write a query that will determine if a node is a Root Node, Leaf Node or Inner Node. I wrote below SQL query for this:

```<code>select N,
case
when P is null then 'Root'
when N in (select distinct P from BST) then 'Inner'
when N not in (select distinct P from BST) then 'Leaf'
end as type
from BST
</code>```

However, this is not giving me desired result as last condition for 'Leaf' in Case statement doesn't satisfy for leaf node. I am getting below output in this case:

I have a workaround for now as below query which is giving me expected output:

```<code>select N,
case
when P is null then 'Root'
when N in (select distinct P from BST) then 'Inner'
else 'Leaf'
end as type
from BST
</code>```

Expected Output:

But I can't figure out what's wrong with the first one. Could someone explain me this?

答:
Because P has a null value.

You can't compare NULL with the regular (arithmetic) comparison operators. Any arithmetic comparison to NULL will return NULL, even NULL = NULL or NULL <> NULL will yield NULL.

Use IS or IS NOT instead.

Body:
I have table called BST as shown below:

Here N is value of node of Binary Tree and P is its Parent node. I have to write a query that will determine if a node is a Root Node, Leaf Node or Inner Node. I wrote below SQL query for this:

select N,
case
when P is null then 'Root'
when N in (select distinct P from BST) then 'Inner'
when N not in (select distinct P from BST) then 'Leaf'
end as type
from BST

However, this is not giving me desired result as last condition for 'Leaf' in Case statement doesn't satisfy for leaf node. I am getting below output in this case:

I have a workaround for now as below query which is giving me expected output:

select N,
case
when P is null then 'Root'
when N in (select distinct P from BST) then 'Inner'
else 'Leaf'
end as type
from BST

Expected Output:

But I can't figure out what's wrong with the first one. Could someone explain me this?


问:
How to make JTextField appear after a button click and only accept the same length of characters as another string -Java GUI
I had posted a similar question before but it got deleted by accident.

My JTextField is supposed to appear after clicking a button which it does but only after minimizing the window. Another problem with it is that it accepts single characters when it's supposed to accept a phrase of only a certain length.

Here's a bit of the code since it's so long:

```<code> static String answer = "MY PUZZLE", puzzle = "M- -U----";

  //inside constructor
  guess = new JTextField("Write in Caps");
  guess.setVisible(false);
  guess.addActionListener(this);
  board.add(guess);

  //actionperformed
  guess.setVisible(true);
  gueStr = guess.getText();

  if (gueStr.length() != answer.length()) //if it is not the same length
  {
    gueStr = "";
  }
</code>```

the String "puzzle" is changed if a letter button (code not shown here) that is a character from the "answer" String is pressed or if the user's guess is the same phrase as the answer String

```<code>  if ( gueStr.equals(answer)) //if the guess is the answer
  {
    puzzle = answer;
  }

    for(int x=0; x < answer.length(); x++) //go through answer
    {
        if(letter == answer.charAt(x)) //if the letter pressed matches a character in answer
        {
          puzzle = puzzle.substring(0,x) + letter + puzzle.substring(x+1); //substitute in letter
        }

    }
</code>```

If more code is needed for understanding, I can post it. I'd be happy for a few pointers :D

Edit:

Thanks for all help guys, but I haven't been successful in understanding the second part yet.

Right now, I can get the textfield to show, but the problem lies with accepting a certain character length.  It has to be the exact same length as another string, no more, no less.

I have tried implementing it with the links you guys gave but only ended up getting confused (sorry). Can someone please offer a specific example?

Edit:

Resolved after using validate() and adding guess.setActionCommand("1").

答:
Use InputVerifier to validate your text input

Refer below example :

```<code>import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JTextField;

class PassVerifier extends InputVerifier {

    public boolean verify(JComponent input) {
        JTextField tf = (JTextField) input;

        String text = tf.getText();

        // do your  validation
//        if (text.equals(answer)) //if the guess is the answer
//        {
//            puzzle = answer;
//        }
//        for (int x = 0; x < answer.length(); x++) //go through answer
//        {
//            if (letter == answer.charAt(x)) //if the letter pressed matches a character in answer
//            {
//                puzzle = puzzle.substring(0, x) + letter + puzzle.substring(x + 1); //substitute in letter
//            }
//        }
        return true; // return true or false according to validation
    }
}
</code>```

Set to InputVerifier to your JTextField

```<code> JTextField tf1 = new JTextField ("Type \"pass\" here");
 tf1.setInputVerifier(new PassVerifier());
</code>```

Body:
I had posted a similar question before but it got deleted by accident.

My JTextField is supposed to appear after clicking a button which it does but only after minimizing the window. Another problem with it is that it accepts single characters when it's supposed to accept a phrase of only a certain length.

Here's a bit of the code since it's so long:

 static String answer = "MY PUZZLE", puzzle = "M- -U----";

  //inside constructor
  guess = new JTextField("Write in Caps");
  guess.setVisible(false);
  guess.addActionListener(this);
  board.add(guess);

  //actionperformed
  guess.setVisible(true);
  gueStr = guess.getText();

  if (gueStr.length() != answer.length()) //if it is not the same length
  {
    gueStr = "";
  }

the String "puzzle" is changed if a letter button (code not shown here) that is a character from the "answer" String is pressed or if the user's guess is the same phrase as the answer String

  if ( gueStr.equals(answer)) //if the guess is the answer
  {
    puzzle = answer;
  }

    for(int x=0; x < answer.length(); x++) //go through answer
    {
        if(letter == answer.charAt(x)) //if the letter pressed matches a character in answer
        {
          puzzle = puzzle.substring(0,x) + letter + puzzle.substring(x+1); //substitute in letter
        }

    }

If more code is needed for understanding, I can post it. I'd be happy for a few pointers :D

Edit:

Thanks for all help guys, but I haven't been successful in understanding the second part yet.

Right now, I can get the textfield to show, but the problem lies with accepting a certain character length.  It has to be the exact same length as another string, no more, no less.

I have tried implementing it with the links you guys gave but only ended up getting confused (sorry). Can someone please offer a specific example?

Edit:

Resolved after using validate() and adding guess.setActionCommand("1").

Body:
Use InputVerifier to validate your text input

Refer below example :

import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JTextField;

class PassVerifier extends InputVerifier {

    public boolean verify(JComponent input) {
        JTextField tf = (JTextField) input;

        String text = tf.getText();

        // do your  validation
//        if (text.equals(answer)) //if the guess is the answer
//        {
//            puzzle = answer;
//        }
//        for (int x = 0; x < answer.length(); x++) //go through answer
//        {
//            if (letter == answer.charAt(x)) //if the letter pressed matches a character in answer
//            {
//                puzzle = puzzle.substring(0, x) + letter + puzzle.substring(x + 1); //substitute in letter
//            }
//        }
        return true; // return true or false according to validation
    }
}

Set to InputVerifier to your JTextField

 JTextField tf1 = new JTextField ("Type \"pass\" here");
 tf1.setInputVerifier(new PassVerifier());


问:
Angular select does not populate options
I am trying to learn nodejs. I have a simple application where I have defined an array options in app.component.ts

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  options = ["Option1", "Option2"];
}
</code>```

and I am trying to expose the options as dropdown app.component.html

```<code><div style="text-align:center">
  <h1>
    {{options}}!
    <select name="repeatSelect" id="repeatSelect" ng-model="app-root">
      <option ng-repeat="option in options" value="{{option}}">{{option}}</option>
    </select>
  </h1>
</code>```

For some reason the selectbox is not getting populated. If I print the options I can clearly see that it print fine.
Here is the screenshot

答:
You should use *ngFor . Because you are using angular 4. There is no ng-repeat directive in angular 2/4/5. </p>

```<code><option *ngFor="let option of options" value="{{option}}">{{option}}</option>
</code>```

Body:
I am trying to learn nodejs. I have a simple application where I have defined an array options in app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  options = ["Option1", "Option2"];
}

and I am trying to expose the options as dropdown app.component.html

    {{options}}!
    <select name="repeatSelect" id="repeatSelect" ng-model="app-root">
      <option ng-repeat="option in options" value="{{option}}">{{option}}</option>
    </select>

For some reason the selectbox is not getting populated. If I print the options I can clearly see that it print fine.
Here is the screenshot

Body:
You should use *ngFor . Because you are using angular 4. There is no ng-repeat directive in angular 2/4/5.

<option *ngFor="let option of options" value="{{option}}">{{option}}</option>


问:
How do I 'sleep' python without pausing entire script
I'm fairly new to python and am trying to make a basic stopwatch script. I want to be able to pause the stopwatch, but the time.sleep(1) code which waits for the next number to be shown interferes with the keyboard event. BTW I'm using the python package 'keyboard' to get the event. I have tried threading but I can't pause the other thread as far as I know.

Here's my code:

```<code>import time, keyboard, sys

print('Stopwatch \n')
input('Press enter to start:')

def counter():
    stopwatch = 0
    while True:
        time.sleep(1)
        stopwatch += 1
        print(stopwatch)
        question()

def question():
    while True:
        if keyboard.is_pressed('p'):
            print('\nPaused')
            input('Press enter to resume:')
        if keyboard.is_pressed('s'):
            print('\nStopped')
            sys.exit()

counter()
</code>```

I don't necessarily need the question function, but was experimenting to see if I could get it to work. I could combine the two functions.

答:
I've got some good news and some bad news. The bad news is that you can't do what you're trying to do the way you're trying to do it, for exactly the problem you're now facing. Python doesn't have a way of just pausing the execution of one function, it's all or nothing. You can solve this by implementing through multiprocessing or threading, but you're really just opening a can of worms to get into that before you're ready.

The good news is that you don't need to do all that. You're trying to find the difference between a start time and an end time, right? Let's boil it down to basics and do that.

```<code>import datetime

start = datetime.datetime.now()
input("Press enter to stop.")
stop = datetime.datetime.now()
result = (stop - start).total_seconds()
</code>```

You can implement pausing by waiting for other actions (in a while True loop as you've done above), getting the difference in seconds between start and stop and adding it to a running total.

Body:
I'm fairly new to python and am trying to make a basic stopwatch script. I want to be able to pause the stopwatch, but the time.sleep(1) code which waits for the next number to be shown interferes with the keyboard event. BTW I'm using the python package 'keyboard' to get the event. I have tried threading but I can't pause the other thread as far as I know.

Here's my code:

import time, keyboard, sys

print('Stopwatch \n')
input('Press enter to start:')

def counter():
    stopwatch = 0
    while True:
        time.sleep(1)
        stopwatch += 1
        print(stopwatch)
        question()

def question():
    while True:
        if keyboard.is_pressed('p'):
            print('\nPaused')
            input('Press enter to resume:')
        if keyboard.is_pressed('s'):
            print('\nStopped')
            sys.exit()

counter()

I don't necessarily need the question function, but was experimenting to see if I could get it to work. I could combine the two functions.

Body:
I've got some good news and some bad news. The bad news is that you can't do what you're trying to do the way you're trying to do it, for exactly the problem you're now facing. Python doesn't have a way of just pausing the execution of one function, it's all or nothing. You can solve this by implementing through multiprocessing or threading, but you're really just opening a can of worms to get into that before you're ready.

The good news is that you don't need to do all that. You're trying to find the difference between a start time and an end time, right? Let's boil it down to basics and do that.

import datetime

start = datetime.datetime.now()
input("Press enter to stop.")
stop = datetime.datetime.now()
result = (stop - start).total_seconds()

You can implement pausing by waiting for other actions (in a while True loop as you've done above), getting the difference in seconds between start and stop and adding it to a running total.


问:
error: command 'c++' failed with exit status 1
So I am trying to install Pyv8 by following instruction from https://andrewwilkinson.wordpress.com/2012/01/23/integrating-python-and-javascript-with-pyv8/

```<code>
    sudo aptitude install scons libboost-python-dev
    svn checkout http://v8.googlecode.com/svn/trunk/ v8
    svn checkout http://pyv8.googlecode.com/svn/trunk/ pyv8
    cd v8
    export PyV8=`pwd`
    cd ../pyv8
    python setup.py build
    sudo python setup.py install
</code>```

Error comes when running second last command about building the setup.

```<code>
    -Wstrict-prototypes -fPIC -DBOOST_PYTHON_STATIC_LIB -
    DV8_NATIVE_REGEXP -DENABLE_DEBUGGER_SUPPORT -DV8_TARGET_ARCH_X64 -
    I/home/amit/Downloads/pyv8/build/v8_r19632/include -
    I/home/amit/Downloads/pyv8/build/v8_r19632 -
    I/home/amit/Downloads/pyv8/build/v8_r19632/src -I/usr/local/include -
    I/usr/include/python2.7 -c src/PyV8.cpp -o build/temp.linux-x86_64-
    2.7/src/PyV8.o -Wno-write-strings -g -O3
    cc1plus: warning: command line option ‘-Wstrict-prototypes’ is valid for
    C/ObjC but not for C++ [enabled by default]
    c++ -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-
    functions -Wl,-z,relro -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall
    -Wstrict-prototypes -D_FORTIFY_SOURCE=2 -g -fstack-protector --param=ssp-
    buffer-size=4 -Wformat -Werror=format-security build/temp.linux-x86_64-
    2.7/src/Utils.o build/temp.linux-x86_64-2.7/src/Exception.o
    build/temp.linux-x86_64-2.7/src/Context.o build/temp.linux-x86_64-
    2.7/src/Engine.o build/temp.linux-x86_64-2.7/src/Wrapper.o
    build/temp.linux-x86_64-2.7/src/Debug.o build/temp.linux-x86_64-
    2.7/src/Locker.o build/temp.linux-x86_64-2.7/src/AST.o     build/temp.linux-
    x86_64-2.7/src/PrettyPrinter.o build/temp.linux-x86_64-2.7/src/PyV8.o
    L/usr/local/lib -
    L/home/amit/Downloads/pyv8/build/v8_r19632/out/x64.release/obj.target/tool
    s/gyp/ -lboost_python -lboost_thread -lboost_system -lrt -lv8_base.x64 -
    lv8_snapshot -o build/lib.linux-x86_64-2.7/_PyV8.so -fPIC -lrt
    /usr/bin/ld: cannot find -lboost_thread
    /usr/bin/ld: cannot find -lboost_system
    collect2: error: ld returned 1 exit status

    error: command 'c++' failed with exit status 1
</code>```

答:
It is because the version of gcc and g++ is too low for me, as I downgrade it when i install cuda sometime. Just follow the following commands:

```<code>$ cd /usr/bin
$  rm gcc
$ ln -s gcc-5 gcc
$ rm g++
$ ln -s g++-5 g++
</code>```

Done.

Body:
So I am trying to install Pyv8 by following instruction from https://andrewwilkinson.wordpress.com/2012/01/23/integrating-python-and-javascript-with-pyv8/

    sudo aptitude install scons libboost-python-dev
    svn checkout http://v8.googlecode.com/svn/trunk/ v8
    svn checkout http://pyv8.googlecode.com/svn/trunk/ pyv8
    cd v8
    export PyV8=`pwd`
    cd ../pyv8
    python setup.py build
    sudo python setup.py install

Error comes when running second last command about building the setup.

    -Wstrict-prototypes -fPIC -DBOOST_PYTHON_STATIC_LIB -
    DV8_NATIVE_REGEXP -DENABLE_DEBUGGER_SUPPORT -DV8_TARGET_ARCH_X64 -
    I/home/amit/Downloads/pyv8/build/v8_r19632/include -
    I/home/amit/Downloads/pyv8/build/v8_r19632 -
    I/home/amit/Downloads/pyv8/build/v8_r19632/src -I/usr/local/include -
    I/usr/include/python2.7 -c src/PyV8.cpp -o build/temp.linux-x86_64-
    2.7/src/PyV8.o -Wno-write-strings -g -O3
    cc1plus: warning: command line option ‘-Wstrict-prototypes’ is valid for
    C/ObjC but not for C++ [enabled by default]
    c++ -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-
    functions -Wl,-z,relro -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall
    -Wstrict-prototypes -D_FORTIFY_SOURCE=2 -g -fstack-protector --param=ssp-
    buffer-size=4 -Wformat -Werror=format-security build/temp.linux-x86_64-
    2.7/src/Utils.o build/temp.linux-x86_64-2.7/src/Exception.o
    build/temp.linux-x86_64-2.7/src/Context.o build/temp.linux-x86_64-
    2.7/src/Engine.o build/temp.linux-x86_64-2.7/src/Wrapper.o
    build/temp.linux-x86_64-2.7/src/Debug.o build/temp.linux-x86_64-
    2.7/src/Locker.o build/temp.linux-x86_64-2.7/src/AST.o     build/temp.linux-
    x86_64-2.7/src/PrettyPrinter.o build/temp.linux-x86_64-2.7/src/PyV8.o
    L/usr/local/lib -
    L/home/amit/Downloads/pyv8/build/v8_r19632/out/x64.release/obj.target/tool
    s/gyp/ -lboost_python -lboost_thread -lboost_system -lrt -lv8_base.x64 -
    lv8_snapshot -o build/lib.linux-x86_64-2.7/_PyV8.so -fPIC -lrt
    /usr/bin/ld: cannot find -lboost_thread
    /usr/bin/ld: cannot find -lboost_system
    collect2: error: ld returned 1 exit status

    error: command 'c++' failed with exit status 1

Body:
It is because the version of gcc and g++ is too low for me, as I downgrade it when i install cuda sometime. Just follow the following commands:

$ cd /usr/bin
$  rm gcc
$ ln -s gcc-5 gcc
$ rm g++
$ ln -s g++-5 g++

Done.


问:
Order by joined table through table
my mySQL (pun intended) is a bit rusty. I am trying to join a table through another table.

```<code>carparks has many clients
clients has many cars
</code>```

This is the query

```<code>select `carparks`.* from `carparks`

left join `clients` on `carparks`.`carpark_id` = `clients`.`carpark_id`

left join `cars` on `clients`.`client_id` = `cars`.`client_id`

where `carparks`.`carpark_id` in (1, 3, 8, 33, 34, 38, 39)

order by `cars`.`created_at` desc
</code>```

As you can see I am trying to order by the created_at column of cars, the above query though returns duplicated carparks for each of the cars within the carpark.

What I am looking at is to return only those carparks with the ids in the WHERE IN clause, simply ordered by the created_at column of the cars table.

Thanks

答:
Reduce the wanted dates to one per carpark before joining back to carparks. Note if a carpark does have no cars than a left join is logical, however I expect every carpark (that is open for business) will have cars, so that left join might not be needed.</p>

```<code>SELECT `carparks`.*
FROM `carparks`
LEFT JOIN (
       SELECT
              `carparks`.`carpark_id`
            , max(`cars`.`created_at`) max_car_created
       FROM `clients`
       INNER JOIN `cars` ON `clients`.`client_id` = `cars`.`client_id`
       GROUP BY
              `carparks`.`carpark_id`
       ) d ON `carparks`.`carpark_id` = d.`carpark_id`
WHERE `carparks`.`carpark_id` IN (1, 3, 8, 33, 34, 38, 39)
ORDER BY max_car_created DESC
</code>```

Title: Order by joined table through table

Body:
my mySQL (pun intended) is a bit rusty. I am trying to join a table through another table.

carparks has many clients
clients has many cars

This is the query

select `carparks`.* from `carparks`

left join `clients` on `carparks`.`carpark_id` = `clients`.`carpark_id`

left join `cars` on `clients`.`client_id` = `cars`.`client_id`

where `carparks`.`carpark_id` in (1, 3, 8, 33, 34, 38, 39)

order by `cars`.`created_at` desc

As you can see I am trying to order by the created_at column of cars, the above query though returns duplicated carparks for each of the cars within the carpark.

What I am looking at is to return only those carparks with the ids in the WHERE IN clause, simply ordered by the created_at column of the cars table.

Thanks

Body:
Reduce the wanted dates to one per carpark before joining back to carparks. Note if a carpark does have no cars than a left join is logical, however I expect every carpark (that is open for business) will have cars, so that left join might not be needed.

SELECT `carparks`.*
FROM `carparks`
LEFT JOIN (
       SELECT
              `carparks`.`carpark_id`
            , max(`cars`.`created_at`) max_car_created
       FROM `clients`
       INNER JOIN `cars` ON `clients`.`client_id` = `cars`.`client_id`
       GROUP BY
              `carparks`.`carpark_id`
       ) d ON `carparks`.`carpark_id` = d.`carpark_id`
WHERE `carparks`.`carpark_id` IN (1, 3, 8, 33, 34, 38, 39)
ORDER BY max_car_created DESC


问:
Insert and select data in sql server
I want to insert data from table sp_test with two columns; (empid and amount) into another table sp_emp (regisno,empid,itemid,year,month,week,amount,paymentdate).

This is the query I used

```<code>Insert into sp_emp(regisno,empid,itemid,year,month,week,amount,paymentdate)
Select * from sp_test
</code>```

and it returned as select list for insert statement has fewer items. How should I put the values for another column?

答:
The the columns list of the insert clause must be equal to the columns list of the select clause (both number of columns and data types).

If your sp_emp columns allows null values, you can specify NULL as values. If your columns have default values, you can set them by using the keyword DEFAULT as the value:

```<code>Insert into sp_emp(regisno,empid,itemid,year,month,week,amount,paymentdate)
SELECT DEFAULT,EmpID,NULL,NULL,NULL,NULL,Amount,NULL
FROM sp_test
</code>```

However, a better option would be to simply omit these columns from the insert clause columns list - This will create a much simpler statement.

```<code>Insert into sp_emp(empid,amount)
SELECT EmpID,Amount
FROM sp_test
</code>```

Also, as a side note, you should not use the prefix sp_ for anything in your database. If anything, sp_ is naturally used with stored procedures - but Microsoft uses this prefix for the system stored procedures in SQL Server.

Title: Insert and select data in sql server

Body:
I want to insert data from table sp_test with two columns; (empid and amount) into another table sp_emp (regisno,empid,itemid,year,month,week,amount,paymentdate).

This is the query I used

Insert into sp_emp(regisno,empid,itemid,year,month,week,amount,paymentdate)
Select * from sp_test

and it returned as select list for insert statement has fewer items. How should I put the values for another column?

Body:
The the columns list of the insert clause must be equal to the columns list of the select clause (both number of columns and data types).

If your sp_emp columns allows null values, you can specify NULL as values. If your columns have default values, you can set them by using the keyword DEFAULT as the value:

Insert into sp_emp(regisno,empid,itemid,year,month,week,amount,paymentdate)
SELECT DEFAULT,EmpID,NULL,NULL,NULL,NULL,Amount,NULL
FROM sp_test

However, a better option would be to simply omit these columns from the insert clause columns list - This will create a much simpler statement.

Insert into sp_emp(empid,amount)
SELECT EmpID,Amount
FROM sp_test

Also, as a side note, you should not use the prefix sp_ for anything in your database. If anything, sp_ is naturally used with stored procedures - but Microsoft uses this prefix for the system stored procedures in SQL Server.


问:
Create new column in pandas dataframe based on if/elif/and functions
I have searched for my exact issue to no avail. These two threads Creating a new column based on if-elif-else condition and
create new pandas dataframe column based on if-else condition with a lookup guided my code though my code fails to execute.

Issues: I have a dataframe which I have example-reproduced below. Region attribute has two values only - a or b (or could have more), same for year, though region a could have both years etc. What I want to do is create a new column, "dollars", and look up the value for region, and if it is region "a" AND year is e.g 2006, takes sales in that row, and multiply with rate for that year and append value in new column - dollars. I am beginner and below is what I have so far - via function - and obviously executing the .apply function returns a ValueError: ('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', 'occurred at index 0'). I am particularly interested in a more efficient implementation as the dataframe is rather large and would love to optimize computational efficiency.

```<code>import pandas as np

rate_2006, rate_2007 = 100, 200

c = {
'region': ["a", "a", "a", "a", "a", "b", "b", "b", "b", "a", "b"],
'year': [2006, 2007, 2007, 2006, 2006, 2006, 2007, 2007, 2007, 2006, 2007],
'sales': [500, 100, 2990, 15, 5000, 2000, 150, 300, 250, 1005, 600]
}

df1 = pd.DataFrame(c)
df1

def new_col(row):
    if df1["region"] == "a" and df1["year"] == 2006:
        nc = row["sales"] * rate_2006
    elif df1["region"] == "a" and df1["year"] == 2007:
        nc = row["sales"] * rate_2007
    elif df1["region"] == "b" and df1["year"] == 2006:
        nc = row["sales"] * rate_2006
    else:
        nc = row["sales"] * rate_2007
    return nc

df1["Dollars"] = df1.apply(new_col, axis=1)
df1
</code>```

答:
The issue maybe due to the way you are using it. I don't know if it will help you. but I have re written the code as per my knowledge that is working.</p>

```<code>import pandas as pd

rate_2006, rate_2007 = 100, 200

c = {
'region': ["a", "a", "a", "a", "a", "b", "b", "b", "b", "a", "b"],
'year': [2006, 2007, 2007, 2006, 2006, 2006, 2007, 2007, 2007, 2006, 2007],
'sales': [500, 100, 2990, 15, 5000, 2000, 150, 300, 250, 1005, 600]
}

df1 = pd.DataFrame(c)
print(df1)

def new_col(value):
    if df1.loc[value,"region"] == "a" and df1.loc[value,"year"] == 2006:
        df1.loc[value,"Dollars"] = df1.loc[value,"sales"] * rate_2006
    elif df1.loc[value,"region"] == "a" and df1.loc[value,"year"] == 2007:
        df1.loc[value,"Dollars"] = df1.loc[value,"sales"] * rate_2007
    elif df1.loc[value,"region"] == "b" and df1.loc[value,"year"] == 2006:
        df1.loc[value,"Dollars"] = df1.loc[value,"sales"] * rate_2006
    else:
        df1.loc[value,"Dollars"] = df1.loc[value,"sales"] * rate_2007

for value in range(len(df1)):
    new_col(value)
</code>```

Body:
I have searched for my exact issue to no avail. These two threads Creating a new column based on if-elif-else condition and
create new pandas dataframe column based on if-else condition with a lookup guided my code though my code fails to execute.

Issues: I have a dataframe which I have example-reproduced below. Region attribute has two values only - a or b (or could have more), same for year, though region a could have both years etc. What I want to do is create a new column, "dollars", and look up the value for region, and if it is region "a" AND year is e.g 2006, takes sales in that row, and multiply with rate for that year and append value in new column - dollars. I am beginner and below is what I have so far - via function - and obviously executing the .apply function returns a ValueError: ('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', 'occurred at index 0'). I am particularly interested in a more efficient implementation as the dataframe is rather large and would love to optimize computational efficiency.

import pandas as np

rate_2006, rate_2007 = 100, 200

c = {
'region': ["a", "a", "a", "a", "a", "b", "b", "b", "b", "a", "b"],
'year': [2006, 2007, 2007, 2006, 2006, 2006, 2007, 2007, 2007, 2006, 2007],
'sales': [500, 100, 2990, 15, 5000, 2000, 150, 300, 250, 1005, 600]
}

df1 = pd.DataFrame(c)
df1

def new_col(row):
    if df1["region"] == "a" and df1["year"] == 2006:
        nc = row["sales"] * rate_2006
    elif df1["region"] == "a" and df1["year"] == 2007:
        nc = row["sales"] * rate_2007
    elif df1["region"] == "b" and df1["year"] == 2006:
        nc = row["sales"] * rate_2006
    else:
        nc = row["sales"] * rate_2007
    return nc

df1["Dollars"] = df1.apply(new_col, axis=1)
df1

Body:
The issue maybe due to the way you are using it. I don't know if it will help you. but I have re written the code as per my knowledge that is working.

import pandas as pd

rate_2006, rate_2007 = 100, 200

c = {
'region': ["a", "a", "a", "a", "a", "b", "b", "b", "b", "a", "b"],
'year': [2006, 2007, 2007, 2006, 2006, 2006, 2007, 2007, 2007, 2006, 2007],
'sales': [500, 100, 2990, 15, 5000, 2000, 150, 300, 250, 1005, 600]
}

df1 = pd.DataFrame(c)
print(df1)

def new_col(value):
    if df1.loc[value,"region"] == "a" and df1.loc[value,"year"] == 2006:
        df1.loc[value,"Dollars"] = df1.loc[value,"sales"] * rate_2006
    elif df1.loc[value,"region"] == "a" and df1.loc[value,"year"] == 2007:
        df1.loc[value,"Dollars"] = df1.loc[value,"sales"] * rate_2007
    elif df1.loc[value,"region"] == "b" and df1.loc[value,"year"] == 2006:
        df1.loc[value,"Dollars"] = df1.loc[value,"sales"] * rate_2006
    else:
        df1.loc[value,"Dollars"] = df1.loc[value,"sales"] * rate_2007

for value in range(len(df1)):
    new_col(value)


问:
Mysql : dump database along data
I want to dump my database along the table schema and the table data also using the unix command line .

I used .

```<code>mysqldump -d -u root  -p frontend > frontend.sql
</code>```

But above command is dumping only schema not the data from the database .

Please help me out how can i dump the database along the data also.

答:
To restore database from .sql dumpfile

mysql -u [yourusername] -p [password] [nameofthedatabase] <
  /pathtoyoursqldumpfile.sql

Use mysqldump to create backup from database.

mysqldump -u [yourusername] -p [password] [nameofthedatabase] >
  /pathtoyoursqldumpfile.sql

Title: Mysql : dump database along data

Body:
I want to dump my database along the table schema and the table data also using the unix command line .

I used .

mysqldump -d -u root  -p frontend > frontend.sql

But above command is dumping only schema not the data from the database .

Please help me out how can i dump the database along the data also.


问:
what is the best way to test DLL functions ?
I want to test my function and flows.
Lua scripts are a way for testing, Im able to load C Lib from lua and invoke the functions. The greatest advantage of using Lua is if you want to change calling scenerio, you just have to change your lua script file and execute it.

But I want to know that are there any better way to test a DLL code?

答:
There is no such thing exist in the universe as "the best way".Citation needed

However, the generally accepted practice currently is to write automated unit tests. That is, you use a unit testing framework that allows you to express different scenarios of the consumption of the library code. You may think of tests as of a huge bunch of little programs that use the functions and classes in the library to verify their correctness, except that you don't actually write main functions, makefiles, printing and all the boring stuff is handled for you. Tests can pass or fail individually. Usually you can give names to them and organize into blocks. When test fails, a framework typically explain where and why, reducing the time and effort required for the debugging.

Unit tests are frequently built and ran automatically, e.g. by the IDE or a watch script after rebuilding your library and/or by a continuous integration system after a commit into a version control system.

Generally you write tests in the same language as your library (it's just simpler), but if your library is designed to interface with other languages you can of course use any or multiple of these languages as well.

There is an entire branch of programming methodology that is based on unit testing, called Test-driven development (TDD). In short, TDD instructs you to write a unit test first for a given scenario and only then the simplest library code that allows the test to pass.

Few examples of unit testing frameworks for C++ (no particular order):

Google Test

CppUnit

Boost.Test

Catch


问:
ASP.Net Core MVC Dependency Injection not working
I am trying to inject a interface into to my HomeController and I am getting this error:

InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Configuration.IConfiguration' while attempting to activate

My Startup class is as follows:

```<code>public Startup(IApplicationEnvironment appEnv)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(appEnv.ApplicationBasePath)
        .AddEnvironmentVariables()
        .AddJsonFile("appsettings.json");
    Configuration = builder.Build();
}

public IConfigurationRoot Configuration { get; set; }

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddApplicationInsightsTelemetry(Configuration);

    services.AddEntityFramework()
        .AddSqlServer()
        .AddDbContext<ApplicationDbContext>(options => options
            .UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

    services.AddMvc();
    services.AddSingleton(provider => Configuration);

    // Add application services.
    services.AddTransient<IEmailSender, AuthMessageSender>();
    services.AddTransient<ISmsSender, AuthMessageSender>();
}

public void Configure(
    IApplicationBuilder app,
    IHostingEnvironment env,
    ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseApplicationInsightsRequestTelemetry();

    if (env.IsDevelopment())
    {
        app.UseBrowserLink();
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");

        try
        {
            using (var serviceScope = app.ApplicationServices
                .GetRequiredService<IServiceScopeFactory>()
                .CreateScope())
            {
                serviceScope.ServiceProvider
                        .GetService<ApplicationDbContext>()
                        .Database.Migrate();
            }
        }
        catch { }
    }

    app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());

    app.UseApplicationInsightsExceptionTelemetry();
    app.UseStaticFiles();
    app.UseIdentity();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });

    app.Run((async (context) =>
    {
        await context.Response.WriteAsync("Error");
    }));
}
</code>```

and my HomeController constructor is:

```<code>public HomeController(IConfiguration configuration, IEmailSender mailService)
{
    _mailService = mailService;
    _to = configuration["emailAddress.Support"];
}
</code>```

Please tell me where I am mistaken.

Microsoft.Extensions.DependencyInjection.ServiceLookup.Service.PopulateCallSites(ServiceProvider provider, ISet`1 callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)

答:
In Core 2.0 it's recommended to use IConfiguration instead of IConfigurationRoot

```<code>public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; }
</code>```

from https://learn.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/#add-configuration-providers

ContentLicense: CC BY-SA 4.0

Body:
I am trying to inject a interface into to my HomeController and I am getting this error:

InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Configuration.IConfiguration' while attempting to activate

My Startup class is as follows:

public Startup(IApplicationEnvironment appEnv)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(appEnv.ApplicationBasePath)
        .AddEnvironmentVariables()
        .AddJsonFile("appsettings.json");
    Configuration = builder.Build();
}

public IConfigurationRoot Configuration { get; set; }

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddApplicationInsightsTelemetry(Configuration);

    services.AddEntityFramework()
        .AddSqlServer()
        .AddDbContext<ApplicationDbContext>(options => options
            .UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

    services.AddMvc();
    services.AddSingleton(provider => Configuration);

    // Add application services.
    services.AddTransient<IEmailSender, AuthMessageSender>();
    services.AddTransient<ISmsSender, AuthMessageSender>();
}

public void Configure(
    IApplicationBuilder app,
    IHostingEnvironment env,
    ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseApplicationInsightsRequestTelemetry();

    if (env.IsDevelopment())
    {
        app.UseBrowserLink();
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");

        try
        {
            using (var serviceScope = app.ApplicationServices
                .GetRequiredService<IServiceScopeFactory>()
                .CreateScope())
            {
                serviceScope.ServiceProvider
                        .GetService<ApplicationDbContext>()
                        .Database.Migrate();
            }
        }
        catch { }
    }

    app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());

    app.UseApplicationInsightsExceptionTelemetry();
    app.UseStaticFiles();
    app.UseIdentity();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });

    app.Run((async (context) =>
    {
        await context.Response.WriteAsync("Error");
    }));
}

and my HomeController constructor is:

public HomeController(IConfiguration configuration, IEmailSender mailService)
{
    _mailService = mailService;
    _to = configuration["emailAddress.Support"];
}

Please tell me where I am mistaken.

Microsoft.Extensions.DependencyInjection.ServiceLookup.Service.PopulateCallSites(ServiceProvider provider, ISet`1 callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)

Body:
In Core 2.0 it's recommended to use IConfiguration instead of IConfigurationRoot

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; }

from https://learn.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/#add-configuration-providers


问:
How can we make playlist repeateable continuously in AVPlayer
hi Friends
I am using AVPlayer but in it I want to play .mov file continuously repeatable.So I want to use seekToTime but cant get proper idea so please any one tell me how? </p>

答:
For iOS 10+ you can use AVPlayerLooper

Sample from Apple documentation:

```<code>let asset = // AVAsset with its 'duration' property value loaded
let playerItem = AVPlayerItem(asset: asset)

// Create a new player looper with the queue player and template item
playerLooper = AVPlayerLooper(player: queuePlayer, templateItem:playerItem)

// Begin looping playback
queuePlayer.play()
</code>```

Body:
For iOS 10+ you can use AVPlayerLooper

Sample from Apple documentation:

let asset = // AVAsset with its 'duration' property value loaded
let playerItem = AVPlayerItem(asset: asset)

// Create a new player looper with the queue player and template item
playerLooper = AVPlayerLooper(player: queuePlayer, templateItem:playerItem)

// Begin looping playback
queuePlayer.play()


问:
How can I create a new "file type" in the command line?
To create a registry entry, the reg command is used. How can I use the reg command to specify a file, for example, of type .test to automatically open with openTest.exe, and be listed as a Useless Test File under the file type details?

答:
Try this batch to Associate .test as filetype and default run program to run the .test file.

```<code>@echo off
SETLOCAL EnableDelayedExpansion
ASSOC .test=Useless Test File

set myapppath="%homedrive%\MyTestProgram\"
REG ADD "HKCR\.test\DefaultIcon" /d %myapppath%\openTest.ico
REG ADD "HKCR\.test\shell\Open\command" /d "%myapppath%\openTest.exe %%1"
</code>```

The above batch will associate ".test" and set its description as "Useless Test File"

myapppath will set your path to your application directory.(edit path as required)

Body:
Try this batch to Associate .test as filetype and default run program to run the .test file.

@echo off
SETLOCAL EnableDelayedExpansion
ASSOC .test=Useless Test File

set myapppath="%homedrive%\MyTestProgram\"
REG ADD "HKCR\.test\DefaultIcon" /d %myapppath%\openTest.ico
REG ADD "HKCR\.test\shell\Open\command" /d "%myapppath%\openTest.exe %%1"

The above batch will associate ".test" and set its description as "Useless Test File"

myapppath will set your path to your application directory.(edit path as required)


问:
Select statement on XML not returning desired output
```<code>DECLARE @barcode XML

            SET @barcode = '<BCODES><BCODE>a</BCODE><BCODE>b</BCODE><BCODE>c</BCODE><BCODE>d</BCODE></BCODES>'

            --INSERT INTO #barcode
            SELECT      v.x.value('BCODE[1]','VARCHAR(15)') AS Barcodes
            FROM        @barcode.nodes('BCODES') v(x)
</code>```

Result-->

Barcodes

a

I'm unable to get b,c and d in the output.

答:
Just do this:

```<code>SELECT v.x.value('.','VARCHAR(15)') AS Barcodes
FROM @barcode.nodes('BCODES/BCODE') v(x)
</code>```

The idea is first to get all BCODE nodes and then to extract its values.

Body:
DECLARE @barcode XML

            SET @barcode = '<BCODES><BCODE>a</BCODE><BCODE>b</BCODE><BCODE>c</BCODE><BCODE>d</BCODE></BCODES>'

            --INSERT INTO #barcode
            SELECT      v.x.value('BCODE[1]','VARCHAR(15)') AS Barcodes
            FROM        @barcode.nodes('BCODES') v(x)

Result-->

Barcodes

a

I'm unable to get b,c and d in the output.

Body:
Just do this:

SELECT v.x.value('.','VARCHAR(15)') AS Barcodes
FROM @barcode.nodes('BCODES/BCODE') v(x)

The idea is first to get all BCODE nodes and then to extract its values.


问:
How to find if 3 numbers in a set of size N exactly sum up to M
I want to know how I can implement a better solution than O(N^3). Its similar to the knapsack and subset problems. In my question N<=8000, so i started computing sums of pairs of numbers and stored them in an array. Then I would binary search in the sorted set for each (M-sum[i]) value but the problem arises how will I keep track of the indices which summed up to sum[i]. I know I could declare extra space but my Sums array already has a size of 64 million, and hence I couldn't complete my O(N^2) solution. Please advice if I can do some optimization or if I need some totally different technique.</p>

答:
You could benefit from some generic tricks to improve the performance of your algorithm.

1) Don't store what you use only once

It is a common error to store more than you really need. Whenever your memory requirement seem to blow up the first question to ask yourself is Do I really need to store that stuff ? Here it turns out that you do not (as Steve explained in comments), compute the sum of two numbers (in a triangular fashion to avoid repeating yourself) and then check for the presence of the third one.

We drop the O(N**2) memory complexity! Now expected memory is O(N).

2) Know your data structures, and in particular: the hash table

Perfect hash tables are rarely (if ever) implemented, but it is (in theory) possible to craft hash tables with O(1) insertion, check and deletion characteristics, and in practice you do approach those complexities (tough it generally comes at the cost of a high constant factor that will make you prefer so-called suboptimal approaches).

Therefore, unless you need ordering (for some reason), membership is better tested through a hash table in general.

We drop the 'log N' term in the speed complexity.

With those two recommendations you easily get what you were asking for:

Build a simple hash table: the number is the key, the index the satellite data associated

Iterate in triangle fashion over your data set: for i in [0..N-1]; for j in [i+1..N-1]

At each iteration, check if K = M - set[i] - set[j] is in the hash table, if it is, extract k = table[K] and if k != i and k != j store the triple (i,j,k) in your result.

If a single result is sufficient, you can stop iterating as soon as you get the first result, otherwise you just store all the triples.

ContentLicense: CC BY-SA 2.5


问:
String encrypted in Ruby gives: 'BadPaddingException' when decrypted in Java
I'm using the following Ruby code to encrypt a string

```<code>require 'openssl'
require 'base64'

public_key = OpenSSL::PKey::RSA.new(File.read('public_key'))

Base64.encode64(public_key.public_encrypt('Some random string that I want to encrypt.'))
</code>```

I need to pass the encrypted text in a request to the API, and on the API end, I'm getting the following error(read through the API logs):

```<code>javax.crypto.BadPaddingException: Decryption error
</code>```

Now, I have gone through numerous questions over at Stackoverflow, but given my Ruby code, what I'm doing wrong that the encrypted text can't be decrypted on the API end. Obviously, the API end is using Java.

I'm a completely noob when it comes to encryption, but through encrypting and decrypting in Ruby, I have made sure that the implementation is correct in Ruby. The problem arises when the text encrypted through Ruby language gets decrypted through Java on the API end.

答:
From Cryptography book

'PKCS1 padding adds 11 bytes to your original data.'

So you shall encrypt using buffer of size public key length - 11 and use actual public key size for decryption

For 1024 bit RSA keys, the encryption size is normally 117 and decryption buffer size is 128.

Body:
I'm using the following Ruby code to encrypt a string

require 'openssl'
require 'base64'

public_key = OpenSSL::PKey::RSA.new(File.read('public_key'))

Base64.encode64(public_key.public_encrypt('Some random string that I want to encrypt.'))

I need to pass the encrypted text in a request to the API, and on the API end, I'm getting the following error(read through the API logs):

javax.crypto.BadPaddingException: Decryption error

Now, I have gone through numerous questions over at Stackoverflow, but given my Ruby code, what I'm doing wrong that the encrypted text can't be decrypted on the API end. Obviously, the API end is using Java.

I'm a completely noob when it comes to encryption, but through encrypting and decrypting in Ruby, I have made sure that the implementation is correct in Ruby. The problem arises when the text encrypted through Ruby language gets decrypted through Java on the API end.


问:
Comparing 2 lists (nested with normal)
Compare two lists:

```<code>abc=[[a,b],[c],[x,y,z]]
pqr=[a,b,x,y,z]
</code>```

Print the matched strings.

I want the output to be like:

```<code>z=[a,b,x,y,z]
</code>```

Title: Comparing 2 lists (nested with normal)

Body:
Compare two lists:

abc=[[a,b],[c],[x,y,z]]
pqr=[a,b,x,y,z]

Print the matched strings.

I want the output to be like:

z=[a,b,x,y,z]

Body:
try below code:

abc=[['a','b'],['c'],['x','y','z']]
pqr = ['a','b','x','y','z']
z=[c for l in abc for c in l if c in pqr]

output:

['a', 'b', 'x', 'y', 'z']


问:
Stacked chart with data array in d3 js
I have try to customize my existing code of Stacked Bar graph with the help of this link
https://bl.ocks.org/mbostock/1134768.

I have done this graph with the help of given link but i have some confusion about the data points on y axis as shown below in picture

Here is my full code of Stacked bar Graph

```<code>var data = [
    {month: 'Jan',total:100 ,A: 35, B: 5, C: 10},
    {month: 'Feb',total:200 ,A: 30, B: 10, C: 20},
    {month: 'Mar',total:300 ,A: 0, B: 10, C: 20}
];

var xData = ["A", "B", "C"];

var margin = {top: 20, right: 50, bottom: 30, left: 50},
        width = 400 - margin.left - margin.right,
        height = 300 - margin.top - margin.bottom;

var x = d3.scale.ordinal()
        .rangeRoundBands([0, width], .35);

var y = d3.scale.linear()
        .rangeRound([height, 0]);

var color = d3.scale.category20();

var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom");

var yAxis = d3.svg.axis()
        .scale(y)
      .orient("left");

var svg = d3.select("#chart").append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

data.forEach(function(d) {
      xData.forEach(function(c) {
        d[c] = +d[c];}); })

var dataIntermediate = xData.map(function (c) {
    return data.map(function (d) {
        return {x: d.month, y: d[c]};});});

var dataStackLayout = d3.layout.stack()(dataIntermediate);

x.domain(dataStackLayout[0].map(function (d) {
    return d.x; }));

y.domain([0,d3.max(dataStackLayout[dataStackLayout.length - 1],
            function (d) { return d.y0 + d.y;}) ]).nice();

var layer = svg.selectAll(".stack")
        .data(dataStackLayout)
        .enter().append("g")
        .attr("class", "stack")
        .style("fill", function (d, i) {
            console.info(i, color(i));
            return color(i);});

layer.selectAll("rect")
        .data(function (d) {
            return d;})
        .enter().append("rect")
        .attr("x", function (d) {
            console.info("dx", d.x,x(d.x), x.rangeBand());
            return x(d.x);})
        .attr("y", function (d) {
            return y(d.y + d.y0);})
        .attr("height", function (d) {
            return y(d.y0) - y(d.y + d.y0); })
        .attr("width", x.rangeBand() -1);

svg.append("g")
        .attr("class", "axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);

  svg.append("g")
      .attr("class", "axis axis--y")
      .call(yAxis)
       .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end");
</code>```

As i have taken help from the given url, i have change my code which take array data as input instead of CSV file. But i think my data points(label) on y axis is not according to given data(key:total).

Any help should be appreciated.

答:
In case you are trying to add a new dataset with key "total", try to add key "total" in your xData array like following and it should be Visible on chart.</p>

```<code>var xData = ["total", "A", "B", "C"];
</code>```

Title: Stacked chart with data array in d3 js

Body:
I have try to customize my existing code of Stacked Bar graph with the help of this link
https://bl.ocks.org/mbostock/1134768.

I have done this graph with the help of given link but i have some confusion about the data points on y axis as shown below in picture

Here is my full code of Stacked bar Graph

var data = [
    {month: 'Jan',total:100 ,A: 35, B: 5, C: 10},
    {month: 'Feb',total:200 ,A: 30, B: 10, C: 20},
    {month: 'Mar',total:300 ,A: 0, B: 10, C: 20}
];

var xData = ["A", "B", "C"];

var margin = {top: 20, right: 50, bottom: 30, left: 50},
        width = 400 - margin.left - margin.right,
        height = 300 - margin.top - margin.bottom;

var x = d3.scale.ordinal()
        .rangeRoundBands([0, width], .35);

var y = d3.scale.linear()
        .rangeRound([height, 0]);

var color = d3.scale.category20();

var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom");

var yAxis = d3.svg.axis()
        .scale(y)
      .orient("left");

var svg = d3.select("#chart").append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

data.forEach(function(d) {
      xData.forEach(function(c) {
        d[c] = +d[c];}); })

var dataIntermediate = xData.map(function (c) {
    return data.map(function (d) {
        return {x: d.month, y: d[c]};});});

var dataStackLayout = d3.layout.stack()(dataIntermediate);

x.domain(dataStackLayout[0].map(function (d) {
    return d.x; }));

y.domain([0,d3.max(dataStackLayout[dataStackLayout.length - 1],
            function (d) { return d.y0 + d.y;}) ]).nice();

var layer = svg.selectAll(".stack")
        .data(dataStackLayout)
        .enter().append("g")
        .attr("class", "stack")
        .style("fill", function (d, i) {
            console.info(i, color(i));
            return color(i);});

layer.selectAll("rect")
        .data(function (d) {
            return d;})
        .enter().append("rect")
        .attr("x", function (d) {
            console.info("dx", d.x,x(d.x), x.rangeBand());
            return x(d.x);})
        .attr("y", function (d) {
            return y(d.y + d.y0);})
        .attr("height", function (d) {
            return y(d.y0) - y(d.y + d.y0); })
        .attr("width", x.rangeBand() -1);

svg.append("g")
        .attr("class", "axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);

  svg.append("g")
      .attr("class", "axis axis--y")
      .call(yAxis)
       .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end");

As i have taken help from the given url, i have change my code which take array data as input instead of CSV file. But i think my data points(label) on y axis is not according to given data(key:total).

Any help should be appreciated.

Body:
In case you are trying to add a new dataset with key "total", try to add key "total" in your xData array like following and it should be Visible on chart.

var xData = ["total", "A", "B", "C"];


问:
How to drop all contents like Tables, Packages, Indexes, Sequences, LOB all these at one time from user
I create one user name as MD. Unfortunately I copy the database from SYS to user MD using SQL developer. SO that lots of Tables, Indexes, Sequences, Objects and lot more has been copied. I want to delete all these at one time. How it is possible, While i tried to delete but not all has to be deleted.

答:
If you have grant to 'DROP USER', You can drop MD user with this command:

```<code>DROP USER MD CASCADE;
</code>```

and create MD user again.

Otherwise, You can make drop commands with following select:

```<code>SELECT 'DROP ' || T.OBJECT_TYPE || ' ' || T.OBJECT_NAME || ';' || CHR(10) COMMANDS
FROM USER_OBJECTS T
WHERE T.OBJECT_TYPE IN ('TABLE', 'VIEW', 'PACKAGE', 'PACKAGE BODY', 'TRIGGER');
</code>```

You can add or remove object types in where clause.

Body:
If you have grant to 'DROP USER', You can drop MD user with this command:

DROP USER MD CASCADE;

and create MD user again.

Otherwise, You can make drop commands with following select:

SELECT 'DROP ' || T.OBJECT_TYPE || ' ' || T.OBJECT_NAME || ';' || CHR(10) COMMANDS
FROM USER_OBJECTS T
WHERE T.OBJECT_TYPE IN ('TABLE', 'VIEW', 'PACKAGE', 'PACKAGE BODY', 'TRIGGER');

You can add or remove object types in where clause.


问:
< followed by space or not in regex
I have a multi-line textbox, if I enter below string:

```<code>index a<3

2<x
</code>```

By using regex I need to add space after character '<' if there is no space.
And if already have space after character '<' then keep as it is don't add additional space.

Expected result should be:

```<code>index a< 3

2< x
</code>```

I tried (?<=<)(?!$) and <[^\s]+  these but giving syntax error, when used inside Javascript.

I can use them in back end(C#) but I don't want to put server request for it, as it not a good option.

答:
See the following approach without regex (ok, only little bit of regex used in split)

document.querySelector( "textarea" ).addEventListener( "blur", function(){
  var value = this.value;
  //console.log( value );
  this.value = value.split( /\n|\r/ ).map( function(item){
    //console.log( item, item.split( /<|<\s/ ) );
    return item.split( /<\s|</ ).join( "< " );
  }).join( "\n" );
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Focus out of the below textarea to see the space added
<textarea>
index a<3
index a<3
</textarea></code>```

Title: < followed by space or not in regex

Body:
I have a multi-line textbox, if I enter below string:

index a<3

2<x

By using regex I need to add space after character '<' if there is no space.
And if already have space after character '<' then keep as it is don't add additional space.

Expected result should be:

index a< 3

2< x

I tried (?<=<)(?!$) and <[^\s]+  these but giving syntax error, when used inside Javascript.

I can use them in back end(C#) but I don't want to put server request for it, as it not a good option.

Body:
See the following approach without regex (ok, only little bit of regex used in split)

document.querySelector( "textarea" ).addEventListener( "blur", function(){
  var value = this.value;
  //console.log( value );
  this.value = value.split( /\n|\r/ ).map( function(item){
    //console.log( item, item.split( /<|<\s/ ) );
    return item.split( /<\s|</ ).join( "< " );
  }).join( "\n" );
})

Focus out of the below textarea to see the space added
<textarea>
index a<3
index a<3
</textarea>


问:
F# - JSON Type Provider - Literal String
I have an interesting problem using the F# Type Provider. Using the following sample json to generate the required type works beautifully but with one glaring issue - one of the values is a literal string ("235") but that string does not occur in the real data - each new record has a different three-digit number:

```<code>{
"record": {
    "235": {
        "Id": "001",
        "Name": "A. N. Other",
        "IdDatetime": "2017-11-11T13:10:00+00:00"
        ...
    }
    "255": {
        "Id": "005",
        "Name": "D. Other",
        "IdDatetime": "2017-11-11T13:10:00+00:00"
        ...
    }
}
</code>```

So, unfortunately, I cannot access the Id, Name, and IdDateTime fields without knowing the three-digit code in advance!

Any advice?

答:
Do you have to use the JsonProvider? There is a simpler JsonParser in FSharp.Data that allows easier access to more dynamic data. After that it's just a simple exercise to destructure it to get to the inner part.

```<code>#r @"../packages/FSharp.Data/lib/net40/FSharp.Data.dll"

open FSharp.Data
open FSharp.Data.JsonExtensions

[<Literal>]
let jsonText = """
{
"record": {
    "235": {
        "Id": "001",
        "Name": "A. N. Other",
        "IdDatetime": "2017-11-11T13:10:00+00:00"
        }
    }
}
"""

let json1 = JsonValue.Parse(jsonText)
let json2 = json1?record

let json3 =
    match json2 with
        | JsonValue.Record x -> x

let json4 =
    match json3 with
    [|(_,x)|] -> x
</code>```

val json4 : JsonValue =   {   "Id": "001",   "Name": "A. N. Other",

  "IdDatetime": "2017-11-11T13:10:00+00:00" }

Edit

On an array of jsonvalues this works the same, except you have to map the matching function over. For example:

```<code>let jsonText2 = """
{
"record": {
    "235": {
        "Id": "001",
        "Name": "A. N. Other",
        "IdDatetime": "2017-11-11T13:10:00+00:00"
    },
    "255": {
        "Id": "005",
        "Name": "D. Other",
        "IdDatetime": "2017-11-11T13:10:00+00:00"
    }
  }
}
"""

let json1 = JsonValue.Parse(jsonText2)
let json2 = json1?record

let json3 =
    match json2 with
        | JsonValue.Record x -> x

let json4 =
json3
|> Array.map (function _,x -> x)
</code>```

val json4 : JsonValue [] =   [|{   "Id": "001",   "Name": "A. N.
  Other",   "IdDatetime": "2017-11-11T13:10:00+00:00" };
      {   "Id": "005",   "Name": "D. Other",   "IdDatetime": "2017-11-11T13:10:00+00:00" }|]

Body:
I have an interesting problem using the F# Type Provider. Using the following sample json to generate the required type works beautifully but with one glaring issue - one of the values is a literal string ("235") but that string does not occur in the real data - each new record has a different three-digit number:

{
"record": {
    "235": {
        "Id": "001",
        "Name": "A. N. Other",
        "IdDatetime": "2017-11-11T13:10:00+00:00"
        ...
    }
    "255": {
        "Id": "005",
        "Name": "D. Other",
        "IdDatetime": "2017-11-11T13:10:00+00:00"
        ...
    }
}

So, unfortunately, I cannot access the Id, Name, and IdDateTime fields without knowing the three-digit code in advance!

Any advice?

Body:
Do you have to use the JsonProvider? There is a simpler JsonParser in FSharp.Data that allows easier access to more dynamic data. After that it's just a simple exercise to destructure it to get to the inner part.

#r @"../packages/FSharp.Data/lib/net40/FSharp.Data.dll"

open FSharp.Data
open FSharp.Data.JsonExtensions

[<Literal>]
let jsonText = """
{
"record": {
    "235": {
        "Id": "001",
        "Name": "A. N. Other",
        "IdDatetime": "2017-11-11T13:10:00+00:00"
        }
    }
}
"""

let json1 = JsonValue.Parse(jsonText)
let json2 = json1?record

let json3 =
    match json2 with
        | JsonValue.Record x -> x

let json4 =
    match json3 with
    [|(_,x)|] -> x

val json4 : JsonValue =   {   "Id": "001",   "Name": "A. N. Other",

  "IdDatetime": "2017-11-11T13:10:00+00:00" }

Edit

On an array of jsonvalues this works the same, except you have to map the matching function over. For example:

let jsonText2 = """
{
"record": {
    "235": {
        "Id": "001",
        "Name": "A. N. Other",
        "IdDatetime": "2017-11-11T13:10:00+00:00"
    },
    "255": {
        "Id": "005",
        "Name": "D. Other",
        "IdDatetime": "2017-11-11T13:10:00+00:00"
    }
  }
}
"""

let json1 = JsonValue.Parse(jsonText2)
let json2 = json1?record

let json3 =
    match json2 with
        | JsonValue.Record x -> x

let json4 =
json3
|> Array.map (function _,x -> x)

val json4 : JsonValue [] =   [|{   "Id": "001",   "Name": "A. N.
  Other",   "IdDatetime": "2017-11-11T13:10:00+00:00" };
      {   "Id": "005",   "Name": "D. Other",   "IdDatetime": "2017-11-11T13:10:00+00:00" }|]


问:
Testing firebase HTTPS call with CORS
I am trying to setup a local testing environment for my firebase cloud functions. However I run into problems when trying to do a fake call to one of my HTTP functions.

The reason for my error seems to be that I am using CORS (npm). When I remove cors and run the function "test" seen below with just a response.status(200) everything works. But when wrapping with cors(req,res) my test fails with TypeError: Cannot read property 'origin' of undefined.

What am I doing wrong here?

In index.js -->

```<code>exports.test = functions.https.onRequest((request, response) => {

cors(request, response, () => {
    response.status(200);
    response.send("test ok");
})
</code>```

In my test.js

```<code>describe('Cloud Functions', () => {
    // [START stubConfig]
    var myFunctions, configStub, adminInitStub, functions, admin, cors;

    before(() => {
        // Since index.js makes calls to functions.config and admin.initializeApp at the top of the file,
        // we need to stub both of these functions before requiring index.js. This is because the
        // functions will be executed as a part of the require process.
        // Here we stub admin.initializeApp to be a dummy function that doesn't do anything.
        admin = require('firebase-admin');
        cors = require('cors')({
            origin: true
        });
        adminInitStub = sinon.stub(admin, 'initializeApp');
        // Next we stub functions.config(). Normally config values are loaded from Cloud Runtime Config;
        // here we'll just provide some fake values for firebase.databaseURL and firebase.storageBucket
        // so that an error is not thrown during admin.initializeApp's parameter check
        functions = require('firebase-functions');
        configStub = sinon.stub(functions, 'config').returns({
            firebase: {
                databaseURL: 'https://not-a-project.firebaseio.com',
                storageBucket: 'not-a-project.appspot.com',
            }
            // You can stub any other config values needed by your functions here, for example:
            // foo: 'bar'
        });
        // Now we can require index.js and save the exports inside a namespace called myFunctions.
        // This includes our cloud functions, which can now be accessed at myFunctions.makeUppercase
        // and myFunctions.addMessage
        myFunctions = require('../index');
    });

    after(() => {
        // Restoring our stubs to the original methods.
        configStub.restore();
        adminInitStub.restore();
    });
    // [END stubConfig]

        describe('test', () => {
            it('should return status code 200', (done) => {

                // [START invokeHTTPS]
                // A fake request object, with req.query.text set to 'input'
                const req = {};
                // A fake response object, with a stubbed redirect function which asserts that it is called
                // with parameters 303, 'new_ref'.
                const res = {
                    status: (status) => {
                        assert.equal(status, 200);
                        done();
                    }
                };

                // Invoke addMessage with our fake request and response objects. This will cause the
                // assertions in the response object to be evaluated.
                myFunctions.test(req, res);
                // [END invokeHTTPS]

            })
        })

})
</code>```

答:
Here's how I got around the cors errors, with sinon

```<code>const res = {};

Object.assign(res, {
  status: sinon.stub().returns(res),
  end: sinon.stub().returns(res),
  json: sinon.stub().returns(res),
  setHeader: sinon.stub(),
  getHeader: sinon.stub(),
});

beforeEach(() => {
  Object.values(res).forEach(stub => stub.resetHistory());
});
</code>```

Then, in your test, you can test your responses:

```<code>    cloudFunctions.testFunction({ query: { text: 'foo' } }, res);
    response = res.json.lastCall.args[0];
</code>```

Title: Testing firebase HTTPS call with CORS

Body:
I am trying to setup a local testing environment for my firebase cloud functions. However I run into problems when trying to do a fake call to one of my HTTP functions.

The reason for my error seems to be that I am using CORS (npm). When I remove cors and run the function "test" seen below with just a response.status(200) everything works. But when wrapping with cors(req,res) my test fails with TypeError: Cannot read property 'origin' of undefined.

What am I doing wrong here?

In index.js -->

exports.test = functions.https.onRequest((request, response) => {

cors(request, response, () => {
    response.status(200);
    response.send("test ok");
})

In my test.js

describe('Cloud Functions', () => {
    // [START stubConfig]
    var myFunctions, configStub, adminInitStub, functions, admin, cors;

    before(() => {
        // Since index.js makes calls to functions.config and admin.initializeApp at the top of the file,
        // we need to stub both of these functions before requiring index.js. This is because the
        // functions will be executed as a part of the require process.
        // Here we stub admin.initializeApp to be a dummy function that doesn't do anything.
        admin = require('firebase-admin');
        cors = require('cors')({
            origin: true
        });
        adminInitStub = sinon.stub(admin, 'initializeApp');
        // Next we stub functions.config(). Normally config values are loaded from Cloud Runtime Config;
        // here we'll just provide some fake values for firebase.databaseURL and firebase.storageBucket
        // so that an error is not thrown during admin.initializeApp's parameter check
        functions = require('firebase-functions');
        configStub = sinon.stub(functions, 'config').returns({
            firebase: {
                databaseURL: 'https://not-a-project.firebaseio.com',
                storageBucket: 'not-a-project.appspot.com',
            }
            // You can stub any other config values needed by your functions here, for example:
            // foo: 'bar'
        });
        // Now we can require index.js and save the exports inside a namespace called myFunctions.
        // This includes our cloud functions, which can now be accessed at myFunctions.makeUppercase
        // and myFunctions.addMessage
        myFunctions = require('../index');
    });

    after(() => {
        // Restoring our stubs to the original methods.
        configStub.restore();
        adminInitStub.restore();
    });
    // [END stubConfig]

        describe('test', () => {
            it('should return status code 200', (done) => {

                // [START invokeHTTPS]
                // A fake request object, with req.query.text set to 'input'
                const req = {};
                // A fake response object, with a stubbed redirect function which asserts that it is called
                // with parameters 303, 'new_ref'.
                const res = {
                    status: (status) => {
                        assert.equal(status, 200);
                        done();
                    }
                };

                // Invoke addMessage with our fake request and response objects. This will cause the
                // assertions in the response object to be evaluated.
                myFunctions.test(req, res);
                // [END invokeHTTPS]

            })
        })

})

Body:
Here's how I got around the cors errors, with sinon

const res = {};

Object.assign(res, {
  status: sinon.stub().returns(res),
  end: sinon.stub().returns(res),
  json: sinon.stub().returns(res),
  setHeader: sinon.stub(),
  getHeader: sinon.stub(),
});

beforeEach(() => {
  Object.values(res).forEach(stub => stub.resetHistory());
});

Then, in your test, you can test your responses:

    cloudFunctions.testFunction({ query: { text: 'foo' } }, res);
    response = res.json.lastCall.args[0];


问:
How to rotate a canvas by following mouse if the canvas already has something drawn on it
I currently have a canvas that has an element drawn on it that I draw using a custom function and the onload function I would like to know how to be able to rotate this canvas around by following the mouse 360 degrees like turning a wheel. The code is as follows

<!DOCTYPE html>

        <title>Help</title>

        <canvas id="MyCanvas" width="500" height="500"></canvas>

```
</div>
</div>
</p>

<p>Does anyone know how this would be possible I have tried multiple different functions. however, they do not seem to be able to do anything.
help will be very appreciated.</p>

<p>Edited but with slight issue </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

    <head>
        <title>Help</title>
    </head>

    <style>
    canvas{
         border: 2px solid black;
        }
    </style>

    <body>

        <canvas id="Canvas" height="300"></canvas>

        <script>
            const ctx = canvas.getContext("2d");

            const mouse = { x: 0, y: 0 };
            function mouseEvents(e) {
              const bounds = canvas.getBoundingClientRect();
              mouse.x = e.pageX - bounds.left - scrollX;
              mouse.y = e.pageY - bounds.top - scrollY;
            }
            document.addEventListener("mousemove", mouseEvents);

            function drawRotated(x, y, angle) {
              ctx.setTransform(1, 0, 0, 1, x, y);
              ctx.rotate(angle);
              ctx.beginPath();
              ctx.arc(0, 0, 100, 0, Math.PI * 2);
              ctx.moveTo(-100, 0);
              ctx.lineTo(100, 0);
              ctx.lineTo(60, -80);
              ctx.closePath();
              ctx.stroke();
            }

            function update(timer) {
              ctx.setTransform(1, 0, 0, 1, 0, 0); // reset transform
              ctx.clearRect(0, 0, 300, 300);

              var angle = Math.atan2(mouse.y - 150, mouse.x - 150);

              drawRotated(150, 150, angle);
              requestAnimationFrame(update);
            }
            requestAnimationFrame(update);
        </script>

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

答:
You need to create a mouse move listener, and an animation loop.

In the animation loop get the mouse position and use Math.atan2( to get the direction from the center canvas to the mouse.

Then set the transform with ctx.setTransform to scale and position the designs rotation center, and then use ctx.rotate to rotate the transform to point along the angle computed.

See snippet for more details

const ctx = canvas.getContext("2d");
// create mouse event listener
const mouse = { x: 0, y: 0 };
function mouseEvents(e) {
  const bounds = canvas.getBoundingClientRect();
  mouse.x = e.pageX - bounds.left - scrollX;
  mouse.y = e.pageY - bounds.top - scrollY;
}
document.addEventListener("mousemove", mouseEvents);

// draw design at x,y and rotated by angle
function drawRotated(x, y, angle) {
  ctx.setTransform(1, 0, 0, 1, x, y);
  ctx.rotate(angle);
  ctx.beginPath();
  ctx.arc(0, 0, 100, 0, Math.PI * 2);
  ctx.moveTo(-100, 0);
  ctx.lineTo(100, 0);
  ctx.lineTo(60, -80);
  ctx.closePath();
  ctx.stroke();
}

// render loop called 60 times a second
function update(timer) {
  ctx.setTransform(1, 0, 0, 1, 0, 0); // reset transform
  ctx.clearRect(0, 0, 300, 300);

  // get angle from center to mouse
  var angle = Math.atan2(mouse.y - 150, mouse.x - 150);

  // draw rotated design
  drawRotated(150, 150, angle);
  requestAnimationFrame(update);
}
requestAnimationFrame(update);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas {
  border: 2px solid black;
}</code>```

<canvas id="canvas" height=300></canvas>```

Body:
I currently have a canvas that has an element drawn on it that I draw using a custom function and the onload function I would like to know how to be able to rotate this canvas around by following the mouse 360 degrees like turning a wheel. The code is as follows

<!DOCTYPE html>

        <title>Help</title>

        <canvas id="MyCanvas" width="500" height="500"></canvas>

Does anyone know how this would be possible I have tried multiple different functions. however, they do not seem to be able to do anything.
help will be very appreciated.

Edited but with slight issue

<!DOCTYPE html>

        <title>Help</title>

        <canvas id="Canvas" height="300"></canvas>

Body:
You need to create a mouse move listener, and an animation loop.

In the animation loop get the mouse position and use Math.atan2( to get the direction from the center canvas to the mouse.

Then set the transform with ctx.setTransform to scale and position the designs rotation center, and then use ctx.rotate to rotate the transform to point along the angle computed.

See snippet for more details

const ctx = canvas.getContext("2d");
// create mouse event listener
const mouse = { x: 0, y: 0 };
function mouseEvents(e) {
  const bounds = canvas.getBoundingClientRect();
  mouse.x = e.pageX - bounds.left - scrollX;
  mouse.y = e.pageY - bounds.top - scrollY;
}
document.addEventListener("mousemove", mouseEvents);

// draw design at x,y and rotated by angle
function drawRotated(x, y, angle) {
  ctx.setTransform(1, 0, 0, 1, x, y);
  ctx.rotate(angle);
  ctx.beginPath();
  ctx.arc(0, 0, 100, 0, Math.PI * 2);
  ctx.moveTo(-100, 0);
  ctx.lineTo(100, 0);
  ctx.lineTo(60, -80);
  ctx.closePath();
  ctx.stroke();
}

// render loop called 60 times a second
function update(timer) {
  ctx.setTransform(1, 0, 0, 1, 0, 0); // reset transform
  ctx.clearRect(0, 0, 300, 300);

  // get angle from center to mouse
  var angle = Math.atan2(mouse.y - 150, mouse.x - 150);

  // draw rotated design
  drawRotated(150, 150, angle);
  requestAnimationFrame(update);
}
requestAnimationFrame(update);

canvas {
  border: 2px solid black;
}

<canvas id="canvas" height=300></canvas>


问:
How to check which type of data stored in a variable in python?
I am very new to Python.Is there any method through which i can find out which type of value is stored in a particular variable?

In below code how to find out type of stored value in a variable?

```<code>counter = 100
miles   = 1000.0
name    = "John"
name    =10

print counter
print miles
print name
</code>```

答:
Quite simply, use type command built into python.

For example, you could check the type of this variable:

```<code>>>> name = 'John'
>>> print(type(name))
<class 'str'>
</code>```

Use this method wherever you want on a variable, and you don't necessarily have to print it. You could use it to do different things with different variables based on what type it is, for example.

Hoped this helped :)

Body:
I am very new to Python.Is there any method through which i can find out which type of value is stored in a particular variable?

In below code how to find out type of stored value in a variable?

counter = 100
miles   = 1000.0
name    = "John"
name    =10

print counter
print miles
print name

Body:
Quite simply, use type command built into python.

For example, you could check the type of this variable:

>>> name = 'John'
>>> print(type(name))
<class 'str'>

Use this method wherever you want on a variable, and you don't necessarily have to print it. You could use it to do different things with different variables based on what type it is, for example.

Hoped this helped :)


答:
You could try :

```<code>DECLARE @barcode XML;
SET @barcode = '<BCODES><BCODE>a</BCODE><BCODE>b</BCODE><BCODE>c</BCODE><BCODE>d</BCODE></BCODES>';

            --INSERT INTO #barcode

SELECT barcode = n.v.value('.[1]', 'NVARCHAR(128)')
FROM @barcode.nodes('BCODES/BCODE') AS n(v);
</code>```

Result :

```<code>barcode
a
b
c
d
</code>```

Title: Select statement on XML not returning desired output

Body:
DECLARE @barcode XML

            SET @barcode = '<BCODES><BCODE>a</BCODE><BCODE>b</BCODE><BCODE>c</BCODE><BCODE>d</BCODE></BCODES>'

            --INSERT INTO #barcode
            SELECT      v.x.value('BCODE[1]','VARCHAR(15)') AS Barcodes
            FROM        @barcode.nodes('BCODES') v(x)

Result-->

Barcodes

a

I'm unable to get b,c and d in the output.

Body:
You could try :

DECLARE @barcode XML;
SET @barcode = '<BCODES><BCODE>a</BCODE><BCODE>b</BCODE><BCODE>c</BCODE><BCODE>d</BCODE></BCODES>';

            --INSERT INTO #barcode

SELECT barcode = n.v.value('.[1]', 'NVARCHAR(128)')
FROM @barcode.nodes('BCODES/BCODE') AS n(v);

Result :

barcode
a
b
c
d


问:
React Material ui beta datepicker format
I can't figure out how to change format for datepicker field.
For user it shows MM/DD/YYYY and I want to show YYYY-MM-DD. Cant find any info in docs so maybe someone knows how to change format?
My component code looks like </p>

```<code><Field
name='date'
component={TextField}
type='date'/>
</code>```

答:
You can pass desired format date in as value prop in your DatePicker component.
https://jsfiddle.net/mu5r94m6/4/

<DatePicker hintText="Pick your date" value={new Date(2007,11, 5)}/>

Body:
I can't figure out how to change format for datepicker field.
For user it shows MM/DD/YYYY and I want to show YYYY-MM-DD. Cant find any info in docs so maybe someone knows how to change format?
My component code looks like

<Field
name='date'
component={TextField}
type='date'/>