问:
Return JSX from function
I have a a component that needs to check for multiple options and return based on those options. Therefore I have created an outside function that is called in my component return statement to determine the format that will be returned:

render() {
    const { policy } = this.props;
    let deployment = policy.Deployment;
    let value = policy.value;
    let policyLegend = deployment.policyLegend;
    let policyObj = this.valueToPolicy(policyLegend, value);
    console.log(policyObj);
    if(policy.name == "SP4") {
      policyLegend[1].values = this.formatSp4Firmware(policyLegend[1]);
      return (

          <Form onSubmit={ (event) => this.handleSubmit(event, this.props) }>
            {
              policyLegend.map((policy) => {
                return (

{ policy.displayName }

                    { this.renderSp4Policies(policy) }

                );
              })
            }
            <Button name={ 'Submit' } type='submit'>Submit</Button>
            <Button onClick={ this.props.onCancel }>Cancel</Button>
          </Form>

      )
    }
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script></code>```

renderSp4Policies(policy) {
    if(policy.displayName == "Firmware Options") {
      let firmwareDropdownNames = this.formatFirmawareDropdownNames(policy);
      let toggles = policy.values[0][Object.keys(policy.values[0])];
      let toggleOptions = []
      Object.keys(toggles).map(toggle => {
       if(typeof(toggles[toggle]) == "boolean"){
          var obj = {};
          obj[toggle] = toggles[toggle];
        toggleOptions.push(obj);
        }
      })
      return (
        toggleOptions.map(toggleOption => {
          let toggleName = Object.keys(toggleOption).toString();
          return (
            <Form.Field key={ toggleName }>
              { toggleName }
              <Checkbox toggle />
            </Form.Field>
          )
        })
      )
    } else {
        return (
          policy.values.map(value => {
            return(
              <Form.Field key={ value.name }>
                { value.displayName || value.name }
                <Checkbox toggle />
              </Form.Field>
            )
          }
        )
      )
    }
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script></code>```

EDIT

I have applied some of the answers given with moderate success.

Within renderSp4Policies what is being returned in the else statement displays, but the beginning if(policy.displayName == "Firmware Options") returns nothing.

Appreciate all advice, thank you in advance!

答:
It seems like many people already did really well to help you fix your problem and explain it with details. But don't forget to follow the new concept of Component-Based architecture that React has introduced. So as a best practice you can write it this way:

```<code>import React, {Component} from "react";

import Sp4Policies from "./sp4Policies";

class MyComponent extends Component {
  render() {
    const { policy } = this.props;
    let deployment = policy.Deployment;
    let value = policy.value;
    let policyLegend = deployment.policyLegend;
    let policyObj = this.valueToPolicy(policyLegend, value);
    console.log(policyObj);
    if(policy.name == "SP4") {
      policyLegend[1].values = this.formatSp4Firmware(policyLegend[1]);
      return (
        <div>
          <Form onSubmit={ (event) => this.handleSubmit(event, this.props) }>
            {
              policyLegend.map((policy) => {
                return (
                  <div key={ policy.id }>
                    <h3>{ policy.displayName }</h3>
                    <Sp4Policies policy={policy} />
                  </div>
                );
              })
            }
            <Button name={ 'Submit' } type='submit'>Submit</Button>
            <Button onClick={ this.props.onCancel }>Cancel</Button>
          </Form>
        </div>
      )
    }
  }
}
</code>```

and a separate file:

```<code>import React, {Component} from "react";

class Sp4Policies extends Component {
  render() {
     const policy = this.props.policy;

     if (policy.displayName == "Firmware Options") {
       return (
         policy.values.map(value => (
           <Form.Field key={ value.name }>
             <label>{ value.displayName || value.name }</label>
             <Checkbox toggle />
           </Form.Field>
        ))
       );
     }

     return (
       let toggles = policy.values[0][Object.keys(policy.values[0])];
       Object.keys(toggles).forEach(toggle => {
         if(typeof(toggles[toggle]) !== "boolean"){
             delete toggles[toggle];
         }
       })
       Object.keys(toggles).map(toggle => {
         return(
           <Form.Field key={ toggle }>
             <label> { toggle } </label>
             <Checkbox toggle />
           </Form.Field>
         );
       })
     );
  }
}

export default Sp4Policies;
</code>```

this makes your code clean and it ensures separation of concerns between your components. And of course you can still separate it even further.

Title: Return JSX from function

Body:
I have a a component that needs to check for multiple options and return based on those options. Therefore I have created an outside function that is called in my component return statement to determine the format that will be returned:

render() {
    const { policy } = this.props;
    let deployment = policy.Deployment;
    let value = policy.value;
    let policyLegend = deployment.policyLegend;
    let policyObj = this.valueToPolicy(policyLegend, value);
    console.log(policyObj);
    if(policy.name == "SP4") {
      policyLegend[1].values = this.formatSp4Firmware(policyLegend[1]);
      return (

          <Form onSubmit={ (event) => this.handleSubmit(event, this.props) }>
            {
              policyLegend.map((policy) => {
                return (

{ policy.displayName }

                    { this.renderSp4Policies(policy) }

                );
              })
            }
            <Button name={ 'Submit' } type='submit'>Submit</Button>
            <Button onClick={ this.props.onCancel }>Cancel</Button>
          </Form>

      )
    }
  }

renderSp4Policies(policy) {
    if(policy.displayName == "Firmware Options") {
      let firmwareDropdownNames = this.formatFirmawareDropdownNames(policy);
      let toggles = policy.values[0][Object.keys(policy.values[0])];
      let toggleOptions = []
      Object.keys(toggles).map(toggle => {
       if(typeof(toggles[toggle]) == "boolean"){
          var obj = {};
          obj[toggle] = toggles[toggle];
        toggleOptions.push(obj);
        }
      })
      return (
        toggleOptions.map(toggleOption => {
          let toggleName = Object.keys(toggleOption).toString();
          return (
            <Form.Field key={ toggleName }>
              { toggleName }
              <Checkbox toggle />
            </Form.Field>
          )
        })
      )
    } else {
        return (
          policy.values.map(value => {
            return(
              <Form.Field key={ value.name }>
                { value.displayName || value.name }
                <Checkbox toggle />
              </Form.Field>
            )
          }
        )
      )
    }
  }

EDIT

I have applied some of the answers given with moderate success.

Within renderSp4Policies what is being returned in the else statement displays, but the beginning if(policy.displayName == "Firmware Options") returns nothing.

Appreciate all advice, thank you in advance!

Body:
It seems like many people already did really well to help you fix your problem and explain it with details. But don't forget to follow the new concept of Component-Based architecture that React has introduced. So as a best practice you can write it this way:

import React, {Component} from "react";

import Sp4Policies from "./sp4Policies";

class MyComponent extends Component {
  render() {
    const { policy } = this.props;
    let deployment = policy.Deployment;
    let value = policy.value;
    let policyLegend = deployment.policyLegend;
    let policyObj = this.valueToPolicy(policyLegend, value);
    console.log(policyObj);
    if(policy.name == "SP4") {
      policyLegend[1].values = this.formatSp4Firmware(policyLegend[1]);
      return (
        <div>
          <Form onSubmit={ (event) => this.handleSubmit(event, this.props) }>
            {
              policyLegend.map((policy) => {
                return (
                  <div key={ policy.id }>
                    <h3>{ policy.displayName }</h3>
                    <Sp4Policies policy={policy} />
                  </div>
                );
              })
            }
            <Button name={ 'Submit' } type='submit'>Submit</Button>
            <Button onClick={ this.props.onCancel }>Cancel</Button>
          </Form>
        </div>
      )
    }
  }
}

and a separate file:

import React, {Component} from "react";

class Sp4Policies extends Component {
  render() {
     const policy = this.props.policy;

     if (policy.displayName == "Firmware Options") {
       return (
         policy.values.map(value => (
           <Form.Field key={ value.name }>
             <label>{ value.displayName || value.name }</label>
             <Checkbox toggle />
           </Form.Field>
        ))
       );
     }

     return (
       let toggles = policy.values[0][Object.keys(policy.values[0])];
       Object.keys(toggles).forEach(toggle => {
         if(typeof(toggles[toggle]) !== "boolean"){
             delete toggles[toggle];
         }
       })
       Object.keys(toggles).map(toggle => {
         return(
           <Form.Field key={ toggle }>
             <label> { toggle } </label>
             <Checkbox toggle />
           </Form.Field>
         );
       })
     );
  }
}

export default Sp4Policies;

this makes your code clean and it ensures separation of concerns between your components. And of course you can still separate it even further.


来源: stackexchange

问:
URL construction using okHttpClient
I am getting a problem with constructing a URL with okHttpClient. I am getting
below error in URL construction (http://16.234.156.25:88/example)

Please find the code :

```<code>public static void main(String[] args) throws IOException, URISyntaxException {
OkHttpClient client = new OkHttpClient.Builder().connectTimeout(30, TimeUnit.SECONDS)
                    .writeTimeout(30, TimeUnit.SECONDS).readTimeout(30, TimeUnit.SECONDS).build();

            String host = "16.234.156.25";
            int port = 88;

            String port1 = Integer.toString(port);
            String ipadd = host + ":" + port1;

            URI uri = new URI(ipadd);
            String finalURL = uri.toString();

            HashMap<String, String> map = new HashMap<>();

            map.put("", finalURL):

            for (Entry<String, String> m : map.entrySet()) {

                Request request = new Request.Builder()

                        .url("http://" + m.getValue() + "/example").get()
                        .addHeader("cache-control", "no-cache")
                        .addHeader("postman-token", "e6335509-3e1d-54c8-a975-dc9430e6d115").build();
</code>```

Error :

Exception in thread "main" java.net.URISyntaxException: Illegal
  character in scheme name at index 0: 16.234.156.25:88 at
  java.net.URI$Parser.fail(URI.java:2848)

答:
The error message is very good. The "scheme" is the first part of the URL, before the "://". The problem is that you didn't provide one. I'm guessing you need an "http" or "https". Look at the Javadoc for the URI class; you need more than just an IP address.

Good luck.

ContentLicense: CC BY-SA 3.0

Title: URL construction using okHttpClient

Body:
I am getting a problem with constructing a URL with okHttpClient. I am getting
below error in URL construction (http://16.234.156.25:88/example)

Please find the code :

public static void main(String[] args) throws IOException, URISyntaxException {
OkHttpClient client = new OkHttpClient.Builder().connectTimeout(30, TimeUnit.SECONDS)
                    .writeTimeout(30, TimeUnit.SECONDS).readTimeout(30, TimeUnit.SECONDS).build();

            String host = "16.234.156.25";
            int port = 88;

            String port1 = Integer.toString(port);
            String ipadd = host + ":" + port1;

            URI uri = new URI(ipadd);
            String finalURL = uri.toString();

            HashMap<String, String> map = new HashMap<>();

            map.put("", finalURL):

            for (Entry<String, String> m : map.entrySet()) {

                Request request = new Request.Builder()

                        .url("http://" + m.getValue() + "/example").get()
                        .addHeader("cache-control", "no-cache")
                        .addHeader("postman-token", "e6335509-3e1d-54c8-a975-dc9430e6d115").build();

Error :

Exception in thread "main" java.net.URISyntaxException: Illegal
  character in scheme name at index 0: 16.234.156.25:88 at
  java.net.URI$Parser.fail(URI.java:2848)


问:
How do not write provided characters to bash stdout when program interrupted on getpass?
I have the simple code witch get password by getpass:

```<code>if (!(pass = getpass("Enter password:\n"))) {
    perror("getpass failed");
    return -1;
}
</code>```

Also I have a signal handler witch exit program.

If signal was caught at the time of getting password from terminal, program stops, but all provided by user characters appears on bash prompt.

Code of signal handler:

```<code>void handle (int sig) {
    printf("Time for password entering expired!\n");
    /* Enable echo on terminal after aborted getpass*/
    system("stty echo");
    exit(-1);
}
</code>```

How can I make bash prompt clear after interrupt program by signal?

答: Using of termios resolved problem.

Body:
I have the simple code witch get password by getpass:

if (!(pass = getpass("Enter password:\n"))) {
    perror("getpass failed");
    return -1;
}

Also I have a signal handler witch exit program.

If signal was caught at the time of getting password from terminal, program stops, but all provided by user characters appears on bash prompt.

Code of signal handler:

void handle (int sig) {
    printf("Time for password entering expired!\n");
    /* Enable echo on terminal after aborted getpass*/
    system("stty echo");
    exit(-1);
}

How can I make bash prompt clear after interrupt program by signal?

Body: Using of termios resolved problem.


问:
Scenario output gives wrong answer upon second loop
I'm pretty much done with this program except for this small problem.

The problem is when the first time I loop through the program with the following in put of 20.0 36.0 72.0 2.0 10.0 18.0 10.0 my output comes out to be 232.59 sec which is correct.

For the second time I loop around, I input 25.0 72.0 200.0 1.5 8.0 30.0 20.0 my output comes out to be 800.41 which is wrong when it should be 1141.63

Now if I reverse the inputs and take what I entered for the second loop for the first loop and first for the second loop. I do get my output of 1141.63 for the first loop, but the second loop, my answer is 1141.63 . I am very puzzled as to how this happening. One of my early solutions was to reset all variables back to 0 after each loop using another function, but that didn't seem to work and now I'm here.

EDIT: Problem figured out. Had to reset time and volFilled to 0 at the end of each loop.

```<code>void Well::timeReq()
{
    bool exit = false;

    while (!exit)
    {

        std::cout << "Enter 7 digits to evaluate or type 0 now to exit." << std::endl;

        std::cin >> UP;

        if (UP == 0)
        {
            exit = true;
            break;
        }

        std::cin >> D >> L >> B >> P >> DOWN >> V;

        double WL = L;

        double radius = (D / 2);

        while (volFilled < V)
        {

            time += UP;

            time += sqrt(2 * (L) / (acceleration * 12.0));

            time += (L) / (P);

            L += (B * cuIns) / (pi*pow(radius, 2));

            time += DOWN;
            volFilled += B;
        }

        std::cout << std::endl;
        std::cout << "Scenario " << scenario << ":" << std::endl;

        std::cout << std::left << std::setw(25) << "\tUp Hill"            << std::left << std::setw(30) << std::fixed << std::setprecision(2)
                  << UP << " sec" << std::endl;

        std::cout << std::left << std::setw(25) << "\tWell Diamter"       << std::left << std::setw(30) << std::fixed << std::setprecision(2)
                  << D << " in" << std::endl;

        std::cout << std::left << std::setw(25) << "\tWater Level"        << std::left << std::setw(30) << std::fixed << std::setprecision(2)
                  << WL << " in" << std::endl;

        std::cout << std::left << std::setw(25) << "\tBucket Volume"      << std::left << std::setw(30) << std::fixed << std::setprecision(2)
                  << B << " cu ft" << std::endl;

        std::cout << std::left << std::setw(25) << "\tBucket Ascent Rate" << std::left << std::setw(30) << std::fixed << std::setprecision(2)
                  << P << " in/sec" << std::endl;

        std::cout << std::left << std::setw(25) << "\tDownhill"           << std::left << std::setw(30) << std::fixed << std::setprecision(2)
                  << DOWN << " sec" << std::endl;

        std::cout << std::left << std::setw(25) << "\tRequired Volume"    << std::left << std::setw(30) << std::fixed << std::setprecision(2)
                  << V << " cu ft" << std::endl;

        std::cout << std::left << std::setw(25) << "\tTIME REQUIRED"      << std::left << std::setw(30) << std::fixed << std::setprecision(2)
                  << time << " sec" << std::endl;

        scenario++;
    }
}
</code>```

答: While this may not completely fix your issue, you need to at least reinitialize your volFilled value back to 0.0 between scenarios. Otherwise you're just continuing from the previous scenario's volFilled, and that explains why the second test that you did with switching the scenarios yielded the same output. After the first scenario where volFilled reaches 20.0, it won't execute the logic inside the considion while (volFilled < V) in the second scenario because at this point, volFilled = 20 while V = 10.

Body:
I'm pretty much done with this program except for this small problem.

The problem is when the first time I loop through the program with the following in put of 20.0 36.0 72.0 2.0 10.0 18.0 10.0 my output comes out to be 232.59 sec which is correct.

For the second time I loop around, I input 25.0 72.0 200.0 1.5 8.0 30.0 20.0 my output comes out to be 800.41 which is wrong when it should be 1141.63

Now if I reverse the inputs and take what I entered for the second loop for the first loop and first for the second loop. I do get my output of 1141.63 for the first loop, but the second loop, my answer is 1141.63 . I am very puzzled as to how this happening. One of my early solutions was to reset all variables back to 0 after each loop using another function, but that didn't seem to work and now I'm here.

EDIT: Problem figured out. Had to reset time and volFilled to 0 at the end of each loop.

void Well::timeReq()
{
    bool exit = false;

    while (!exit)
    {

        std::cout << "Enter 7 digits to evaluate or type 0 now to exit." << std::endl;

        std::cin >> UP;

        if (UP == 0)
        {
            exit = true;
            break;
        }

        std::cin >> D >> L >> B >> P >> DOWN >> V;

        double WL = L;

        double radius = (D / 2);

        while (volFilled < V)
        {

            time += UP;

            time += sqrt(2 * (L) / (acceleration * 12.0));

            time += (L) / (P);

            L += (B * cuIns) / (pi*pow(radius, 2));

            time += DOWN;
            volFilled += B;
        }

        std::cout << std::endl;
        std::cout << "Scenario " << scenario << ":" << std::endl;

        std::cout << std::left << std::setw(25) << "\tUp Hill"            << std::left << std::setw(30) << std::fixed << std::setprecision(2)
                  << UP << " sec" << std::endl;

        std::cout << std::left << std::setw(25) << "\tWell Diamter"       << std::left << std::setw(30) << std::fixed << std::setprecision(2)
                  << D << " in" << std::endl;

        std::cout << std::left << std::setw(25) << "\tWater Level"        << std::left << std::setw(30) << std::fixed << std::setprecision(2)
                  << WL << " in" << std::endl;

        std::cout << std::left << std::setw(25) << "\tBucket Volume"      << std::left << std::setw(30) << std::fixed << std::setprecision(2)
                  << B << " cu ft" << std::endl;

        std::cout << std::left << std::setw(25) << "\tBucket Ascent Rate" << std::left << std::setw(30) << std::fixed << std::setprecision(2)
                  << P << " in/sec" << std::endl;

        std::cout << std::left << std::setw(25) << "\tDownhill"           << std::left << std::setw(30) << std::fixed << std::setprecision(2)
                  << DOWN << " sec" << std::endl;

        std::cout << std::left << std::setw(25) << "\tRequired Volume"    << std::left << std::setw(30) << std::fixed << std::setprecision(2)
                  << V << " cu ft" << std::endl;

        std::cout << std::left << std::setw(25) << "\tTIME REQUIRED"      << std::left << std::setw(30) << std::fixed << std::setprecision(2)
                  << time << " sec" << std::endl;

        scenario++;
    }
}


问:
Change font of UINavigationController title
Can I change the font of my UINavigationController? --> title

答:
The answer from @morgancodes will set the font for all UINavigationController titles. I've updated it for Swift 4:

```<code>let attributes = [NSAttributedStringKey.font: UIFont(name: "Menlo", size: 14) as Any]
UINavigationBar.appearance().titleTextAttributes = attributes
UIBarButtonItem.appearance().setTitleTextAttributes(attributes, for: .normal)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
The answer from @morgancodes will set the font for all UINavigationController titles. I've updated it for Swift 4:

let attributes = [NSAttributedStringKey.font: UIFont(name: "Menlo", size: 14) as Any]
UINavigationBar.appearance().titleTextAttributes = attributes
UIBarButtonItem.appearance().setTitleTextAttributes(attributes, for: .normal)


问:
PHP: CSV to Array and Array to HTML
I have converted an one-column CSV into a PHP associative array with the following code:

```<code>$file = array_map('str_getcsv', file('file.csv'));
</code>```

And now I have something like this:

```<code>Array (
[0] => Array ( [0] => Value 1 )
[1] => Array ( [0] => Value 2 )
[2] => Array ( [0] => Value 3 )
.
.
.
[i] => Array ( [0] => Value i )
)
</code>```

How can I put those values into a HTML form? I have tried it using foreach ($file as $pos => $pos2 => $pos3) to declare the loop, but the form still shows "Array" as output.

Also, is there any way to get a simple numeric array from this CSV?

答:
As you have array of arrays and you need values under key 0 in each subarray, your code can be:

```<code>foreach ($file as $pos) {
    echo $pos[0];
}
</code>```

Title: PHP: CSV to Array and Array to HTML

Body:
I have converted an one-column CSV into a PHP associative array with the following code:

$file = array_map('str_getcsv', file('file.csv'));

And now I have something like this:

Array (
[0] => Array ( [0] => Value 1 )
[1] => Array ( [0] => Value 2 )
[2] => Array ( [0] => Value 3 )
.
.
.
[i] => Array ( [0] => Value i )
)

How can I put those values into a HTML form? I have tried it using foreach ($file as $pos => $pos2 => $pos3) to declare the loop, but the form still shows "Array" as output.

Also, is there any way to get a simple numeric array from this CSV?

Body:
As you have array of arrays and you need values under key 0 in each subarray, your code can be:

foreach ($file as $pos) {
    echo $pos[0];
}


问:
403 error when trying to access Google Authsub from FLash Application (Authsub for Actionscript)
I am trying to get my Flex application to authenticate with google using the instructions here:

http://code.google.com/apis/gdata/docs/as-authsub.html

I have copied the example there and am trying to get it to work. I am running my app on a loca server so I have changed the next parameter:

```<code>authSubParams['next'] = 'http://localhost/AuthSub.html';
</code>```

Getting the first token works fine but when I try to get the long lived token I get an error:

```<code>getLongLivedToken: singleUseToken: 1%2Fa...
onHttpStatus: [HTTPStatusEvent type="httpStatus" bubbles=false cancelable=false eventPhase=2 status=403 responseURL=null]
onGetTokenFailed: Error #2032: Stream Error. URL: https://accounts.googleapis.com/accounts/AuthSubSessionToken
</code>```

it looks like I am getting a 403 error. Any ideas?

Whole App:

```<code><?xml version="1.0" encoding="utf-8"?>
<s:Application
    xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark"
    xmlns:mx="library://ns.adobe.com/flex/mx"
    minWidth="955"
    minHeight="600"
    initialize=" onInitialized() "
    applicationComplete=" onLoaded() "
    >

    <fx:Script>
        <![CDATA[

            import flash.external.ExternalInterface;
            import flash.net.navigateToURL;

            import mx.controls.Alert;

            private function onInitialized() : void {
                // Load the cross domain policy file for each of the googleapis.com
                // domains used. At the very least, we need the ones for the API (photos)
                // and the one for AuthSub for ActionScript (accounts).
                Security.loadPolicyFile('http://photos.googleapis.com/data/crossdomain.xml');
                Security.loadPolicyFile('https://accounts.googleapis.com/crossdomain.xml');
            }

            private function onLoaded() : void {
                // Once the application has loaded, check to see if an AuthSub token was
                // placed into the current page's URL. If it was, the user has already
                // authenticated, we can continue to connect to the the service itself.
                // In a real application, the long-term cookie would also be stored and
                // checked here, to remove the need for the user to authenticate for this
                // application every time it is used.
                var searchPortion : String = ExternalInterface.call('window.location.search.toString');

                //searchPortion = "?token=tokenSavenFromPreviousAttempt";

                if (searchPortion.length > 0) {
                    // remove the ? from the token and extract the token.
                    searchPortion = searchPortion.substring(1);

                    // NOTE: Real applications should parse the URL properly.
                    if (searchPortion.indexOf('token=') == 0) {

                        log( "token found: " + searchPortion );

                        getLongLivedToken(searchPortion.substring(6));
                        return;
                    }
                }

                // No token found; redirect the user to the AuthSub page. Note that this URL
                // is on the google.com domain. We can contact the google.com domain because
                // this isn't a request from within Flash, but rather a page redirect.
                var getTokenPage : URLRequest = new URLRequest('https://www.google.com/accounts/AuthSubRequest');

                // Construct the parameters of the AuthSub request. These are the same parameters
                // as normal AuthSub, which can be found here: http://code.google.com/apis/accounts/docs/AuthSub.html#AuthSubRequest
                var authSubParams : URLVariables = new URLVariables();
                authSubParams['scope'] = 'http://photos.googleapis.com/data'; // photos API
                authSubParams['session'] = 1; // single-use token
                authSubParams['secure'] = 0; // non-secure apps
                authSubParams['next'] = 'http://localhost/AuthSub.html'; // The URL of this app.
                //authSubParams['next'] = 'http://localhost/'; // The URL of this app.

                log( "token not found, sending AuthSubRequest" );

                getTokenPage.data =  authSubParams;
                navigateToURL(getTokenPage, '_top');
            }

            private function getLongLivedToken(singleUseToken : String) : void {
                // Construct a call to the AuthSub for ActionScript endpoint on accounts.googleapis.com.
                // This call will exchange the single use token given to use by AuthSub for a long-term
                // token that we can use to make requests to endpoints such as Photos.
                var getTokenRequest : URLRequest = new URLRequest('https://accounts.googleapis.com/accounts/AuthSubSessionToken');

                // Due to a bug in Flash, a URLRequest with a GET request will
                // not properly send headers. We therefore use POST for this and *ALL*
                // requests.
                getTokenRequest.method = URLRequestMethod.POST;

                // Due to a bug in Flash, a URLRequest without a valid parameter will
                // not properly send headers. We therefore add a useless parameter to
                // make this code work.
                getTokenRequest.data = new URLVariables('pleaseignore=ignore');

                // Add the AuthSub for ActionScript headers.
                getTokenRequest.requestHeaders.push(new URLRequestHeader('Authorization', 'AuthSub token="' + singleUseToken + '"'));

                // Create the loader to get the token itself. The loader will callback
                // to the following event handlers if and when the server responds.
                var getToken : URLLoader = new URLLoader();
                getToken.addEventListener(Event.COMPLETE, onGetTokenResult);
                getToken.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onGetTokenFailed);
                getToken.addEventListener(IOErrorEvent.IO_ERROR, onGetTokenFailed);
                getToken.addEventListener( HTTPStatusEvent.HTTP_STATUS, onHttpStatus );

                log( "getLongLivedToken: singleUseToken: " + singleUseToken );

                try {
                    getToken.load(getTokenRequest);
                } catch (e : Error) {

                    log( "error:\n" + e.message );

                    Alert.show('Some error occurred: ' + e);

                }
            }

            private function onGetTokenResult(e : Event) : void {

                // Load the parameters from the response.
                var getToken : URLLoader = URLLoader(e.target);
                var params : URLVariables = new URLVariables(getToken.data);

                // Parse the session token from the result. Real applications
                // might at this point store the token in a long-term cookie so
                // that repeated usages of the application do not require this entire
                // authentication process.
                var sessionToken : String = params.Token;

                log( "onGetTokenResult: sessionToken: " + sessionToken );

                // Trim the newline from the end of the session token.
                sessionToken = sessionToken.substring(0, sessionToken.length - 1);

                Alert.show('session token: [' + sessionToken + ']');

                // Prepare a request to the photos API for the private album
                // of the user.
                var albumRequest : URLRequest = new URLRequest('http://photos.googleapis.com/data/feed/api/user/default');
                albumRequest.data = new URLVariables('access=private&v=2&err=xml');

                // Due to a bug in Flash, a URLRequest with a GET request will
                // not properly send headers. We therefore use POST for this and *ALL*
                // requests.
                albumRequest.method = URLRequestMethod.POST;

                var authsubHeader : String = 'AuthSub token="' + sessionToken + '"';

                // Add the Authorization header which uses the session token.
                albumRequest.requestHeaders.push(new URLRequestHeader('Authorization', authsubHeader));

                // The X-HTTP-Method-Override header tells the Photos API to treat this request
                // as a GET request, even though it is being conducted as a POST (due to the bug
                // mentioned above). This is very important, as GData APIs will react differently
                // to different HTTP request types.
                albumRequest.requestHeaders.push(new URLRequestHeader('X-HTTP-Method-Override', 'GET'));

                // We expect ATOM XML to be returned.
                albumRequest.requestHeaders.push(new URLRequestHeader('Content-Type', 'application/atom+xml'));

                var getAlbum : URLLoader = new URLLoader();
                getAlbum.addEventListener(Event.COMPLETE, onGetAlbumResult);
                getAlbum.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onGetAlbumFailed);
                getAlbum.addEventListener(IOErrorEvent.IO_ERROR, onGetAlbumFailed);

                try {
                    getAlbum.load(albumRequest);
                } catch (e : Error) {
                    Alert.show('Some error occurred: ' + e);
                }
            }

            private function onGetAlbumResult(e : Event) : void {
                // Load the XML from the response.
                var getAlbum : URLLoader = URLLoader(e.target);
                Alert.show('Returned XML: ' + getAlbum.data);
            }

            private function onGetTokenFailed(e : ErrorEvent) : void {
                log( "onGetTokenFailed: " + e.text );
                Alert.show('Some error occurred: ' + e);
            }

            private function onGetAlbumFailed(e : ErrorEvent) : void {
                log( "onGetAlbumFailed: " + e.text );
                Alert.show('Some error occurred: ' + e);
            }

            private function onHttpStatus(e : HTTPStatusEvent) : void {
                log( "onHttpStatus: " + e );
                Alert.show('Some error occurred: ' + e);
            }

            private function log( message : String ) : void
            {
                trace( message );

                debugOutput.text = debugOutput.text ? debugOutput.text : "";

                debugOutput.text = debugOutput.text.length == 0 ? message : debugOutput.text + "\n" + message;
            }

        ]]>
    </fx:Script>

    <s:TextArea
        id="debugOutput"
        left="5"
        right="5"
        top="5"
        bottom="5"
        />

</s:Application>
</code>```

答:
Change:

```<code>var searchPortion : String = ExternalInterface.call('window.location.search.toString');
</code>```

to

```<code>var searchPortion : String = decodeURIComponent( ExternalInterface.call('window.location.search.toString'));
</code>```

Body:
I am trying to get my Flex application to authenticate with google using the instructions here:

http://code.google.com/apis/gdata/docs/as-authsub.html

I have copied the example there and am trying to get it to work. I am running my app on a loca server so I have changed the next parameter:

authSubParams['next'] = 'http://localhost/AuthSub.html';

Getting the first token works fine but when I try to get the long lived token I get an error:

getLongLivedToken: singleUseToken: 1%2Fa...
onHttpStatus: [HTTPStatusEvent type="httpStatus" bubbles=false cancelable=false eventPhase=2 status=403 responseURL=null]
onGetTokenFailed: Error #2032: Stream Error. URL: https://accounts.googleapis.com/accounts/AuthSubSessionToken

it looks like I am getting a 403 error. Any ideas?

Whole App:

<?xml version="1.0" encoding="utf-8"?>
<s:Application
    xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark"
    xmlns:mx="library://ns.adobe.com/flex/mx"
    minWidth="955"
    minHeight="600"
    initialize=" onInitialized() "
    applicationComplete=" onLoaded() "
    >

    <fx:Script>
        <![CDATA[

            import flash.external.ExternalInterface;
            import flash.net.navigateToURL;

            import mx.controls.Alert;

            private function onInitialized() : void {
                // Load the cross domain policy file for each of the googleapis.com
                // domains used. At the very least, we need the ones for the API (photos)
                // and the one for AuthSub for ActionScript (accounts).
                Security.loadPolicyFile('http://photos.googleapis.com/data/crossdomain.xml');
                Security.loadPolicyFile('https://accounts.googleapis.com/crossdomain.xml');
            }

            private function onLoaded() : void {
                // Once the application has loaded, check to see if an AuthSub token was
                // placed into the current page's URL. If it was, the user has already
                // authenticated, we can continue to connect to the the service itself.
                // In a real application, the long-term cookie would also be stored and
                // checked here, to remove the need for the user to authenticate for this
                // application every time it is used.
                var searchPortion : String = ExternalInterface.call('window.location.search.toString');

                //searchPortion = "?token=tokenSavenFromPreviousAttempt";

                if (searchPortion.length > 0) {
                    // remove the ? from the token and extract the token.
                    searchPortion = searchPortion.substring(1);

                    // NOTE: Real applications should parse the URL properly.
                    if (searchPortion.indexOf('token=') == 0) {

                        log( "token found: " + searchPortion );

                        getLongLivedToken(searchPortion.substring(6));
                        return;
                    }
                }

                // No token found; redirect the user to the AuthSub page. Note that this URL
                // is on the google.com domain. We can contact the google.com domain because
                // this isn't a request from within Flash, but rather a page redirect.
                var getTokenPage : URLRequest = new URLRequest('https://www.google.com/accounts/AuthSubRequest');

                // Construct the parameters of the AuthSub request. These are the same parameters
                // as normal AuthSub, which can be found here: http://code.google.com/apis/accounts/docs/AuthSub.html#AuthSubRequest
                var authSubParams : URLVariables = new URLVariables();
                authSubParams['scope'] = 'http://photos.googleapis.com/data'; // photos API
                authSubParams['session'] = 1; // single-use token
                authSubParams['secure'] = 0; // non-secure apps
                authSubParams['next'] = 'http://localhost/AuthSub.html'; // The URL of this app.
                //authSubParams['next'] = 'http://localhost/'; // The URL of this app.

                log( "token not found, sending AuthSubRequest" );

                getTokenPage.data =  authSubParams;
                navigateToURL(getTokenPage, '_top');
            }

            private function getLongLivedToken(singleUseToken : String) : void {
                // Construct a call to the AuthSub for ActionScript endpoint on accounts.googleapis.com.
                // This call will exchange the single use token given to use by AuthSub for a long-term
                // token that we can use to make requests to endpoints such as Photos.
                var getTokenRequest : URLRequest = new URLRequest('https://accounts.googleapis.com/accounts/AuthSubSessionToken');

                // Due to a bug in Flash, a URLRequest with a GET request will
                // not properly send headers. We therefore use POST for this and *ALL*
                // requests.
                getTokenRequest.method = URLRequestMethod.POST;

                // Due to a bug in Flash, a URLRequest without a valid parameter will
                // not properly send headers. We therefore add a useless parameter to
                // make this code work.
                getTokenRequest.data = new URLVariables('pleaseignore=ignore');

                // Add the AuthSub for ActionScript headers.
                getTokenRequest.requestHeaders.push(new URLRequestHeader('Authorization', 'AuthSub token="' + singleUseToken + '"'));

                // Create the loader to get the token itself. The loader will callback
                // to the following event handlers if and when the server responds.
                var getToken : URLLoader = new URLLoader();
                getToken.addEventListener(Event.COMPLETE, onGetTokenResult);
                getToken.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onGetTokenFailed);
                getToken.addEventListener(IOErrorEvent.IO_ERROR, onGetTokenFailed);
                getToken.addEventListener( HTTPStatusEvent.HTTP_STATUS, onHttpStatus );

                log( "getLongLivedToken: singleUseToken: " + singleUseToken );

                try {
                    getToken.load(getTokenRequest);
                } catch (e : Error) {

                    log( "error:\n" + e.message );

                    Alert.show('Some error occurred: ' + e);

                }
            }

            private function onGetTokenResult(e : Event) : void {

                // Load the parameters from the response.
                var getToken : URLLoader = URLLoader(e.target);
                var params : URLVariables = new URLVariables(getToken.data);

                // Parse the session token from the result. Real applications
                // might at this point store the token in a long-term cookie so
                // that repeated usages of the application do not require this entire
                // authentication process.
                var sessionToken : String = params.Token;

                log( "onGetTokenResult: sessionToken: " + sessionToken );

                // Trim the newline from the end of the session token.
                sessionToken = sessionToken.substring(0, sessionToken.length - 1);

                Alert.show('session token: [' + sessionToken + ']');

                // Prepare a request to the photos API for the private album
                // of the user.
                var albumRequest : URLRequest = new URLRequest('http://photos.googleapis.com/data/feed/api/user/default');
                albumRequest.data = new URLVariables('access=private&v=2&err=xml');

                // Due to a bug in Flash, a URLRequest with a GET request will
                // not properly send headers. We therefore use POST for this and *ALL*
                // requests.
                albumRequest.method = URLRequestMethod.POST;

                var authsubHeader : String = 'AuthSub token="' + sessionToken + '"';

                // Add the Authorization header which uses the session token.
                albumRequest.requestHeaders.push(new URLRequestHeader('Authorization', authsubHeader));

                // The X-HTTP-Method-Override header tells the Photos API to treat this request
                // as a GET request, even though it is being conducted as a POST (due to the bug
                // mentioned above). This is very important, as GData APIs will react differently
                // to different HTTP request types.
                albumRequest.requestHeaders.push(new URLRequestHeader('X-HTTP-Method-Override', 'GET'));

                // We expect ATOM XML to be returned.
                albumRequest.requestHeaders.push(new URLRequestHeader('Content-Type', 'application/atom+xml'));

                var getAlbum : URLLoader = new URLLoader();
                getAlbum.addEventListener(Event.COMPLETE, onGetAlbumResult);
                getAlbum.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onGetAlbumFailed);
                getAlbum.addEventListener(IOErrorEvent.IO_ERROR, onGetAlbumFailed);

                try {
                    getAlbum.load(albumRequest);
                } catch (e : Error) {
                    Alert.show('Some error occurred: ' + e);
                }
            }

            private function onGetAlbumResult(e : Event) : void {
                // Load the XML from the response.
                var getAlbum : URLLoader = URLLoader(e.target);
                Alert.show('Returned XML: ' + getAlbum.data);
            }

            private function onGetTokenFailed(e : ErrorEvent) : void {
                log( "onGetTokenFailed: " + e.text );
                Alert.show('Some error occurred: ' + e);
            }

            private function onGetAlbumFailed(e : ErrorEvent) : void {
                log( "onGetAlbumFailed: " + e.text );
                Alert.show('Some error occurred: ' + e);
            }

            private function onHttpStatus(e : HTTPStatusEvent) : void {
                log( "onHttpStatus: " + e );
                Alert.show('Some error occurred: ' + e);
            }

            private function log( message : String ) : void
            {
                trace( message );

                debugOutput.text = debugOutput.text ? debugOutput.text : "";

                debugOutput.text = debugOutput.text.length == 0 ? message : debugOutput.text + "\n" + message;
            }

        ]]>
    </fx:Script>

    <s:TextArea
        id="debugOutput"
        left="5"
        right="5"
        top="5"
        bottom="5"
        />

</s:Application>

Body:
Change:

var searchPortion : String = ExternalInterface.call('window.location.search.toString');

to

var searchPortion : String = decodeURIComponent( ExternalInterface.call('window.location.search.toString'));


问:
Jade/Pug: non-empty optional argument
Here is the standard method of the passing optional arguments in JADE/PUG mixin:

```<code>mixin TestMixin(id)
    - id = id || ''
    div(id=id)
</code>```

However, in the case of HTML ID, it should not be empty. If we have the empty ID, we should not add this attribute. I checked the Jade/Pug conditionals docs, but there are not enough the examples.

答:
This is a great case for an if/else conditional.</p>

```<code>mixin TestMixin(id)
  if id
    div(id=id)
  else
    div
</code>```

Title: Jade/Pug: non-empty optional argument

Body:
Here is the standard method of the passing optional arguments in JADE/PUG mixin:

mixin TestMixin(id)
    - id = id || ''
    div(id=id)

However, in the case of HTML ID, it should not be empty. If we have the empty ID, we should not add this attribute. I checked the Jade/Pug conditionals docs, but there are not enough the examples.

Body:
This is a great case for an if/else conditional.

mixin TestMixin(id)
  if id
    div(id=id)
  else
    div


问:
Need to total record counts in SQL Server
I'm trying to get a sum of total records partitioned by entity and status.  I'm able to do this by creating several queries, but I'd like to know if there's a simpler way than my method.

This is the data:

```<code>    EntityID   StatusDate   StatusType   Total
      10        2017-07-19      H1         3
      10        2017-08-18      H1         3
      10        2017-09-01      H1         3
      10        2017-04-01      H4         23
      10        2017-04-01      H4         23
</code>```

In this example StatusType = H1 has 3 different records, for a total of 3 with that status.  StatusType = H4 has 23 different records, for a total of 23(I didn't include all 23 lines for obvious reasons).  I'd like to total this column to display 26, which is the total of the 3 H1 status and 23 H4 statuses.

This is what I came up with:

```<code>    Select a.*
    into #test
    from
    (select t.*, row_number()over(partition by entityid, statustypename, total order by statusdate) as rn
    from Table t) a
    where rn = 1
</code>```

This produced the following:

```<code>    EntityID    StatusDate   StatusType   Total   rn
      10         2017-07-19     H1          3      1
      10         2017-04-01     H5          23     1
</code>```

I then created this:

```<code>    Select a.*,
    sum(total) over(partition by entityid order by statusdate)as newtotal
    from #test
</code>```

Which produced:

```<code>    EntityID    StatusDate    StatusType   Total   NewTotal
      10         2017-04-01     H4          23        23
      10         2017-07-19     H1           3        26
</code>```

The problem with this is it's getting kind of messy creating all these queries, plus I lost all my detail data from the original data set.  Is there a more efficient way to get these totals?

答:
You can group by the entity and status, and then use COUNT() to get the total of each status, then union that result with a total count, like this:

```<code>SELECT StatusType, COUNT(*)
FROM Table
GROUP BY EntityID, StatusType

UNION

SELECT StatusType = 'Total', COUNT(*)
FROM Table
</code>```

Body:
I'm trying to get a sum of total records partitioned by entity and status.  I'm able to do this by creating several queries, but I'd like to know if there's a simpler way than my method.

This is the data:

    EntityID   StatusDate   StatusType   Total
      10        2017-07-19      H1         3
      10        2017-08-18      H1         3
      10        2017-09-01      H1         3
      10        2017-04-01      H4         23
      10        2017-04-01      H4         23

In this example StatusType = H1 has 3 different records, for a total of 3 with that status.  StatusType = H4 has 23 different records, for a total of 23(I didn't include all 23 lines for obvious reasons).  I'd like to total this column to display 26, which is the total of the 3 H1 status and 23 H4 statuses.

This is what I came up with:

    Select a.*
    into #test
    from
    (select t.*, row_number()over(partition by entityid, statustypename, total order by statusdate) as rn
    from Table t) a
    where rn = 1

This produced the following:

    EntityID    StatusDate   StatusType   Total   rn
      10         2017-07-19     H1          3      1
      10         2017-04-01     H5          23     1

I then created this:

    Select a.*,
    sum(total) over(partition by entityid order by statusdate)as newtotal
    from #test

Which produced:

    EntityID    StatusDate    StatusType   Total   NewTotal
      10         2017-04-01     H4          23        23
      10         2017-07-19     H1           3        26

The problem with this is it's getting kind of messy creating all these queries, plus I lost all my detail data from the original data set.  Is there a more efficient way to get these totals?

Body:
You can group by the entity and status, and then use COUNT() to get the total of each status, then union that result with a total count, like this:

SELECT StatusType, COUNT(*)
FROM Table
GROUP BY EntityID, StatusType

UNION

SELECT StatusType = 'Total', COUNT(*)
FROM Table


问:
Does ns2 has capability to implement store-carry-forward mechanism? If it has how to do that?
I don't know ns 2 has capability to do this but I want to implement store-carry-forward mechanism in ns 2. However, I don't know where to start. Also I don't know what its steps. What protocols this mechanism uses? Is there anybody who can help me?</p>

答:
ns2 + DTN

If you have other ns2 builds / installs : Rename the executable´s ns to a new name → ns-orig, 'ns-app-name', etc. And remove any ns2 *PATH text from .bashrc .

Build ns2 + DTN

```<code>tar xvf ns-allinone-2.35_gcc5.tar.gz
</code>```

https://drive.google.com/file/d/0B7S255p3kFXNVVlxR0ZNRGVORjQ/view?usp=sharing

```<code>cd ns-allinone-2.35/
zcat dtn_ns235.patch.gz | patch -p0
./install
cd ns-2.35/
sudo make install
</code>```

Simulation : Copy an example (from ns2dtn_campaign/) to ns-allinone-2.35/, and run ./simulate_dtn.sh. The location is important as this path is used : ../ns-allinone-2.35/dei80211mr-1.1.4/src/.libs/libdei80211mr.so

Example, simulation files (and one empty folder) to be copied : { bundle-test-large-scen.tcl, create-traffic-file.tcl, scen_n40_pt2_ms20_t5000_x2000_y2000, simulate_dtn.sh, Run1/ }.

Please note that the simulation time is an hour (or more).

Watch the trace file qtrace.tr : Will very slowly increase to ~9MB.

Result : ns-allinone-2.35/Run1/{ bundle_delays.tr, qtrace.tr,   receipt_delays.tr }. The files can be used with Xgraph.

Body:
ns2 + DTN

If you have other ns2 builds / installs : Rename the executable´s ns to a new name → ns-orig, 'ns-app-name', etc. And remove any ns2 *PATH text from .bashrc .

Build ns2 + DTN

tar xvf ns-allinone-2.35_gcc5.tar.gz

https://drive.google.com/file/d/0B7S255p3kFXNVVlxR0ZNRGVORjQ/view?usp=sharing

cd ns-allinone-2.35/
zcat dtn_ns235.patch.gz | patch -p0
./install
cd ns-2.35/
sudo make install

Simulation : Copy an example (from ns2dtn_campaign/) to ns-allinone-2.35/, and run ./simulate_dtn.sh. The location is important as this path is used : ../ns-allinone-2.35/dei80211mr-1.1.4/src/.libs/libdei80211mr.so

Example, simulation files (and one empty folder) to be copied : { bundle-test-large-scen.tcl, create-traffic-file.tcl, scen_n40_pt2_ms20_t5000_x2000_y2000, simulate_dtn.sh, Run1/ }.

Please note that the simulation time is an hour (or more).

Watch the trace file qtrace.tr : Will very slowly increase to ~9MB.

Result : ns-allinone-2.35/Run1/{ bundle_delays.tr, qtrace.tr,   receipt_delays.tr }. The files can be used with Xgraph.


问:
Vectors and physics in games
Can forces be stored as dot products? such as the gravity on a planet.

And for a game, for example a 2d spaceship game. would one add a right thrust vector and a left vector to power the ship and move it around. then this would mean the angle of the ship shown on screen is computed from those vectors and the player would have no control over the actual angle of the ship.

Is this correct?

答:
Can forces be stored as dot products?
such as the gravity on a planet.

This makes no sense whatsoever.  A force is a vector; dot product is the scalar product of two vectors.

And for a game, for example a 2d
spaceship game. would one add a right
thrust vector and a left vector to
power the ship and move it around.
then this would mean the angle of the
ship shown on screen is computed from
those vectors and

the player would
have no control over the actual angle
of the ship.

Huh?

Would you allow the player to vary the magnitudes of either vector?  If yes, then they have some control.

What does "left" and "right" vector mean to you?  What do they mean if the ship rotates 90 degrees?  Do they become "up" and "down"?  How does that change things?

Would you agree that if you have "left" and "right" vectors of equal magnitude that sum of forces in the x-direction is zero and the ship will not accelerate at all?  (You make no mention of vectors in the y-direction, so I'll assume that the sum of forces in the y-direction is zero, too.)

Is this correct?

No.

Your understanding of Newtonian mechanics is equal to your current acceptance rate.

Title: Vectors and physics in games


问:
How to use groupby and take the difference between the two groups?
Let say I have this simplified dataframe with three variables:

```<code> ID    sample  test_result
 P1    Normal           9
 P2    Normal           7
 P3    Normal           2
 P1     Tumor           6
 P2     Tumor           5
 P3     Tumor           3
</code>```

I want to know the difference between the normal and tumor test_results, but I am not sure how to approach it.

I have tried using groupby on sample column and then use the diff() method on test_result column but that did not work.

Here is what I have tried:

```<code>df.groupby('sample')['test_result'].diff()
</code>```

The output I am expecting is like:

```<code>ID   test_result
P1             3 # the difference between P1 Normal and P1 Tumor (i.e. 9-6)
P2             2
P3            -1
</code>```

Any idea how to tackle this?

答:
Or we can keep using groupby

```<code>df['New']=df.sort_values('ID').groupby('ID')['test_result'].diff()
df
Out[636]:
   ID  sample  test_result  New
0  P1  Normal            9  NaN
1  P2  Normal            7  NaN
2  P3  Normal            2  NaN
3  P1   Tumor            6 -3.0
4  P2   Tumor            5 -2.0
5  P3   Tumor            3  1.0
df.dropna()
Out[637]:
   ID sample  test_result  New
3  P1  Tumor            6 -3.0
4  P2  Tumor            5 -2.0
5  P3  Tumor            3  1.0

df.dropna()[['ID','New']]
Out[639]:
   ID  New
3  P1 -3.0
4  P2 -2.0
5  P3  1.0
</code>```

Body:
Let say I have this simplified dataframe with three variables:

 ID    sample  test_result
 P1    Normal           9
 P2    Normal           7
 P3    Normal           2
 P1     Tumor           6
 P2     Tumor           5
 P3     Tumor           3

I want to know the difference between the normal and tumor test_results, but I am not sure how to approach it.

I have tried using groupby on sample column and then use the diff() method on test_result column but that did not work.

Here is what I have tried:

df.groupby('sample')['test_result'].diff()

The output I am expecting is like:

ID   test_result
P1             3 # the difference between P1 Normal and P1 Tumor (i.e. 9-6)
P2             2
P3            -1

Any idea how to tackle this?

Body:
Or we can keep using groupby

df['New']=df.sort_values('ID').groupby('ID')['test_result'].diff()
df
Out[636]:
   ID  sample  test_result  New
0  P1  Normal            9  NaN
1  P2  Normal            7  NaN
2  P3  Normal            2  NaN
3  P1   Tumor            6 -3.0
4  P2   Tumor            5 -2.0
5  P3   Tumor            3  1.0
df.dropna()
Out[637]:
   ID sample  test_result  New
3  P1  Tumor            6 -3.0
4  P2  Tumor            5 -2.0
5  P3  Tumor            3  1.0

df.dropna()[['ID','New']]
Out[639]:
   ID  New
3  P1 -3.0
4  P2 -2.0
5  P3  1.0


问:
Scrape URL provided by CSV
I have a CSV containing some columns with data, the 15th column reports a list of URLs.  Now, I need to select each URL from the column, scrape a new price from the target webpage, and then store that in the price column to update the old price.

Without the same column enumeration, here is an approximate CSV:

```<code>asin,title,product URL,price
KSKFUSH01,Product Title,http://....,56.00
</code>```

Below is the sample code I wrote, but it merely prints URLs :(

```<code>import csv

with open('some.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file)

for line in csv_reader:
    print(line[15])
</code>```

Any help or suggestions about accomplishing this goal?

Thanks

答:
Here's a good guide on how to scrape websites using BeautifulSoup
https://medium.freecodecamp.org/how-to-scrape-websites-with-python-and-beautifulsoup-5946935d93fe</p>

Title: Scrape URL provided by CSV

Body:
I have a CSV containing some columns with data, the 15th column reports a list of URLs.  Now, I need to select each URL from the column, scrape a new price from the target webpage, and then store that in the price column to update the old price.

Without the same column enumeration, here is an approximate CSV:

asin,title,product URL,price
KSKFUSH01,Product Title,http://....,56.00

Below is the sample code I wrote, but it merely prints URLs :(

import csv

with open('some.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file)

for line in csv_reader:
    print(line[15])

Any help or suggestions about accomplishing this goal?

Thanks


问:
Android - how to get ListView to line up underneath Text View
I am attempting to put a ListView beneath a Text View in an Android App. However, the first line of the ListView shows up on the same line as the TextView. How do I get this to move underneath?

Here is the layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="wrap_content"
        android:layout_height="wrap_content">

    <TextView android:id="@+id/android:question"
          android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/dummy_question" />
    <ListView android:id="@+id/android:list"
          android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    <TextView android:id="@+id/android:empty"
          android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/no_notes"/>

</LinearLayout>
</code>```

答: Try using a TableLayout. Example. Good luck.</p>

Body:
I am attempting to put a ListView beneath a Text View in an Android App. However, the first line of the ListView shows up on the same line as the TextView. How do I get this to move underneath?

Here is the layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="wrap_content"
        android:layout_height="wrap_content">

    <TextView android:id="@+id/android:question"
          android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/dummy_question" />
    <ListView android:id="@+id/android:list"
          android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    <TextView android:id="@+id/android:empty"
          android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/no_notes"/>

</LinearLayout>


问:
Bad Minute error Crontab
I am pretty new to crontab so this may be a pretty obvious syntax error, but I can't figure out what the problem is. I've looked at a lot of other posts with the same problem but I can't narrow down the issue.

```<code>PYTHONPATH =/usr/lib/python3.4/site-packages
MAILTO="email@email.com"
45 13 * * * chmod +x  /home/elalo/ServiceNow/scheduler.py >/tmp/out.txt 2>&1
touch /tmp/out.txt
tail /tmp/out.txt
</code>```

Thanks in advance.

答:
There were actually a few reasons why this was not working.

The out files were messing with it and I did not need to include the chmod a+x
I also did not have the python path correctly laid out.

the correct ways is denote the python path:

```<code>/usr/bin/python3.4
</code>```

then add the path to the script so in total it looks likes

```<code>MAILTO="email@address"
30 12 * * * /usr/bin/python3.4 /home/elalo/ServiceNow/scheduler.py
</code>```

Also, inside of the script, I referenced files in the same directory and those also needed the full path.

For example:

```<code>scheduler.txt
</code>```

Needed to be

```<code>/home/elalo/ServiceNow/scheduler.txt
</code>```

Title: Bad Minute error Crontab

Body:
I am pretty new to crontab so this may be a pretty obvious syntax error, but I can't figure out what the problem is. I've looked at a lot of other posts with the same problem but I can't narrow down the issue.

PYTHONPATH =/usr/lib/python3.4/site-packages
MAILTO="email@email.com"
45 13 * * * chmod +x  /home/elalo/ServiceNow/scheduler.py >/tmp/out.txt 2>&1
touch /tmp/out.txt
tail /tmp/out.txt

Thanks in advance.

Body:
There were actually a few reasons why this was not working.

The out files were messing with it and I did not need to include the chmod a+x
I also did not have the python path correctly laid out.

the correct ways is denote the python path:

/usr/bin/python3.4

then add the path to the script so in total it looks likes

MAILTO="email@address"
30 12 * * * /usr/bin/python3.4 /home/elalo/ServiceNow/scheduler.py

Also, inside of the script, I referenced files in the same directory and those also needed the full path.

For example:

scheduler.txt

Needed to be

/home/elalo/ServiceNow/scheduler.txt


问:
Python ipywidget: Align description and boxes
I want to align boxes and description in my code. Please let me know if there is a work around.

Code snippet below:

```<code>def helper(a,b,c):
            print (a)
TextField1= Text(value='', placeholder='Type client table name',description='Client List Name:',disabled=False)
TextField2= Text(value='', placeholder='Type flagged column name',description='Flagged column name:',disabled=False)
TextField3= Text(value='', placeholder='Type columns name',description='Columns name:',disabled=False)
x=interactive(helper,a=TextField1,b=TextField2,c=TextField3)
display(x)
</code>```

I tried to reference another stack page and tried a code that worked for one of the users which was as below

But it did not seem to be working for me.

code snippet below:

```<code>from ipywidgets import widgets
from IPython.display import Javascript, display

align_kw = dict(
    _css = (('.widget-label', 'min-width', '20ex'),),
    margin = '0px 0px 5px 12px'
)
platform_ui = widgets.Dropdown(description = 'platform',options=['iPhone','iPad','Android'], **align_kw)
event_type_ui = widgets.Text(value='open', description='Test Event', **align_kw)
os_version_ui = widgets.Text(value='iOS9', description='Operating System', **align_kw)
refresh_ui = widgets.Checkbox(description='Force Refresh', **align_kw)

display(platform_ui,event_type_ui,os_version_ui,refresh_ui)
</code>```

答: I raised the issue on their git page as well. Please refer to https://github.com/jupyter-widgets/ipywidgets/issues/1849 for solution</p>

Body:
I want to align boxes and description in my code. Please let me know if there is a work around.

Code snippet below:

def helper(a,b,c):
            print (a)
TextField1= Text(value='', placeholder='Type client table name',description='Client List Name:',disabled=False)
TextField2= Text(value='', placeholder='Type flagged column name',description='Flagged column name:',disabled=False)
TextField3= Text(value='', placeholder='Type columns name',description='Columns name:',disabled=False)
x=interactive(helper,a=TextField1,b=TextField2,c=TextField3)
display(x)

I tried to reference another stack page and tried a code that worked for one of the users which was as below

But it did not seem to be working for me.

code snippet below:

from ipywidgets import widgets
from IPython.display import Javascript, display

align_kw = dict(
    _css = (('.widget-label', 'min-width', '20ex'),),
    margin = '0px 0px 5px 12px'
)
platform_ui = widgets.Dropdown(description = 'platform',options=['iPhone','iPad','Android'], **align_kw)
event_type_ui = widgets.Text(value='open', description='Test Event', **align_kw)
os_version_ui = widgets.Text(value='iOS9', description='Operating System', **align_kw)
refresh_ui = widgets.Checkbox(description='Force Refresh', **align_kw)

display(platform_ui,event_type_ui,os_version_ui,refresh_ui)


问:
Python: cx_Freeze: Noting happend if I click the .exe
nothing happend when I double click the test.exe.....

But to start from the beginning, I create a Little python Programm which is in test.py:

test.py:

```<code>import tkinter
top = tkinter.Tk()
top.mainloop()`
</code>```

Then I use cx_Freeze to convert test.py to an exe:
The following lines are in my Setup.py:

```<code>import sys
from cx_Freeze import setup, Executable
import os
build_exe_options = {"packages": ["tkinter"], "include_files":[r"C:\\Program
Files\\Python36\\tcl\\tcl8.6",
         r"C:\\Program Files\\Python36\\tcl\\tk8.6"]}
os.environ['TCL_LIBRARY'] = "C:\\Program Files\\Python36\\tcl\\tcl8.6"
os.environ['TK_LIBRARY'] = "C:\\Program Files\\Python36\\tcl\\tk8.6"
base = None
if sys.platform == "win32":
    base = "Win32GUI"    `
setup(  name = "stest",
    version = "1.0",description = "hello",
    options = {"build_exe": build_exe_options},
    executables = [Executable("test.py", base='Win32GUI')])`
</code>```

Then I open a cmd and type in the following " python setup.py build". No erros appears while Building.

But if I click the test.exe nothing happend.

Where is my mistake?

答:
Do NOT install cx_freeze by "pip install cx_freeze", because an old Version will be installed,

instead go to https://pypi.python.org/pypi/cx_Freeze and then download the right version.

Use for example pip install cx_Freeze-6.0b1-cp36-cp36m-win_amd64.whl.

Finally copy the file "tcl86t.dll" and "tk86t.dll" into the build folder

Body:
nothing happend when I double click the test.exe.....

But to start from the beginning, I create a Little python Programm which is in test.py:

test.py:

import tkinter
top = tkinter.Tk()
top.mainloop()`

Then I use cx_Freeze to convert test.py to an exe:
The following lines are in my Setup.py:

import sys
from cx_Freeze import setup, Executable
import os
build_exe_options = {"packages": ["tkinter"], "include_files":[r"C:\\Program
Files\\Python36\\tcl\\tcl8.6",
         r"C:\\Program Files\\Python36\\tcl\\tk8.6"]}
os.environ['TCL_LIBRARY'] = "C:\\Program Files\\Python36\\tcl\\tcl8.6"
os.environ['TK_LIBRARY'] = "C:\\Program Files\\Python36\\tcl\\tk8.6"
base = None
if sys.platform == "win32":
    base = "Win32GUI"    `
setup(  name = "stest",
    version = "1.0",description = "hello",
    options = {"build_exe": build_exe_options},
    executables = [Executable("test.py", base='Win32GUI')])`

Then I open a cmd and type in the following " python setup.py build". No erros appears while Building.

But if I click the test.exe nothing happend.

Where is my mistake?


问:
JavaFX smooth movement and timelines
I've recently started using JavaFX and I'm making a small game with a player being controlled by WASD keys. At first I made it so you could move the player by adjusting his x & y coordinates on keyPress but I found that the movement was very rough. Now I changed things and started using Timelines starting & stopping them when a key is pressed and released.

The code:

```<code>Timeline timelineW = new Timeline();
Timeline timelineA = new Timeline();
Timeline timelineS = new Timeline();
Timeline timelineD = new Timeline();

 public void createTimeLineW() {
    timelineW.setCycleCount(Timeline.INDEFINITE);
    final KeyValue kv = new KeyValue(player.yProperty(), -Integer.MAX_VALUE);
    final KeyFrame kf = new KeyFrame(Duration.hours(3000), kv);
    timelineW.getKeyFrames().add(kf);
}

public void createTimeLineA() {
    timelineA.setCycleCount(Timeline.INDEFINITE);
    final KeyValue kv = new KeyValue(player.xProperty(), -Integer.MAX_VALUE);
    final KeyFrame kf = new KeyFrame(Duration.hours(3000), kv);
    timelineA.getKeyFrames().add(kf);
}

public void createTimeLineS() {
    timelineS.setCycleCount(Timeline.INDEFINITE);
    final KeyValue kv = new KeyValue(player.yProperty(), Integer.MAX_VALUE);
    final KeyFrame kf = new KeyFrame(Duration.hours(3000), kv);
    timelineS.getKeyFrames().add(kf);
}

public void createTimeLineD() {
    timelineD.setCycleCount(Timeline.INDEFINITE);
    final KeyValue kv = new KeyValue(player.xProperty(), Integer.MAX_VALUE);
    final KeyFrame kf = new KeyFrame(Duration.hours(3000), kv);
    timelineD.getKeyFrames().add(kf);
}
</code>```

This is the base of the current movement. So upon pressing W the imageView player would get timelineW.play() and upon releasing W it would get timelineW.stop(); and like so for the other keys. The overall reason I made this change was because the movement is more smooth but there are still several bugs. Is it possible to even do movement with this? Or should I look into alternatives.

Thanks on forehand.

答:
Typically, you’ll want to periodically check for a key and reset the movement Timeline:

```<code>/** Distance player moves in one "step." */
private static final int movementDistance = 10;

/** Time it takes to move one "step." */
private static final Duration movementTime = Duration.seconds(0.5);

private Timeline xMovement;

private void checkMovementKeys() {
    // ...

    if (xMovement == null) {
        xMovement = new Timeline();
    }

    if (rightMovementKeyPressed) {
        xMovement.getKeyFrames().setAll(
            new KeyFrame(movementTime,
                new KeyValue(player.xProperty(),
                    player.getX() + movementDistance)));
        xMovement.playFromStart();
    }
    if (leftMovementKeyPressed) {
        xMovement.getKeyFrames().setAll(
            new KeyFrame(movementTime,
                new KeyValue(player.xProperty(),
                    player.getX() - movementDistance)));
        xMovement.playFromStart();
    }

    // ...
}
</code>```

Notice that the cycle count is left at its default, which is one.

Title: JavaFX smooth movement and timelines

Body:
I've recently started using JavaFX and I'm making a small game with a player being controlled by WASD keys. At first I made it so you could move the player by adjusting his x & y coordinates on keyPress but I found that the movement was very rough. Now I changed things and started using Timelines starting & stopping them when a key is pressed and released.

The code:

Timeline timelineW = new Timeline();
Timeline timelineA = new Timeline();
Timeline timelineS = new Timeline();
Timeline timelineD = new Timeline();

 public void createTimeLineW() {
    timelineW.setCycleCount(Timeline.INDEFINITE);
    final KeyValue kv = new KeyValue(player.yProperty(), -Integer.MAX_VALUE);
    final KeyFrame kf = new KeyFrame(Duration.hours(3000), kv);
    timelineW.getKeyFrames().add(kf);
}

public void createTimeLineA() {
    timelineA.setCycleCount(Timeline.INDEFINITE);
    final KeyValue kv = new KeyValue(player.xProperty(), -Integer.MAX_VALUE);
    final KeyFrame kf = new KeyFrame(Duration.hours(3000), kv);
    timelineA.getKeyFrames().add(kf);
}

public void createTimeLineS() {
    timelineS.setCycleCount(Timeline.INDEFINITE);
    final KeyValue kv = new KeyValue(player.yProperty(), Integer.MAX_VALUE);
    final KeyFrame kf = new KeyFrame(Duration.hours(3000), kv);
    timelineS.getKeyFrames().add(kf);
}

public void createTimeLineD() {
    timelineD.setCycleCount(Timeline.INDEFINITE);
    final KeyValue kv = new KeyValue(player.xProperty(), Integer.MAX_VALUE);
    final KeyFrame kf = new KeyFrame(Duration.hours(3000), kv);
    timelineD.getKeyFrames().add(kf);
}

This is the base of the current movement. So upon pressing W the imageView player would get timelineW.play() and upon releasing W it would get timelineW.stop(); and like so for the other keys. The overall reason I made this change was because the movement is more smooth but there are still several bugs. Is it possible to even do movement with this? Or should I look into alternatives.

Thanks on forehand.

Body:
Typically, you’ll want to periodically check for a key and reset the movement Timeline:

/** Distance player moves in one "step." */
private static final int movementDistance = 10;

/** Time it takes to move one "step." */
private static final Duration movementTime = Duration.seconds(0.5);

private Timeline xMovement;

private void checkMovementKeys() {
    // ...

    if (xMovement == null) {
        xMovement = new Timeline();
    }

    if (rightMovementKeyPressed) {
        xMovement.getKeyFrames().setAll(
            new KeyFrame(movementTime,
                new KeyValue(player.xProperty(),
                    player.getX() + movementDistance)));
        xMovement.playFromStart();
    }
    if (leftMovementKeyPressed) {
        xMovement.getKeyFrames().setAll(
            new KeyFrame(movementTime,
                new KeyValue(player.xProperty(),
                    player.getX() - movementDistance)));
        xMovement.playFromStart();
    }

    // ...
}

Notice that the cycle count is left at its default, which is one.


问:
Use localization in a PCL
I have localized my Xamarin.Forms project (PCL approach). Additionally, I added another PCL as reference to this project by referencing the output dll from the Debug folder. This PCL is also localized after the same approach like the Xamarin.Forms project by using RESX files and setting the culture with AppResources.Culture = ci;

The current issue is, that this works as expected on my local machine, but not on the build server (Jenkins calling MSBuild). The difference also is that I work in the Debug mode, the generated apk file (Android) is build in the Release mode. But regardless of the mode, locally the localization is working fine in both modes! On the build server the resulting apk file contains now a mixture of two languages:

Localized strings according to the current device language (Xamarin.Forms project)

Non localized strings from the additional PCL (only showing strings from the language neutral RESX file)

Now I don't understand why this works locally, but not on the build server side. What I tried:

I logged the culture in the "faulty" generated apk from the build server and it is correctly set (in both the app and the additional PCL)

I checked the loaded resources and one AppResources.resources is showing up (apparently it contains all RESX files including the language-specific resources?)

I tried to locally call MSBuild similar to the task done on the Jenkins build server, but as always, locally it is working fine

Followed the instructions from Xamarin, but I didn't find any solution

Device culture is e.g. en-US, but my language neutral RESX file is set to en. I tried to add a AppResources.en-US.resx file to the additional PCL, but the system still shows the content from the language neutral RESX file.

Is this a configuration issue on the build server in combination with MSBuild? If yes, what is different or missing? Or is this a code issue? Is this a problem using the same name AppResources for localization in both projects (XF and additional PCL)? Do you have any hints for me to find this issue?

答:
The issue was that the result of the PCL (a dll) was copied to the XF project. But the build artefacts of the PCL also contains language specific resources (called satellite assembly). The folder structure looks like the following:

MyLib/bin/Debug/MyLib.dll

  MyLib/bin/Debug/en/MyLib.resources.dl

The folder en depends on your supported languages and can differ. If I copy all the required files with the same folder structure to the XF project, the translation works as expected. That was the reason, why it worked locally. It seems, that it isn't necessary to set the Culture in the resource files of the additional PCL.

Title: Use localization in a PCL


问:
Breaking Django views into seperate directories and files
I'm quite new to Django and I'm enjoying it a lot. I have broken my app's views into different files and placed them in a directory called app/views/(view files).

I have made an __init__.py file in the views directory this has caused me to have to use myproj.app.views.views in my site code. Which of coarse not very digestible.

Any ideas around this. Or is renaming my views directory to something else the way forward.

Thanks.

答: Just import the views from the other modules in __init__.py.


问:
How to get string between a character and first occurrence of double quotes?
I am trying to get tvg-logo string(http://awebsite/logos/TestChannel.png) but my current code only works on case one.For case 2 and 3 inputs the code outputs not only the tvg-logo value but also the rest of string after it!could you guys show me how to get ONLY tvg-logo url in all these case ?Thanks

```<code>public class HelloWorld {
  public static void main(String[] args) {

    //case 1:
    //String s="-1 tvg-name=\"Test Channel\" tvg-logo=\"http://awebsite/logos/TestChannel.png\"";
    //case 2:
    //String s="-1 tvg-name=\"Test Channel\" tvg-logo=\"http://awebsite/logos/TestChannel.png\" group-title=\"Movies\"";
    //case 3:
    String s="-1 tvg-logo=\"http://awebsite/logos/TestChannel.png\" tvg-name=\"Test Channel\" group-title=\"Movies\"";

    String icon = s.substring(s.indexOf("tvg-logo") + "tvg-logo".length()).replace("=", "").replace("\"", "").replace("\n", "");

    System.out.println("Logo:"+icon);
  }
}
</code>```

output for case 3 input:

```<code>Logo:http://awebsite/logos/TestChannel.png tvg-nameTest Channel group-titleMovies
</code>```

Expected output for all types of input cases:

```<code>Logo:http://awebsite/logos/TestChannel.png
</code>```

答:
If I am right, this is what happens in you code:

your string builder logic ("s.substring ....") works for case 1 because it fits quite well this case;

in case 2, you have also "group-title" and you don't manage this case, thus is still continues to appear on the final string;

in case 3, the situation is the same as the case 2 and moreover tvg-logo and tvg-name are in different orders.

At the end, your code makes a sort of overfitting for the case 1.
Keep the same order inside each string of each case and manage the case in which there is group-title at the end of the string.

Try this (I did not test it):

```<code>boolean groupFound = false;
//case 1:
//String s="-1 tvg-name=\"Test Channel\" tvg-logo=\"http://awebsite/logos/TestChannel.png\"";
//case 2: {
//String s="-1 tvg-name=\"Test Channel\" tvg-logo=\"http://awebsite/logos/TestChannel.png\" group-title=\"Movies\"";
//groupFound = true;}
//case 3: {
String s="-1 tvg-name=\"Test Channel\" tvg-logo=\"http://awebsite/logos/TestChannel.png\"  group-title=\"Movies\"";
groupFound = true; }

String icon = s.substring(s.indexOf("tvg-logo") + "tvg-logo".length()).replace("=", "").replace("\"", "").replace("\n", "");
if(groupFound){
   String group = "group-title";
   int groupIndex = String.indexOf(group);
   String newIcon = icon.substring(0, groupIndex);
}
</code>```

Body:
I am trying to get tvg-logo string(http://awebsite/logos/TestChannel.png) but my current code only works on case one.For case 2 and 3 inputs the code outputs not only the tvg-logo value but also the rest of string after it!could you guys show me how to get ONLY tvg-logo url in all these case ?Thanks

public class HelloWorld {
  public static void main(String[] args) {

    //case 1:
    //String s="-1 tvg-name=\"Test Channel\" tvg-logo=\"http://awebsite/logos/TestChannel.png\"";
    //case 2:
    //String s="-1 tvg-name=\"Test Channel\" tvg-logo=\"http://awebsite/logos/TestChannel.png\" group-title=\"Movies\"";
    //case 3:
    String s="-1 tvg-logo=\"http://awebsite/logos/TestChannel.png\" tvg-name=\"Test Channel\" group-title=\"Movies\"";

    String icon = s.substring(s.indexOf("tvg-logo") + "tvg-logo".length()).replace("=", "").replace("\"", "").replace("\n", "");

    System.out.println("Logo:"+icon);
  }
}

output for case 3 input:

Logo:http://awebsite/logos/TestChannel.png tvg-nameTest Channel group-titleMovies

Expected output for all types of input cases:

Logo:http://awebsite/logos/TestChannel.png

Body:
If I am right, this is what happens in you code:

your string builder logic ("s.substring ....") works for case 1 because it fits quite well this case;

in case 2, you have also "group-title" and you don't manage this case, thus is still continues to appear on the final string;

in case 3, the situation is the same as the case 2 and moreover tvg-logo and tvg-name are in different orders.

At the end, your code makes a sort of overfitting for the case 1.
Keep the same order inside each string of each case and manage the case in which there is group-title at the end of the string.

Try this (I did not test it):

boolean groupFound = false;
//case 1:
//String s="-1 tvg-name=\"Test Channel\" tvg-logo=\"http://awebsite/logos/TestChannel.png\"";
//case 2: {
//String s="-1 tvg-name=\"Test Channel\" tvg-logo=\"http://awebsite/logos/TestChannel.png\" group-title=\"Movies\"";
//groupFound = true;}
//case 3: {
String s="-1 tvg-name=\"Test Channel\" tvg-logo=\"http://awebsite/logos/TestChannel.png\"  group-title=\"Movies\"";
groupFound = true; }

String icon = s.substring(s.indexOf("tvg-logo") + "tvg-logo".length()).replace("=", "").replace("\"", "").replace("\n", "");
if(groupFound){
   String group = "group-title";
   int groupIndex = String.indexOf(group);
   String newIcon = icon.substring(0, groupIndex);
}


问:
Reflect is not defined when my project is deployed to the server

I'm trying to deploy my node.js project to the openshift server,
My project runs fine on my local machine but when deployed on the server it complains as follows

```<code>/opt/app-root/src/node_modules/inversify/lib/annotation/decorator_utils.js:22
    if (Reflect.hasOwnMetadata(metadataKey, annotationTarget) === true) {
        ^

ReferenceError: Reflect is not defined
    at _tagParameterOrProperty (/opt/app-root/src/node_modules/inversify/lib/annotation/decorator_utils.js:22:9)
    at Object.tagProperty (/opt/app-root/src/node_modules/inversify/lib/annotation/decorator_utils.js:12:5)
    at /opt/app-root/src/node_modules/inversify/lib/annotation/inject.js:13:31
    at __decorate (/opt/app-root/src/node_modules/inversify-express-utils/lib/base_http_controller.js:5:110)
    at /opt/app-root/src/node_modules/inversify-express-utils/lib/base_http_controller.js:17:5
    at Object.<anonymous> (/opt/app-root/src/node_modules/inversify-express-utils/lib/base_http_controller.js:25:2)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
</code>```

On VS code when I track the file and try to see where does it get from the Reflect I can see that it reads it from lib.es6.d.ts in vs code libraries so I guess that file isn't available on the server but I don't know how can I include it in the server?

Edit 1:
I'm not using docker and my package.js is as follow:

```<code>{
  "name": "mmm",
  "version": "1.0.0",
  "description": "",
  "main": "build/bootstrap.js",
  "scripts": {
    "compile": "tsc --declaration && node build/bootstrap.js",
    "dev": "nodemon -e ts  --exec \"npm run compile\"",
    "start": "nodemon -e ts  --exec \"npm run compile\"",
    "tsc": "tsc",
    "tsc:w": "tsc -w"
  },
  "author": "mmmm",
  "license": "ISC",
  "dependencies": {
    "@types/body-parser": "^1.16.5",
    "@types/express": "^4.0.39",
    "@types/node": "^8.0.44",
    "bluebird": "^3.5.1",
    "body-parser": "^1.18.2",
    "commander": "^2.12.2",
    "deep-diff": "^0.3.8",
    "express": "^4.16.2",
    "fs-finder": "^1.8.1",
    "inversify": "^4.5.2",
    "inversify-express-utils": "^4.0.1",
    "keypress": "^0.2.1",
    "knex": "^0.13.0",
    "mysql": "^2.15.0",
    "pg": "^7.3.0",
    "reflect-metadata": "^0.1.10",
    "request": "^2.83.0",
    "tape": "^4.8.0",
    "typeorm": "^0.1.1"
  },
  "devDependencies": {
    "nodemon": "^1.12.1",
    "typescript": "^2.6.2"
  }
}
</code>```

and my tsconfig.json is:

```<code>{
    "compilerOptions": {
       "target": "es6",
        "lib": ["es6", "dom"],
        "types": ["reflect-metadata"],
        "module": "commonjs",
        "moduleResolution": "node",
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "outDir": "build",
        "declarationDir": "declaration",
        "watch": false
    },
    "exclude": [
        "node_modules",
        "build",
        "declaration"
    ]
}
</code>```

答: That depends a lot on how you build your app. Is it a docker, s2i or custom. Knowing how your app is built, you have to make sure that either its own build process will install this dependency or that the image your build is based on contains all the required deps.</p>

Body:
I'm trying to deploy my node.js project to the openshift server,
My project runs fine on my local machine but when deployed on the server it complains as follows

/opt/app-root/src/node_modules/inversify/lib/annotation/decorator_utils.js:22
    if (Reflect.hasOwnMetadata(metadataKey, annotationTarget) === true) {
        ^

ReferenceError: Reflect is not defined
    at _tagParameterOrProperty (/opt/app-root/src/node_modules/inversify/lib/annotation/decorator_utils.js:22:9)
    at Object.tagProperty (/opt/app-root/src/node_modules/inversify/lib/annotation/decorator_utils.js:12:5)
    at /opt/app-root/src/node_modules/inversify/lib/annotation/inject.js:13:31
    at __decorate (/opt/app-root/src/node_modules/inversify-express-utils/lib/base_http_controller.js:5:110)
    at /opt/app-root/src/node_modules/inversify-express-utils/lib/base_http_controller.js:17:5
    at Object.<anonymous> (/opt/app-root/src/node_modules/inversify-express-utils/lib/base_http_controller.js:25:2)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)

On VS code when I track the file and try to see where does it get from the Reflect I can see that it reads it from lib.es6.d.ts in vs code libraries so I guess that file isn't available on the server but I don't know how can I include it in the server?

Edit 1:
I'm not using docker and my package.js is as follow:

{
  "name": "mmm",
  "version": "1.0.0",
  "description": "",
  "main": "build/bootstrap.js",
  "scripts": {
    "compile": "tsc --declaration && node build/bootstrap.js",
    "dev": "nodemon -e ts  --exec \"npm run compile\"",
    "start": "nodemon -e ts  --exec \"npm run compile\"",
    "tsc": "tsc",
    "tsc:w": "tsc -w"
  },
  "author": "mmmm",
  "license": "ISC",
  "dependencies": {
    "@types/body-parser": "^1.16.5",
    "@types/express": "^4.0.39",
    "@types/node": "^8.0.44",
    "bluebird": "^3.5.1",
    "body-parser": "^1.18.2",
    "commander": "^2.12.2",
    "deep-diff": "^0.3.8",
    "express": "^4.16.2",
    "fs-finder": "^1.8.1",
    "inversify": "^4.5.2",
    "inversify-express-utils": "^4.0.1",
    "keypress": "^0.2.1",
    "knex": "^0.13.0",
    "mysql": "^2.15.0",
    "pg": "^7.3.0",
    "reflect-metadata": "^0.1.10",
    "request": "^2.83.0",
    "tape": "^4.8.0",
    "typeorm": "^0.1.1"
  },
  "devDependencies": {
    "nodemon": "^1.12.1",
    "typescript": "^2.6.2"
  }
}

and my tsconfig.json is:

{
    "compilerOptions": {
       "target": "es6",
        "lib": ["es6", "dom"],
        "types": ["reflect-metadata"],
        "module": "commonjs",
        "moduleResolution": "node",
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "outDir": "build",
        "declarationDir": "declaration",
        "watch": false
    },
    "exclude": [
        "node_modules",
        "build",
        "declaration"
    ]
}


问:
PHP: Fatal Error: Maximum function nesting
I'm getting the following error message:

PHPFata1error:Maximumfunctionnesting1eve1of'100'reached,aborting

I'm using python and open a php-file like:

```<code>work = commands.getoutput("./scripts/php-file " + str(art) + " < " + str(sys.argv[1]+str(".temp")))
</code>```

I know that my problem has to do with

xdebug.max_nesting_level = 100

and that I should change the value. But: I'm working on a (work-)server and I can't change this value. Is there any way to bypass this problem?

Thanks for any advice!

答:
You could adjust the ini in your PHP code with ini_set</p>

```<code>ini_set('xdebug.max_nesting_level', 200);
</code>```

Body:
I'm getting the following error message:

PHPFata1error:Maximumfunctionnesting1eve1of'100'reached,aborting

I'm using python and open a php-file like:

work = commands.getoutput("./scripts/php-file " + str(art) + " < " + str(sys.argv[1]+str(".temp")))

I know that my problem has to do with

xdebug.max_nesting_level = 100

and that I should change the value. But: I'm working on a (work-)server and I can't change this value. Is there any way to bypass this problem?

Thanks for any advice!

Body:
You could adjust the ini in your PHP code with ini_set

ini_set('xdebug.max_nesting_level', 200);


问:
How to split a file containing a speech into a list of words on python 3?
My assignment is to take in State of the Union addresses by President Bush and President Obama and to figure out the number of unique words (or vocabulary size) and the top 20 most frequently used words. I am on the first stage of counting the number of unique words and have this so far:

```<code>    def uniqueWords(fileName):
fileIn = open(fileName, 'rt', encoding = 'UTF-8')
fileS = open('stopwords.txt', 'rt', encoding = 'UTF-8')
stop = fileS.split()
words = fileIn.split()
for x in range(len(words)):
    words[x] = words[x].lower()
    for z in words[x]:
        if z in '~!@#$%^&*()+=_:;,./\?"{}[]<>|':
            words[x] = words[x].replace(z, '')

unique_words = 0
while unique_words < len(words):
    if words[i] in stop:
        words.remove(words[i])
    else:
        unique_words += 1
return unique_words
</code>```

I keep getting the following error:

uniqueWords('bush_all.txt')
              Traceback (most recent call last):
                 File "", line 1, in
                  uniqueWords('bush_all.txt')
                File "/Users/sarahloughran/Documents/CSCI 203/final                   project/countWords.py", line 12, in uniqueWords
          stop = fileS.split()
      AttributeError: '_io.TextIOWrapper' object has no attribute 'split'

Everywhere that I have looked has told me to use the file.split() function so I'm not sure why this error is occurring. Any help would be greatly appreciated thank you!

答:
If you read a file, you first have to go through all the lines before you can split the lines into idividual words. You can use listcomprehension like this

```<code>stop = [word for line in fileS.readlines() for word in line.split()]
words = [word for line in fileIn.readlines() for word in line.split()]
</code>```

The rest of the code looks fine.

Body:
My assignment is to take in State of the Union addresses by President Bush and President Obama and to figure out the number of unique words (or vocabulary size) and the top 20 most frequently used words. I am on the first stage of counting the number of unique words and have this so far:

    def uniqueWords(fileName):
fileIn = open(fileName, 'rt', encoding = 'UTF-8')
fileS = open('stopwords.txt', 'rt', encoding = 'UTF-8')
stop = fileS.split()
words = fileIn.split()
for x in range(len(words)):
    words[x] = words[x].lower()
    for z in words[x]:
        if z in '~!@#$%^&*()+=_:;,./\?"{}[]<>|':
            words[x] = words[x].replace(z, '')

unique_words = 0
while unique_words < len(words):
    if words[i] in stop:
        words.remove(words[i])
    else:
        unique_words += 1
return unique_words

I keep getting the following error:

uniqueWords('bush_all.txt')
              Traceback (most recent call last):
                 File "", line 1, in
                  uniqueWords('bush_all.txt')
                File "/Users/sarahloughran/Documents/CSCI 203/final                   project/countWords.py", line 12, in uniqueWords
          stop = fileS.split()
      AttributeError: '_io.TextIOWrapper' object has no attribute 'split'

Everywhere that I have looked has told me to use the file.split() function so I'm not sure why this error is occurring. Any help would be greatly appreciated thank you!

Body:
If you read a file, you first have to go through all the lines before you can split the lines into idividual words. You can use listcomprehension like this

stop = [word for line in fileS.readlines() for word in line.split()]
words = [word for line in fileIn.readlines() for word in line.split()]

The rest of the code looks fine.