答:
Point 1:

Do not use function(){} in any of your callbacks. Assuming you are using Typescript (or ES6 for that matter), you are not using lexical this. All of your this will have a reference to the inner scope. You will get lots of undefined. Use fat arrow notations ()=>{}.

Point 2:

Since you are already using Observables in all of your methods, continue to use them (reactive programming) and stay away from using Promise unless necessary.

In your getfromgraphql() method, simply use a flatMap(). It is the same as .then() in promise.

Also, in resolving the error, simply do a .catch() if needed. Observables will propagate the error to the highest caller.

```<code>checkAccessTokenValidity() {
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    let options = new RequestOptions({headers: headers});
    return this.http.post(this.URL + 'oauth/token', this.authentication, options)
        .map(response => {
            this.authObj = response.json();
            this.expirationDate = new Date();
            this.expirationDate.setSeconds(this.expirationDate.getSeconds() + this.authObj.expires_in);
            console.log(this.authObj, this.expirationDate);
        })
        .catch(error=>{
            console.log(error);
            return Observable.empty();
        })
}

getfromgraphql() {
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    // headers.append('Authorization', 'Bearer ' + this.access_token );
    let options = new RequestOptions({headers: headers});

    return this.checkAccessTokenValidity().flatMap(()=>{
        console.log('in then');
        //noinspection TypeScriptValidateTypes
        return this.http.post(this.URL + '/api/v1/graphql', this.query, options);
    })
}
</code>```

Title: http call not triggering in promise callback angular 2

Body:
In my angular 2 project I make this call to get some data:

this.http.getfromgraphql()
      .map((response: Response) => response.json())
      .subscribe(
        (data) => {
          console.log(data);
        });

This triggers the getfromgraphql function shown below, before I make that call though, I have to check if the access token is still valid in checkaccesstokenvalidity, there I set some variables and resolve the function.

the console logs 'in then' but my http post does not trigger.

Why is that?

Also, I am sure there is a better way to do this, but for the life of me I can't figure it out, a better solution is much appreciated

checkAccessTokenValidity() {
    let headers = new Headers();
    headers.append( 'Content-Type', 'application/x-www-form-urlencoded' );
    let options = new RequestOptions({ headers: headers });
    // if(!this.access_token) {
    return new Promise((resolve, reject) => {
      this.http.post(this.URL + 'oauth/token', this.authentication, options)
        .subscribe(function(response) {
            this.authObj = response.json();
            this.expirationDate = new Date();
            this.expirationDate.setSeconds(this.expirationDate.getSeconds() + this.authObj.expires_in);
            console.log(this.authObj, this.expirationDate);
          },
          error => console.log("Error: ", error),
          function() {
            console.log('resolving');
            resolve();
          });

    });
    // }
  }
  getfromgraphql() {
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    // headers.append('Authorization', 'Bearer ' + this.access_token );
    let options = new RequestOptions({ headers: headers });

    this.checkAccessTokenValidity().then(function() {
      console.log('in then');
      //noinspection TypeScriptValidateTypes
      return this.http.post(this.URL + '/api/v1/graphql', this.query, options);
    });
  }

Body:
Point 1:

Do not use function(){} in any of your callbacks. Assuming you are using Typescript (or ES6 for that matter), you are not using lexical this. All of your this will have a reference to the inner scope. You will get lots of undefined. Use fat arrow notations ()=>{}.

Point 2:

Since you are already using Observables in all of your methods, continue to use them (reactive programming) and stay away from using Promise unless necessary.

In your getfromgraphql() method, simply use a flatMap(). It is the same as .then() in promise.

Also, in resolving the error, simply do a .catch() if needed. Observables will propagate the error to the highest caller.

checkAccessTokenValidity() {
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    let options = new RequestOptions({headers: headers});
    return this.http.post(this.URL + 'oauth/token', this.authentication, options)
        .map(response => {
            this.authObj = response.json();
            this.expirationDate = new Date();
            this.expirationDate.setSeconds(this.expirationDate.getSeconds() + this.authObj.expires_in);
            console.log(this.authObj, this.expirationDate);
        })
        .catch(error=>{
            console.log(error);
            return Observable.empty();
        })
}

getfromgraphql() {
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    // headers.append('Authorization', 'Bearer ' + this.access_token );
    let options = new RequestOptions({headers: headers});

    return this.checkAccessTokenValidity().flatMap(()=>{
        console.log('in then');
        //noinspection TypeScriptValidateTypes
        return this.http.post(this.URL + '/api/v1/graphql', this.query, options);
    })
}


来源: stackexchange

问:
PHP MySQL : How to add data written into PHP into Mysql database
So ive got a little webserver going on with a phone-book.
You can click on "add a new member", but when you fill in everything from the web server and click on "save" the new row is not showing up in the show-phone-book file.
I translated it, but the files and comments and in german.

I don't think there is anything more needed than this file, adding new member.

When i execute it, i can fill everything in, click "save" , then it dies and i get to the error : Anfrage fehlgeschlagen.

```<code><?php

if ( $_GET['aktion'] == "speichern" )
{
$Nachname     = $_GET['Nachname'];
$Vorname      = $_GET['Vorname'];
$Anrede       = $_GET['Anrede'];
$Geburtsdatum = $_GET['Geburtsdatum'];
$Telefonnummer= $_GET['Telefonnummer'];
$Email        = $_GET['Email'];

$sql = "INSERT INTO Adressbuch SET ";
$sql .= " Nachname          = '$Nachname', ";
$sql .= " Vorname           = '$Vorname', ";
$sql .= " Anrede            = '$Anrede', ";
$sql .= " Geburtsdatum      = '$Geburtsdatum', ";
$sql .= " Telefonnummer     = '$Telefonnummer',";
$sql .= " Email             = '$Email'";

require_once ('konfiguration.php');
$db_erg = mysqli_query($db_con, $sql)
    or die(" Anfrage fehlgeschlagen");

exit;
}
?>

<form name="" action="" method="GET" enctype="text/html">
<p>Bitte geben Sie die Informationen von Ihrem neuen Kontakt ein<br>
</p>
<p>Nachname:<br>
<input type="text" name="Nachname" value="" size="60">
</p>

<p>Vorname:<br>
<input type="text" name="Vorname" value="" size="60">
</p>

<p>Anrede:<br>
<input type="radio" name="Anrede" value="w"> Frau
<input type="radio" name="Anrede" value="m"> Herr
</p>

<p>Geburtsdatum (YYYY-MM-DD):<br>
<input type="date" name="Geburtsdatum" value="" size="10">
</p>

<p>Telefonnummer:<br>
<input type="text" name="Telefonnummer" value="" size="60">
</p>

<p>E-Mail:<br>
<input type="text" name="Email" value="" size="60">
</p>

<input type="hidden" name="aktion" value="speichern">

<input type="Submit" name="" value="speichern">
</form>
</code>```

答:
You can try using following method.    </p>

```<code>mysqli_query($db_con,$sql) or mysqli_error($db_con);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So ive got a little webserver going on with a phone-book.
You can click on "add a new member", but when you fill in everything from the web server and click on "save" the new row is not showing up in the show-phone-book file.
I translated it, but the files and comments and in german.

I don't think there is anything more needed than this file, adding new member.

When i execute it, i can fill everything in, click "save" , then it dies and i get to the error : Anfrage fehlgeschlagen.

<?php

if ( $_GET['aktion'] == "speichern" )
{
$Nachname     = $_GET['Nachname'];
$Vorname      = $_GET['Vorname'];
$Anrede       = $_GET['Anrede'];
$Geburtsdatum = $_GET['Geburtsdatum'];
$Telefonnummer= $_GET['Telefonnummer'];
$Email        = $_GET['Email'];

$sql = "INSERT INTO Adressbuch SET ";
$sql .= " Nachname          = '$Nachname', ";
$sql .= " Vorname           = '$Vorname', ";
$sql .= " Anrede            = '$Anrede', ";
$sql .= " Geburtsdatum      = '$Geburtsdatum', ";
$sql .= " Telefonnummer     = '$Telefonnummer',";
$sql .= " Email             = '$Email'";

require_once ('konfiguration.php');
$db_erg = mysqli_query($db_con, $sql)
    or die(" Anfrage fehlgeschlagen");

exit;
}
?>

<form name="" action="" method="GET" enctype="text/html">

Bitte geben Sie die Informationen von Ihrem neuen Kontakt ein

Nachname:

<input type="text" name="Nachname" value="" size="60">

Vorname:

<input type="text" name="Vorname" value="" size="60">

Anrede:

<input type="radio" name="Anrede" value="w"> Frau
<input type="radio" name="Anrede" value="m"> Herr

Geburtsdatum (YYYY-MM-DD):

<input type="date" name="Geburtsdatum" value="" size="10">

Telefonnummer:

<input type="text" name="Telefonnummer" value="" size="60">

E-Mail:

<input type="text" name="Email" value="" size="60">

<input type="hidden" name="aktion" value="speichern">

<input type="Submit" name="" value="speichern">
</form>

Body:
You can try using following method.

mysqli_query($db_con,$sql) or mysqli_error($db_con);


问:
How to monitor Apache Camel status?
I have already working Camel configuration that is watching a database table (through spring and hibernate), and when something shows up in DB, Camel consumes it and sends message to JMS broker.

This works flawlessly. And is built in DSL in MyOwnMessageRouteBuilder.configure()

Now I'd like to add monitoring that do something if no new data shows up in DB in given (like 3h) time. Is that possible in Camel at all? I can see callbacks like onCompletion or onException, but nothing like onIdle()....

Best regards

答:
You may look at BAM
http://camel.apache.org/bam

However usually some monitoring tooling may already be able to do this, and thus you may be able to find a generic solution.

ContentLicense: CC BY-SA 2.5

Title: How to monitor Apache Camel status?


问:
How do I optimize filtering in AngularJS?
I have here a filter for AngularJS. Is there any better way for this?</p>

```<code> return function (data, selected) {
        var result = [];
        if (selected[0] == 'All Types') {
            result = data;
        }
        else {
            for (var i = 0; i < data.length; i++) {
                for (var j = 0; j < selected.length; j++) {
                    if (data[i].Type == selected[j]) {
                        result.push(data[i]);
                    }
                }
            }
        }

        return result;
    };
</code>```

答:
Use data for selected value. I am assuming selected value is in data[i].selected.

```<code>return function (data) {
    var result = [];
    if (data[0].selected == 'All Types') {
        result = data;
    }
    else {
        for (var i = 0; i < data.length; i++) {
            if (data[i].Type == data[i].selected) {
                result.push(data[i]);
            }
        }
    }
    return result;
};
</code>```

We can use filters

```<code>return function (data) {
    if (data[0].selected == 'All Types') {
        return data;
    }
    else {
        return data.filter(function (item) {
            return item.Type == item.selected;
        });
    }

};
</code>```

Body:
I have here a filter for AngularJS. Is there any better way for this?

 return function (data, selected) {
        var result = [];
        if (selected[0] == 'All Types') {
            result = data;
        }
        else {
            for (var i = 0; i < data.length; i++) {
                for (var j = 0; j < selected.length; j++) {
                    if (data[i].Type == selected[j]) {
                        result.push(data[i]);
                    }
                }
            }
        }

        return result;
    };

Body:
Use data for selected value. I am assuming selected value is in data[i].selected.

return function (data) {
    var result = [];
    if (data[0].selected == 'All Types') {
        result = data;
    }
    else {
        for (var i = 0; i < data.length; i++) {
            if (data[i].Type == data[i].selected) {
                result.push(data[i]);
            }
        }
    }
    return result;
};

We can use filters

return function (data) {
    if (data[0].selected == 'All Types') {
        return data;
    }
    else {
        return data.filter(function (item) {
            return item.Type == item.selected;
        });
    }

};


问:
Change font and font size of CodeLens in Visual Studio Code
I have enabled CodeLens for Visual Studio Code for TypeScript. The question is how I can change font and font size of it?

答:
This is not possible as of VSCode 1.14

We are tracking a feature request for this here: https://github.com/Microsoft/vscode/issues/16038


问:
Developing unit-test for node js using mocha, supertest with async/await functions, but i am getting error "Resolution method is overspecified"
Developing unit-test for NodeJs REST API using mocha, supertest with async/await functions, but i am getting below error,
I am using arrow functions with async and await keywords.

```<code>Error: Resolution method is overspecified.
</code>```

So someone could help me out here?

答:
This happens because the async function by default returns a promise and you call the done function manually as well which confuses Mocha as to when the test is actually finished. Please see the issue here. A quick-and-dirty solution would be to wrap the async function in another, not async function like this:

it("should work", done => {
  (async () => {
    await something;
    done();
  })();
});
```

But the better way would be to compose promises in such a way that the returned from the async function promise resolves in the right moment of time and not to call the done callback manually at all.

Body:
Developing unit-test for NodeJs REST API using mocha, supertest with async/await functions, but i am getting below error,
I am using arrow functions with async and await keywords.

Error: Resolution method is overspecified.

So someone could help me out here?

Body:
This happens because the async function by default returns a promise and you call the done function manually as well which confuses Mocha as to when the test is actually finished. Please see the issue here. A quick-and-dirty solution would be to wrap the async function in another, not async function like this:

it("should work", done => {
  (async () => {
    await something;
    done();
  })();
});

But the better way would be to compose promises in such a way that the returned from the async function promise resolves in the right moment of time and not to call the done callback manually at all.


问:
Multiline non terminated regex
I came across a problem with regex parsing columns in ASCII tables.

Imagine an ASCII table like:

```<code>COL1  | COL2    | COL3
======================
ONE   | APPLE   | PIE
----------------------
TWO   | APPLE   | PIES
----------------------
THREE | PLUM-   | PIES
      | APRICOT |
</code>```

For the first 2 entries a trivial capture regex does the deal

```<code>(?:(?<COL1>\w+)\s*\|\s*(?<COL2>\w+)\s*\|\s*(?<COL3>\w+)\s*)
</code>```

However this regex captures the header, as well as it doesn't capture the 3rd line.

I can't solve following two problems :

How to exclude the header?

How to extend the COL2 capture group to capture the multiline entry PLUM-APRICOT?

Thanks for your help!

答:
Some people, when confronted with a problem, think
  “I know, I'll use regular expressions.”   Now they have two problems. (http://regex.info/blog/2006-09-15/247)

I've assumed an input string like:

```<code>String input = ""
            + "\n" + "COL1  | COL2    | COL3"
            + "\n" + "======================"
            + "\n" + "ONE   | APPLE   | PIE "
            + "\n" + "----------------------"
            + "\n" + "TWO   | APPLE   | PIES"
            + "\n" + "----------------------"
            + "\n" + "THREE | PLUM-   | PIES"
            + "\n" + "      | APRICOT |     ";
</code>```

To split the header and the table you can use input.split("={2,}"). This returns an array of strings of the header and the table.

After trimming the table you can use table.split("-{2,}") to get the rows of the table.

All rows can be converted to arrays of cells by using row.split("\\|").

Dealing with multiline rows: Before converting the rows to cells, you can call row.split("\n") to split multiline rows.
When this split operations returns an array with more than one element, they should be split on pipes (split("\\|")) and the resulting cells should be merged.

From here its just element manipulation to get it into the format you desire.

Title: Multiline non terminated regex

Body:
I came across a problem with regex parsing columns in ASCII tables.

Imagine an ASCII table like:

COL1  | COL2    | COL3
======================
ONE   | APPLE   | PIE
----------------------
TWO   | APPLE   | PIES
----------------------
THREE | PLUM-   | PIES
      | APRICOT |

For the first 2 entries a trivial capture regex does the deal

(?:(?<COL1>\w+)\s*\|\s*(?<COL2>\w+)\s*\|\s*(?<COL3>\w+)\s*)

However this regex captures the header, as well as it doesn't capture the 3rd line.

I can't solve following two problems :

How to exclude the header?

How to extend the COL2 capture group to capture the multiline entry PLUM-APRICOT?

Thanks for your help!

Body:
Some people, when confronted with a problem, think
  “I know, I'll use regular expressions.”   Now they have two problems. (http://regex.info/blog/2006-09-15/247)

I've assumed an input string like:

String input = ""
            + "\n" + "COL1  | COL2    | COL3"
            + "\n" + "======================"
            + "\n" + "ONE   | APPLE   | PIE "
            + "\n" + "----------------------"
            + "\n" + "TWO   | APPLE   | PIES"
            + "\n" + "----------------------"
            + "\n" + "THREE | PLUM-   | PIES"
            + "\n" + "      | APRICOT |     ";

To split the header and the table you can use input.split("={2,}"). This returns an array of strings of the header and the table.

After trimming the table you can use table.split("-{2,}") to get the rows of the table.

All rows can be converted to arrays of cells by using row.split("\\|").

Dealing with multiline rows: Before converting the rows to cells, you can call row.split("\n") to split multiline rows.
When this split operations returns an array with more than one element, they should be split on pipes (split("\\|")) and the resulting cells should be merged.

From here its just element manipulation to get it into the format you desire.


问:
http call not triggering in promise callback angular 2
In my angular 2 project I make this call to get some data:

```<code>this.http.getfromgraphql()
      .map((response: Response) => response.json())
      .subscribe(
        (data) => {
          console.log(data);
        });
</code>```

This triggers the getfromgraphql function shown below, before I make that call though, I have to check if the access token is still valid in checkaccesstokenvalidity, there I set some variables and resolve the function.

the console logs 'in then' but my http post does not trigger.

Why is that?

Also, I am sure there is a better way to do this, but for the life of me I can't figure it out, a better solution is much appreciated

```<code>checkAccessTokenValidity() {
    let headers = new Headers();
    headers.append( 'Content-Type', 'application/x-www-form-urlencoded' );
    let options = new RequestOptions({ headers: headers });
    // if(!this.access_token) {
    return new Promise((resolve, reject) => {
      this.http.post(this.URL + 'oauth/token', this.authentication, options)
        .subscribe(function(response) {
            this.authObj = response.json();
            this.expirationDate = new Date();
            this.expirationDate.setSeconds(this.expirationDate.getSeconds() + this.authObj.expires_in);
            console.log(this.authObj, this.expirationDate);
          },
          error => console.log("Error: ", error),
          function() {
            console.log('resolving');
            resolve();
          });

    });
    // }
  }
  getfromgraphql() {
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    // headers.append('Authorization', 'Bearer ' + this.access_token );
    let options = new RequestOptions({ headers: headers });

    this.checkAccessTokenValidity().then(function() {
      console.log('in then');
      //noinspection TypeScriptValidateTypes
      return this.http.post(this.URL + '/api/v1/graphql', this.query, options);
    });
  }
</code>```

答:
Use this

```<code>return this.http.post(this.heroesUrl, { name }, options)
       .toPromise()
</code>```

or add a resolve() in your subscribe

```<code> .subscribe(function(response) {
        this.authObj = response.json();
        this.expirationDate = new Date();
        this.expirationDate.setSeconds(this.expirationDate.getSeconds() +
        this.authObj.expires_in);
        console.log(this.authObj, this.expirationDate);
        resolve();
      },
</code>```

and instead of resolve in error you can use reject() in your error body

following plunker will help you
https://embed.plnkr.co/?show=preview
check for hero.service.promise.ts in app/toh folder

Body:
Use this

return this.http.post(this.heroesUrl, { name }, options)
       .toPromise()

or add a resolve() in your subscribe

 .subscribe(function(response) {
        this.authObj = response.json();
        this.expirationDate = new Date();
        this.expirationDate.setSeconds(this.expirationDate.getSeconds() +
        this.authObj.expires_in);
        console.log(this.authObj, this.expirationDate);
        resolve();
      },

and instead of resolve in error you can use reject() in your error body

following plunker will help you
https://embed.plnkr.co/?show=preview
check for hero.service.promise.ts in app/toh folder


问:
How to create custom java library and call its function inside Android App
I am new to java and android development and I want to create my own java library (JAR files) and I want to call this jar lib function inside android app code base.

Although there are numerous online tutorials available which demonstrate how to do this I couldnt find one for a newbee person like me.

The resources available on the internet, assume that a person should be hands on java and android platform. This is not the case with me.

I have just started learning it and I want to create a java library and call its function into an Android App.

So to achieve this, below are the steps I have performed.

Step 1 : Created a sample program "Addition of 2 numbers" so this is what I have written.

```<code> package MyPackage;
 import java.io.*;
 import java.net.*;

 public class MyAddition {
    public static int addition(int a, int b){
       return (a+b);
    }
 }
</code>```

Saved it as MyAddition.java .Compiled and created its  class file MyAddition.class inside folder [folder_path]..../mylib/MyPackage/

Steps 2 : Created its JAR files using following command

```<code>   jar -cf mylib.jar [folder_path]../mylib
</code>```

Steps 3 :

Now I have installed Android Studio in order to create my android app code base where I want to call this JAR lib function.

In Android Studio, I have created a new project using its predefined "bottom Navigation activity"  as "My Application" so the whole project is set up by the Android Studio. Here is a screenshot for the whole setup.

Step 4 : : I have my complete application set up which looks like this.

Step 5 : : Now I want to integrate my JAR file which I've created earlier into this app. So to achieve this I've added the jar lib "mylib.jar" inside apps/libs folder like this.

Step 6 : : After doing all this, I am adding following line into the build.gradle file
     compile files 'libs/mylib.jar'

and then sync.

After Adding the Jar, I am calling its function inside Android App Function
but in this case its showing me error "can not resolve the MyPackage", where as it shows me this inside the application scope

Now I could not proceed further in order to include and call jar files function.

Any help is appreciated .

答:
Try Android Archive (AAR) file rather than Jar. This is very effective library type for android </p>

<p>Check here for more info </p>

Body:
I am new to java and android development and I want to create my own java library (JAR files) and I want to call this jar lib function inside android app code base.

Although there are numerous online tutorials available which demonstrate how to do this I couldnt find one for a newbee person like me.

The resources available on the internet, assume that a person should be hands on java and android platform. This is not the case with me.

I have just started learning it and I want to create a java library and call its function into an Android App.

So to achieve this, below are the steps I have performed.

Step 1 : Created a sample program "Addition of 2 numbers" so this is what I have written.

 package MyPackage;
 import java.io.*;
 import java.net.*;

 public class MyAddition {
    public static int addition(int a, int b){
       return (a+b);
    }
 }

Saved it as MyAddition.java .Compiled and created its  class file MyAddition.class inside folder [folder_path]..../mylib/MyPackage/

Steps 2 : Created its JAR files using following command

   jar -cf mylib.jar [folder_path]../mylib

Steps 3 :

Now I have installed Android Studio in order to create my android app code base where I want to call this JAR lib function.

In Android Studio, I have created a new project using its predefined "bottom Navigation activity"  as "My Application" so the whole project is set up by the Android Studio. Here is a screenshot for the whole setup.

Step 4 : : I have my complete application set up which looks like this.

Step 5 : : Now I want to integrate my JAR file which I've created earlier into this app. So to achieve this I've added the jar lib "mylib.jar" inside apps/libs folder like this.

Step 6 : : After doing all this, I am adding following line into the build.gradle file
     compile files 'libs/mylib.jar'

and then sync.

After Adding the Jar, I am calling its function inside Android App Function
but in this case its showing me error "can not resolve the MyPackage", where as it shows me this inside the application scope

Now I could not proceed further in order to include and call jar files function.

Any help is appreciated .

Body:
Try Android Archive (AAR) file rather than Jar. This is very effective library type for android

Check here for more info


问:
C and OpenMP: pointer to shared read-only data slows down execution
This is my situation, I have an array of pointers that point to arrays of some data... Let's say:

```<code>    Data** array = malloc ( 100 * sizeof(Data*));
    for(i = 0; i < 100; i++) array[i] = malloc (20 * sizeof(Data);
</code>```

Inside a parallel region, I make some operations that use that data. For instance:

```<code>    #pragma omp parallel num_threads(4) firstprivate(array)
    {
         function(array[0], array[omp_get_thread_num()];
    }
</code>```

The first parameter is read-only but is the same along all threads...

The problem is that if I use as the first parameter a diferent block of data, i.e.: array[omp_get_thread_num()+1], each function lasts 1seg. But when I use the same block of data, array[0], each function call lasts 4segs.

My theory is that there is no way to know if the array[0] will be changed or not by the funciton so each thread asks for a copy and invalidate the copies that other threads have and that should explain the delay...

I tried to make a local copy of array[0] like this:

```<code>    #pragma omp parallel num_threads(4) firstprivate(array)
    {
        Data* tempData = malloc(20 * sizeof(Data));
        memcpy(tempData,array[0], 20*sizeof(Data));

        function(tempData, array[omp_get_thread_num()];
    }
</code>```

But I get the same result... It's like the thread doesn't 'release' the Data block so other threads could use it...

I have to note that the first parameter is not always array[0] so I can't use firstprivate(array[0]) in the pragma line...

Questions are:

Am I doing something wrong?

Is there a way to 'release' a shared block of memory so other threads
could use it?

It was very difficult try to make me understand so if you need further information, please let me know!

Thanks in advance... Javier

EDIT: I can't change the function declaration because it comes inside a library! (ACML)

答:
I think you are wrong in your analysis. If the data is not changed, imho it will not be synchronized between cores. There are two probable reasons for the slowing down.

The core #0 gets function(array[0], array[0]). You said that first parameter is read-only, but the second is not. So core #0 will change the data in array[0] and the CPU will have to synchronize this data between the cores all the time.

The second possible reason is the small size of your arrays (20 elements). What happens is that the core #1 gets a pointer to the 20-element array, and core #2 gets the pointer to array, which is probably right after the array #1 in memory. Thus there is a high probability that they lie on the same cache line. The CPU does not track changing each particular element - if it sees that elements on the same cache line are changed, it will synchronize the cache between the cores. Solution is to make each array bigger (so that after 20 elements you have unused space equal to cache size (128K? 256K?))

My guess that you have both, #1 and #2 problems in your code.

Body:
This is my situation, I have an array of pointers that point to arrays of some data... Let's say:

    Data** array = malloc ( 100 * sizeof(Data*));
    for(i = 0; i < 100; i++) array[i] = malloc (20 * sizeof(Data);

Inside a parallel region, I make some operations that use that data. For instance:

    #pragma omp parallel num_threads(4) firstprivate(array)
    {
         function(array[0], array[omp_get_thread_num()];
    }

The first parameter is read-only but is the same along all threads...

The problem is that if I use as the first parameter a diferent block of data, i.e.: array[omp_get_thread_num()+1], each function lasts 1seg. But when I use the same block of data, array[0], each function call lasts 4segs.

My theory is that there is no way to know if the array[0] will be changed or not by the funciton so each thread asks for a copy and invalidate the copies that other threads have and that should explain the delay...

I tried to make a local copy of array[0] like this:

    #pragma omp parallel num_threads(4) firstprivate(array)
    {
        Data* tempData = malloc(20 * sizeof(Data));
        memcpy(tempData,array[0], 20*sizeof(Data));

        function(tempData, array[omp_get_thread_num()];
    }

But I get the same result... It's like the thread doesn't 'release' the Data block so other threads could use it...

I have to note that the first parameter is not always array[0] so I can't use firstprivate(array[0]) in the pragma line...

Questions are:

Am I doing something wrong?

Is there a way to 'release' a shared block of memory so other threads
could use it?

It was very difficult try to make me understand so if you need further information, please let me know!

Thanks in advance... Javier

EDIT: I can't change the function declaration because it comes inside a library! (ACML)


问:
Learning TypeScript - Casting Types
I'm new to TypeScript and I'm playing around with the various language features. Below is a code sample I've been working on during one of the many online courses.

I'm having issues getting inheritence and overloading to work properly.
throughout the code I make use of a car which is of base class Auto, and a truck which is off child class Truck.

I'm trying to see if it is possible to cast the car as a Truck and access the specialized function HonkHorn.
Also I'm trying to cast a truck back to an Auto and access the base function for WriteDetails.

In both cases it seems the objects stay of their original type. So typecast4.HonkHorn(); generates a runtime error:

Uncaught TypeError: typecast4.HonkHorn is not a function.

Trying to cast back Truck to Auto will always result in the specialized override for WriteDetails to be called. The casting code is all the way at the bottom of the sample.

Can someone please help me understand why this is happening?

Thanks in advance!

```<code>// defines the structure of auto options
interface IAutoOptions{
    engine: Engine,
    color: string,
    price: number,
    year: number
}

// extends autooptions with truck specific options
interface ITruckOptions extends IAutoOptions{
    fourbyfour: boolean,
    bedlength: string
}

// defines the structure of engines
interface IEngine {
    enginetype: string;
    horsepower: number;
    hydraulicpump?: string
    start(warmuptime: number, callback: () => void): void;
    stop(): void;
}

// the engine class must implement the members as specified in the IEngine interface
class Engine implements IEngine{
    enginetype: string;
    horsepower: number;
    hydraulicpump?: string; //optional hydraulic parameter
    constructor(enginetype: string, horsepower: number, hydraulicpump? : string ) {
        this.enginetype = enginetype;
        this.horsepower = horsepower;
        if (!(hydraulicpump)){
            hydraulicpump = "Not Available"; //if no hydraulic parameter is provided we set it to "Not Available"
        }
        this.hydraulicpump = hydraulicpump;
    }
    // start requires a callback parameter which accepts a specialized callback object/function that accepts and returns nothing
    // by accepting a callback object/function that code can be seperated off, which makes this class much cleaner and organized
    start(warmuptime: number, callback: () => void) {
        window.setTimeout(() => {
            callback();
            document.write(this.enginetype + " has started!" + "</br>");
        }, warmuptime);
    };
    stop() {
        document.write(this.enginetype + " has stopped!" + "</br>");
    };
}

// base class for autos
class Auto {
    engine: Engine;
    color: string;
    price: number;
    year: number;

    constructor(options: IAutoOptions) {
        this.engine = options.engine;
        this.color = options.color;
        this.price = options.price;
        this.year = options.year;
    }

    //WriteDetails contains the base details for each Auto which can be overriden in specialized classes
    WriteDetails() {
        document.write("Color: " + this.color + "</br>");
        document.write("Year: " + this.year + "</br>");
        document.write("Price: $"  + this.price + "</br>");
        document.write("Engine Type: " + this.engine.enginetype + "</br>");
        document.write("Horse Power: " + this.engine.horsepower + "</br>");
        document.write("Hydraulic Pump: " + this.engine.hydraulicpump + "</br>");
    };
}

// Truck extends Auto to add Truck specific fields and function overloads
// Note that it does not contains all the base fields from Auto thus making it much smaller and cleaner
// Only truck specific code is added.
class Truck extends Auto{
    fourbyfour: boolean;
    bedlength: string;
    constructor(options: ITruckOptions) {
        // to overload the constructor super() must to be called, which calls the base class constructor in Auto
        super(options);
        this.bedlength = options.bedlength;
        this.fourbyfour = options.fourbyfour;
    }
    // WriteDetails overrides the Auto WriteDetails, but first calls the base WriteDetails function
    WriteDetails() {
        super.WriteDetails();
        document.write("Bed Length: " + this.bedlength + "</br>");
        document.write("4x4 : " + this.fourbyfour + "</br>");
    };

    HonkHorn() {
        document.write("Honk Honk!</br>");
    }
}

// below is one of the notations to define a callback object that can be used to call
// the start function on the Engine class
// this callback function has encapsulated car specific logic for starting the engine
// much cleaner than putting the specialized code in the Auto class

var CarEngineStart = () => {
    document.write("<h1>Starting Car</h1>");
    document.write("Check Tires!" + "</br>");
    document.write("Fasten Seatbelts!" + "</br>");
    document.write("Check Mirrors!" + "</br>");
    document.write("Starting Engine!" + "</br>");
};

// yet another way to define a callback object (function)
// this callback function has encapsulated truck specific logic for starting the engine
// much cleaner than putting the specialized code in the Auto or Truck classes

function TruckEngineStart() {
    document.write("<h1>Starting Truck</h1>");
    document.write("Check Tires!" + "</br>");
    document.write("Check if load is properly fastened!" + "</br>");
    document.write("Check timesheet!" + "</br>");
    document.write("Fasten Seatbelts!" + "</br>");
    document.write("Check Mirrors!" + "</br>");
    document.write("Starting Engine!" + "</br>");
}

// ###################### Start logic

// creating an engine
var carengine = new Engine("V8", 300);
// creating another engine, but now providing the optional hydraulicpump parameter
var truckengine = new Engine("V12", 1000, "Flexpump 3000");

var car = new Auto({
    engine: carengine,
    color: 'Blue',
    price: 20000,
    year: 2017
});

var truck = new Truck({
    engine: truckengine,
    color: 'Red',
    price: 80000,
    year: 2015,
    bedlength: 'Long Bed',
    fourbyfour: true
});
document.write("<h1>Car Details</h1>");
car.WriteDetails();

document.write("<h1>Truck Details</h1>");
truck.WriteDetails();

truck.engine.start(10000, TruckEngineStart);
car.engine.start(5000, CarEngineStart);

window.setTimeout(() => {
    document.write("<h1>Stopping Car</h1>");
    car.engine.stop();
    document.write("<h1>Stopping Truck</h1>");
    truck.engine.stop();
}, 15000);

document.write("<h1>Casting Autos</h1>");
document.write("<h2>Auto WriteDetails for Car</h2>");
var typecast: Auto;
typecast = car;
typecast.WriteDetails();
document.write("<h2>Truck WriteDetails for Car with type cast</h2>");
var typecast4: Truck;
typecast4 = <Truck>car;
typecast4.HonkHorn();
typecast4.WriteDetails();
document.write("<h2>Auto WriteDetails for Truck without type cast</h2>");
var typecast2: Auto;
typecast2 = truck;
typecast2.WriteDetails();
document.write("<h2>Auto WriteDetails for Truck with type cast</h2>");
var typecast3: Auto;
typecast3 = <Auto>truck;
typecast3.WriteDetails();
</code>```

答:
There is no type casting in Typescript, but only type assertions. This is for type checking and it won't influence runtime behavior.

For example, the type assertion:

```<code>car as Truck  // older syntax syntax: <Truck> car
</code>```

tells the compiler that the car is of type Truck, but it won't influence the generated JS code.

TypeScript allows you to override its inferred and analyzed view of types in any way you want to. This is done by a mechanism called "type assertion". TypeScript's type assertion is purely you telling the compiler that you know about the types better than it does, and that it should not second guess you.

Type Assertion vs. Casting

The reason why it's not called "type casting" is that casting generally implies some sort of runtime support. However type assertions are purely a compile time construct and a way for you to provide hints to the compiler on how you want your code to be analyzed.

https://basarat.gitbooks.io/typescript/content/docs/types/type-assertion.html

Update:

Another good reference nowadays is the Typescript site itself

Type assertions are a way to tell the compiler “trust me, I know what I’m doing.” A type assertion is like a type cast in other languages, but performs no special checking or restructuring of data. It has no runtime impact, and is used purely by the compiler. TypeScript assumes that you, the programmer, have performed any special checks that you need.

For changing the type, these answers here could be useful: How do I cast a JSON Object to a TypeScript class?

ContentLicense: CC BY-SA 4.0

Title: Learning TypeScript - Casting Types

Body:
I'm new to TypeScript and I'm playing around with the various language features. Below is a code sample I've been working on during one of the many online courses.

I'm having issues getting inheritence and overloading to work properly.
throughout the code I make use of a car which is of base class Auto, and a truck which is off child class Truck.

I'm trying to see if it is possible to cast the car as a Truck and access the specialized function HonkHorn.
Also I'm trying to cast a truck back to an Auto and access the base function for WriteDetails.

In both cases it seems the objects stay of their original type. So typecast4.HonkHorn(); generates a runtime error:

Uncaught TypeError: typecast4.HonkHorn is not a function.

Trying to cast back Truck to Auto will always result in the specialized override for WriteDetails to be called. The casting code is all the way at the bottom of the sample.

Can someone please help me understand why this is happening?

Thanks in advance!

// defines the structure of auto options
interface IAutoOptions{
    engine: Engine,
    color: string,
    price: number,
    year: number
}

// extends autooptions with truck specific options
interface ITruckOptions extends IAutoOptions{
    fourbyfour: boolean,
    bedlength: string
}

// defines the structure of engines
interface IEngine {
    enginetype: string;
    horsepower: number;
    hydraulicpump?: string
    start(warmuptime: number, callback: () => void): void;
    stop(): void;
}

// the engine class must implement the members as specified in the IEngine interface
class Engine implements IEngine{
    enginetype: string;
    horsepower: number;
    hydraulicpump?: string; //optional hydraulic parameter
    constructor(enginetype: string, horsepower: number, hydraulicpump? : string ) {
        this.enginetype = enginetype;
        this.horsepower = horsepower;
        if (!(hydraulicpump)){
            hydraulicpump = "Not Available"; //if no hydraulic parameter is provided we set it to "Not Available"
        }
        this.hydraulicpump = hydraulicpump;
    }
    // start requires a callback parameter which accepts a specialized callback object/function that accepts and returns nothing
    // by accepting a callback object/function that code can be seperated off, which makes this class much cleaner and organized
    start(warmuptime: number, callback: () => void) {
        window.setTimeout(() => {
            callback();
            document.write(this.enginetype + " has started!" + "
");
        }, warmuptime);
    };
    stop() {
        document.write(this.enginetype + " has stopped!" + "
");
    };
}

// base class for autos
class Auto {
    engine: Engine;
    color: string;
    price: number;
    year: number;

    constructor(options: IAutoOptions) {
        this.engine = options.engine;
        this.color = options.color;
        this.price = options.price;
        this.year = options.year;
    }

    //WriteDetails contains the base details for each Auto which can be overriden in specialized classes
    WriteDetails() {
        document.write("Color: " + this.color + "
");
        document.write("Year: " + this.year + "
");
        document.write("Price: $"  + this.price + "
");
        document.write("Engine Type: " + this.engine.enginetype + "
");
        document.write("Horse Power: " + this.engine.horsepower + "
");
        document.write("Hydraulic Pump: " + this.engine.hydraulicpump + "
");
    };
}

// Truck extends Auto to add Truck specific fields and function overloads
// Note that it does not contains all the base fields from Auto thus making it much smaller and cleaner
// Only truck specific code is added.
class Truck extends Auto{
    fourbyfour: boolean;
    bedlength: string;
    constructor(options: ITruckOptions) {
        // to overload the constructor super() must to be called, which calls the base class constructor in Auto
        super(options);
        this.bedlength = options.bedlength;
        this.fourbyfour = options.fourbyfour;
    }
    // WriteDetails overrides the Auto WriteDetails, but first calls the base WriteDetails function
    WriteDetails() {
        super.WriteDetails();
        document.write("Bed Length: " + this.bedlength + "
");
        document.write("4x4 : " + this.fourbyfour + "
");
    };

    HonkHorn() {
        document.write("Honk Honk!
");
    }
}

// below is one of the notations to define a callback object that can be used to call
// the start function on the Engine class
// this callback function has encapsulated car specific logic for starting the engine
// much cleaner than putting the specialized code in the Auto class

var CarEngineStart = () => {
    document.write("
Starting Car
");
    document.write("Check Tires!" + "
");
    document.write("Fasten Seatbelts!" + "
");
    document.write("Check Mirrors!" + "
");
    document.write("Starting Engine!" + "
");
};

// yet another way to define a callback object (function)
// this callback function has encapsulated truck specific logic for starting the engine
// much cleaner than putting the specialized code in the Auto or Truck classes

function TruckEngineStart() {
    document.write("
Starting Truck
");
    document.write("Check Tires!" + "
");
    document.write("Check if load is properly fastened!" + "
");
    document.write("Check timesheet!" + "
");
    document.write("Fasten Seatbelts!" + "
");
    document.write("Check Mirrors!" + "
");
    document.write("Starting Engine!" + "
");
}

// ###################### Start logic

// creating an engine
var carengine = new Engine("V8", 300);
// creating another engine, but now providing the optional hydraulicpump parameter
var truckengine = new Engine("V12", 1000, "Flexpump 3000");

var car = new Auto({
    engine: carengine,
    color: 'Blue',
    price: 20000,
    year: 2017
});

var truck = new Truck({
    engine: truckengine,
    color: 'Red',
    price: 80000,
    year: 2015,
    bedlength: 'Long Bed',
    fourbyfour: true
});
document.write("
Car Details
");
car.WriteDetails();

document.write("
Truck Details
");
truck.WriteDetails();

truck.engine.start(10000, TruckEngineStart);
car.engine.start(5000, CarEngineStart);

window.setTimeout(() => {
    document.write("
Stopping Car
");
    car.engine.stop();
    document.write("
Stopping Truck
");
    truck.engine.stop();
}, 15000);

document.write("
Casting Autos
");
document.write("
Auto WriteDetails for Car
");
var typecast: Auto;
typecast = car;
typecast.WriteDetails();
document.write("
Truck WriteDetails for Car with type cast
");
var typecast4: Truck;
typecast4 = <Truck>car;
typecast4.HonkHorn();
typecast4.WriteDetails();
document.write("
Auto WriteDetails for Truck without type cast
");
var typecast2: Auto;
typecast2 = truck;
typecast2.WriteDetails();
document.write("
Auto WriteDetails for Truck with type cast
");
var typecast3: Auto;
typecast3 = <Auto>truck;
typecast3.WriteDetails();

Body:
There is no type casting in Typescript, but only type assertions. This is for type checking and it won't influence runtime behavior.

For example, the type assertion:

car as Truck  // older syntax syntax: <Truck> car

tells the compiler that the car is of type Truck, but it won't influence the generated JS code.

TypeScript allows you to override its inferred and analyzed view of types in any way you want to. This is done by a mechanism called "type assertion". TypeScript's type assertion is purely you telling the compiler that you know about the types better than it does, and that it should not second guess you.

Type Assertion vs. Casting

The reason why it's not called "type casting" is that casting generally implies some sort of runtime support. However type assertions are purely a compile time construct and a way for you to provide hints to the compiler on how you want your code to be analyzed.

https://basarat.gitbooks.io/typescript/content/docs/types/type-assertion.html

Update:

Another good reference nowadays is the Typescript site itself

Type assertions are a way to tell the compiler “trust me, I know what I’m doing.” A type assertion is like a type cast in other languages, but performs no special checking or restructuring of data. It has no runtime impact, and is used purely by the compiler. TypeScript assumes that you, the programmer, have performed any special checks that you need.

For changing the type, these answers here could be useful: How do I cast a JSON Object to a TypeScript class?


问:
How to call other REST APIs from your node micro-service and send the result as a response?
I am currently trying to implement a BFF (backend for front end architecture).

Using request-promise library I can successfully hit the other microservice but not able to return the result as a response from BFF microservice.

Each time it is returning this result Promise { pending } pending state, could somebody please help me out on this?

My main issue is to know how to receive data into BFF microservice from the other microservice that we are hitting and returning the result from microservice which is hitting other one.

Or if somebody could help me to let know how to access the result from inside .then of any promise?

The flow is like this:

```<code>client(ios/android)===(sends request)==>BFF Microservice==>BP microservice
</code>```

(BFF Microservice handles the request and returns the response on the basis of result received from other microservice)

Microservice code which is calling another microservice:

```<code>import yagmodel from '../../lib/models/yag-model'
import {errorsList} from '../../lib/errors/errorsList'
import request from 'request-promise'
import config from 'config'

//template below to call the REST APIs of other microservices.

export async function getAllBP (req,res) {
    let yagresponse// this varaible is defined to get data from inside(rs.then )

    const username= req.swagger.params.username.value
    const authheader= req.swagger.params.Authorization.value
    console.log("Authorization:"+authheader)

    let rs= await yagmodel.bp(username,authheader)
    console.log(rs)

    rs.then((response)=>{
        // console.log(response.body)
        yagresponse=response.body
        //console.log(rsp)
    }).catch((err)=>{
        console.log(err)
        console.log('errorstatuscode:'+err.statusCode)
    })

    res.status(200).send(yagresponse)
}
</code>```

yag-model.js code:

```<code>import {errorsList} from '../../lib/errors/errorsList'
import request from 'request-promise'

module.exports.bp = async function getBP(username,authheader){
    const options={
        uri: `http://localhost:4000/Health/BP/`+username,
        json: true,
        resolveWithFullResponse: true,
        headers: {
            'Content-Type': 'application/json; charset=utf-8',
            'Accept': 'application/json; charset=utf-8',
            'Authorization':authheader
        },
        method: 'GET'
    }

    return request(options).then ((response)=>{
        return response.body
    }).catch((err)=>{
        console.log(err)
        console.log('errorstatuscode:'+err.statusCode)
    })
}
</code>```

答:
Please don't confuse between promises returned from request-promise and async functions.
async functions can be awaited to get a resolved promise and make your code look good.

I believe in letting people resolve their own problems and just guiding them along the way so just to make sure, aren't you getting the return from the resolved promise in this line of yours:

```<code>console.log(rs)
</code>```

Moreover, by looking at your snippet, you're returning a response.body from within request-promise's thenable. You cannot catch any response errors from the response body, right?

I'd strongly suggest following a pattern wherein you'd catch errors (where you should) and display proper messages when you do. Wrapping your await call in a try/catch can help catch uncaught errors from request-promise.

Peace!

Body:
I am currently trying to implement a BFF (backend for front end architecture).

Using request-promise library I can successfully hit the other microservice but not able to return the result as a response from BFF microservice.

Each time it is returning this result Promise { pending } pending state, could somebody please help me out on this?

My main issue is to know how to receive data into BFF microservice from the other microservice that we are hitting and returning the result from microservice which is hitting other one.

Or if somebody could help me to let know how to access the result from inside .then of any promise?

The flow is like this:

client(ios/android)===(sends request)==>BFF Microservice==>BP microservice

(BFF Microservice handles the request and returns the response on the basis of result received from other microservice)

Microservice code which is calling another microservice:

import yagmodel from '../../lib/models/yag-model'
import {errorsList} from '../../lib/errors/errorsList'
import request from 'request-promise'
import config from 'config'

//template below to call the REST APIs of other microservices.

export async function getAllBP (req,res) {
    let yagresponse// this varaible is defined to get data from inside(rs.then )

    const username= req.swagger.params.username.value
    const authheader= req.swagger.params.Authorization.value
    console.log("Authorization:"+authheader)

    let rs= await yagmodel.bp(username,authheader)
    console.log(rs)

    rs.then((response)=>{
        // console.log(response.body)
        yagresponse=response.body
        //console.log(rsp)
    }).catch((err)=>{
        console.log(err)
        console.log('errorstatuscode:'+err.statusCode)
    })

    res.status(200).send(yagresponse)
}

yag-model.js code:

import {errorsList} from '../../lib/errors/errorsList'
import request from 'request-promise'

module.exports.bp = async function getBP(username,authheader){
    const options={
        uri: `http://localhost:4000/Health/BP/`+username,
        json: true,
        resolveWithFullResponse: true,
        headers: {
            'Content-Type': 'application/json; charset=utf-8',
            'Accept': 'application/json; charset=utf-8',
            'Authorization':authheader
        },
        method: 'GET'
    }

    return request(options).then ((response)=>{
        return response.body
    }).catch((err)=>{
        console.log(err)
        console.log('errorstatuscode:'+err.statusCode)
    })
}

Body:
Please don't confuse between promises returned from request-promise and async functions.
async functions can be awaited to get a resolved promise and make your code look good.

I believe in letting people resolve their own problems and just guiding them along the way so just to make sure, aren't you getting the return from the resolved promise in this line of yours:

console.log(rs)

Moreover, by looking at your snippet, you're returning a response.body from within request-promise's thenable. You cannot catch any response errors from the response body, right?

I'd strongly suggest following a pattern wherein you'd catch errors (where you should) and display proper messages when you do. Wrapping your await call in a try/catch can help catch uncaught errors from request-promise.

Peace!


问:
Do I need to create a different awk script if I don't want to perform the same actions on all of the files i pass as parameters?
I'm a noob writing an awk script to combine two differently formatted files and insert specific data from each into another file, and I was wondering how I could specify which actions to perform on which files? In constructing the pattern statement I want to reference a different field number depending on which file I'm dealing with. Would that require a separate script? Ex:

```<code>file 1:
blue 6'0
brown 5'8
green 5'4

file 2:
36 28 20
</code>```

and then I'd like to combine these two into (after a specfic string)

```<code>file 3:
*string*
blue 6'0 36
brown 5'8 20
green 5'4 28
</code>```

I know in bash scripting the $ references parameter number, but in awk that sign references field number. Any insight you could provide would be helpful. Thanks

答:
As far as I understand the question, this should do:

```<code>xargs -n1 -a file2 | paste -d" " file1 -
</code>```

You can prepend arbitrary strings in the usual way:

```<code>( echo "string" ; xargs -n1 -a file2 | paste -d" " file1 - ) > file3
</code>```

Body:
I'm a noob writing an awk script to combine two differently formatted files and insert specific data from each into another file, and I was wondering how I could specify which actions to perform on which files? In constructing the pattern statement I want to reference a different field number depending on which file I'm dealing with. Would that require a separate script? Ex:

file 1:
blue 6'0
brown 5'8
green 5'4

file 2:
36 28 20

and then I'd like to combine these two into (after a specfic string)

file 3:
*string*
blue 6'0 36
brown 5'8 20
green 5'4 28

I know in bash scripting the $ references parameter number, but in awk that sign references field number. Any insight you could provide would be helpful. Thanks

Body:
As far as I understand the question, this should do:

xargs -n1 -a file2 | paste -d" " file1 -

You can prepend arbitrary strings in the usual way:

( echo "string" ; xargs -n1 -a file2 | paste -d" " file1 - ) > file3


问:
Getting session variables from c# to a different aspx page?
I am trying to get strings that I have put in my session variables to another aspx webform. I am getting it inside my JS script and I would like to know how to go about it. I have tried the following but it doesnt seem to work. Please anyone guide me a bit.

Home.aspx.cs

```<code> HttpContext.Current.Session["InstitutionID"] = BankID;
                        HttpContext.Current.Session["InstitutionName"] = txtBankName.Text.Trim();
</code>```

Index.aspx

```<code>  $(document).ready(function () {
              var param1var ='<%= Session["InstitutionID"]%>';
              var param2var = '<%= Session["InstitutionName"]%>';
                  console.log('param1', param1var);
                  console.log('param1', param2var);
    ........
    })
</code>```

答:
Are you using System.Web.SessionState.HttpSessionState.Session object to get the session object data in the Javascript? That is how I use it in one of my WebForms projects. Hope it helps.</p>

```<code>HttpContext.Current.Session[Constants.SessionStateVariables.LoginFailed] = false;

var loginIsFailed = '<%=Session[XYZProcet.Common.Constants.SessionStateVariables.LoginFailed]%>';
</code>```

Body:
I am trying to get strings that I have put in my session variables to another aspx webform. I am getting it inside my JS script and I would like to know how to go about it. I have tried the following but it doesnt seem to work. Please anyone guide me a bit.

Home.aspx.cs

 HttpContext.Current.Session["InstitutionID"] = BankID;
                        HttpContext.Current.Session["InstitutionName"] = txtBankName.Text.Trim();

Index.aspx

  $(document).ready(function () {
              var param1var ='<%= Session["InstitutionID"]%>';
              var param2var = '<%= Session["InstitutionName"]%>';
                  console.log('param1', param1var);
                  console.log('param1', param2var);
    ........
    })

Body:
Are you using System.Web.SessionState.HttpSessionState.Session object to get the session object data in the Javascript? That is how I use it in one of my WebForms projects. Hope it helps.

HttpContext.Current.Session[Constants.SessionStateVariables.LoginFailed] = false;

var loginIsFailed = '<%=Session[XYZProcet.Common.Constants.SessionStateVariables.LoginFailed]%>';


问:
Center of the center with Flexbox
I am trying to get the logo in the centre of the page, but then I want the text to be in the middle (centre) of the logo and the bottom of the page. So it is in the centre of the centred logo and bottom of the page. So in effect, the logo is in the centre of the page, but the text is in the centre, between the logo and bottom of the page. Here is the JSFiddle that I made and below is the code. I can get everything centred but not the way I want where the logo is in the centre and the text is in the centre, between the logo and bottom of the page.

/* FRONT PAGE LOADER */

.loader {
  position: fixed;
  left: 0px;
  top: 0px;
  width: 100%;
  height: 100%;
  z-index: 9999;
  background: white;
  text-align: center;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  flex-direction: column;
}

.centered {
  align-self: center;
}

.center-center {
  align-self: center;
}

.loading-img {
  width: 80px;
  height: 80px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;
}

/*SPIN THE LOGO */

@-moz-keyframes spin {
  0% {
    -moz-transform: rotate(0deg);
  }
  100% {
    -moz-transform: rotate(360deg);
  }
}

@-o-keyframes spin {
  0% {
    -o-transform: rotate(0deg);
  }
  100% {
    -o-transform: rotate(360deg);
  }
}

@-webkit-keyframes spin {
  0% {
    -webkit-transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="loader">
  <div class="centered" id="blank2"><img class="img-responsive loading-img" src="https://upload.wikimedia.org/wikipedia/commons/d/d0/Newscycle-Circle.png" />
    <p id="blank3">LOADING</p>
  </div>
  <div class="center-center">
    <h3 id="blank1">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras et ultricies risus. Sed pulvinar leo non ligula luctus aliquet.</h3>
  </div>
</div></code>```

答:
For this to work you need to add these 2 lines to your .loader rule

(you also need to add their prefixed versions, which I didn't)

```<code>justify-content: center;
align-items: center;
</code>```

Then you need to add a ghost element (I used the pseudo ::before) to balance the bottom text and give them both flex-grow: 1; flex-basis: 0; so they share the remaining space equal.

```<code>.loader::before,
.center-center {
  content: '\00a0';
  flex-grow: 1;
  flex-basis: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}
</code>```

And finally get rid of some of the margin's or else they will make it look like it doesn't work

```<code>.center-center h3 {
  margin: 0;
}
.centered p {
  margin-bottom: 0;
}
</code>```

```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* FRONT PAGE LOADER */

.loader {
  position: fixed;
  left: 0px;
  top: 0px;
  width: 100%;
  height: 100%;
  z-index: 9999;
  background: white;
  text-align: center;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.loader::before,
.center-center {
  content: '';
  flex-grow: 1;
  flex-basis: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}
.center-center h3 {
  margin: 0;
}
.centered p {
  margin-bottom: 0;
}

.loading-img {
  width: 80px;
  height: 80px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;
}

/*SPIN THE LOGO */
@-moz-keyframes spin {
  0% {
    -moz-transform: rotate(0deg);
  }
  100% {
    -moz-transform: rotate(360deg);
  }
}

@-o-keyframes spin {
  0% {
    -o-transform: rotate(0deg);
  }
  100% {
    -o-transform: rotate(360deg);
  }
}
@-webkit-keyframes spin {
  0% {
    -webkit-transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}</code>```

LOADING

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras et ultricies risus. Sed pulvinar leo non ligula luctus aliquet.

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

<hr>

<p>One can also use <code>transform: translate</code>, instead of a pseudo, in combination with Flexbox</p>

<p><em>Note though, it can make the text and image to overlap on smaller (low) screens</em></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><!-- $(window).load(function () {
"use strict";

function loadingScreen() {
  $(".loader").fadeOut(2000);
}
(function() {
var counter = 3,
  h2 = document.getElementById("blank1"),
  spinningLogo = document.getElementById("blank2"),
  loadingText = document.getElementById("blank3");
setInterval(function() {
  counter -= 1;
  if (counter === 0) {
    clearInterval(counter);
    h2.innerHTML = "";
    spinningLogo.innerHTML = "";
    loadingText.innerHTML = "";
    loadingScreen();
  }
}, 1000);
}());
}); --></code>```

/* FRONT PAGE LOADER */

.loader {
  position: fixed;
  left: 0px;
  top: 0px;
  width: 100%;
  height: 100%;
  z-index: 9999;
  background: white;
  text-align: center;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.center-center {
  position: absolute;
  top: 75%;
  width: 100%;
  left: 0;
  transform: translateY(-50%);
  text-align: center;
}

.center-center h3 {
  margin: 0;
}
.centered p {
  margin-bottom: 0;
}

.loading-img {
  width: 80px;
  height: 80px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;
}

/*SPIN THE LOGO */
@-moz-keyframes spin {
  0% {
    -moz-transform: rotate(0deg);
  }
  100% {
    -moz-transform: rotate(360deg);
  }
}

@-o-keyframes spin {
  0% {
    -o-transform: rotate(0deg);
  }
  100% {
    -o-transform: rotate(360deg);
  }
}
@-webkit-keyframes spin {
  0% {
    -webkit-transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="loader">
  <div class="centered" id="blank2"><img class="img-responsive loading-img" src="https://upload.wikimedia.org/wikipedia/commons/d/d0/Newscycle-Circle.png" />
    <p id="blank3">LOADING</p>
  </div>
  <div class="center-center">
    <h3 id="blank1">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</h3>
  </div>
</div></code>```

One can also use transform: translate alone (it has slightly better browser support than Flexbox)

Note though, it can make the text and image to overlap on smaller (low) screens

```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* FRONT PAGE LOADER */

.loader {
  position: fixed;
  left: 0px;
  top: 0px;
  width: 100%;
  height: 100%;
  z-index: 9999;
  background: white;
  text-align: center;
}

.centered {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.center-center {
  position: absolute;
  top: 75%;
  width: 100%;
  left: 0;
  transform: translateY(-50%);
  text-align: center;
}

.center-center h3 {
  margin: 0;
}
.centered p {
  margin-bottom: 0;
}

.loading-img {
  width: 80px;
  height: 80px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;
}

/*SPIN THE LOGO */
@-moz-keyframes spin {
  0% {
    -moz-transform: rotate(0deg);
  }
  100% {
    -moz-transform: rotate(360deg);
  }
}

@-o-keyframes spin {
  0% {
    -o-transform: rotate(0deg);
  }
  100% {
    -o-transform: rotate(360deg);
  }
}
@-webkit-keyframes spin {
  0% {
    -webkit-transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}</code>```

LOADING

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

```

Title: Center of the center with Flexbox

Body:
I am trying to get the logo in the centre of the page, but then I want the text to be in the middle (centre) of the logo and the bottom of the page. So it is in the centre of the centred logo and bottom of the page. So in effect, the logo is in the centre of the page, but the text is in the centre, between the logo and bottom of the page. Here is the JSFiddle that I made and below is the code. I can get everything centred but not the way I want where the logo is in the centre and the text is in the centre, between the logo and bottom of the page.

/* FRONT PAGE LOADER */

.loader {
  position: fixed;
  left: 0px;
  top: 0px;
  width: 100%;
  height: 100%;
  z-index: 9999;
  background: white;
  text-align: center;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  flex-direction: column;
}

.centered {
  align-self: center;
}

.center-center {
  align-self: center;
}

.loading-img {
  width: 80px;
  height: 80px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;
}

/*SPIN THE LOGO */

@-moz-keyframes spin {
  0% {
    -moz-transform: rotate(0deg);
  }
  100% {
    -moz-transform: rotate(360deg);
  }
}

@-o-keyframes spin {
  0% {
    -o-transform: rotate(0deg);
  }
  100% {
    -o-transform: rotate(360deg);
  }
}

@-webkit-keyframes spin {
  0% {
    -webkit-transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

LOADING

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras et ultricies risus. Sed pulvinar leo non ligula luctus aliquet.

Body:
For this to work you need to add these 2 lines to your .loader rule

(you also need to add their prefixed versions, which I didn't)

justify-content: center;
align-items: center;

Then you need to add a ghost element (I used the pseudo ::before) to balance the bottom text and give them both flex-grow: 1; flex-basis: 0; so they share the remaining space equal.

.loader::before,
.center-center {
  content: '\00a0';
  flex-grow: 1;
  flex-basis: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

And finally get rid of some of the margin's or else they will make it look like it doesn't work

.center-center h3 {
  margin: 0;
}
.centered p {
  margin-bottom: 0;
}

<!-- $(window).load(function () {
"use strict";

function loadingScreen() {
  $(".loader").fadeOut(2000);
}
(function() {
var counter = 3,
  h2 = document.getElementById("blank1"),
  spinningLogo = document.getElementById("blank2"),
  loadingText = document.getElementById("blank3");
setInterval(function() {
  counter -= 1;
  if (counter === 0) {
    clearInterval(counter);
    h2.innerHTML = "";
    spinningLogo.innerHTML = "";
    loadingText.innerHTML = "";
    loadingScreen();
  }
}, 1000);
}());
}); -->

/* FRONT PAGE LOADER */

.loader {
  position: fixed;
  left: 0px;
  top: 0px;
  width: 100%;
  height: 100%;
  z-index: 9999;
  background: white;
  text-align: center;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.loader::before,
.center-center {
  content: '';
  flex-grow: 1;
  flex-basis: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}
.center-center h3 {
  margin: 0;
}
.centered p {
  margin-bottom: 0;
}

.loading-img {
  width: 80px;
  height: 80px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;
}

/*SPIN THE LOGO */
@-moz-keyframes spin {
  0% {
    -moz-transform: rotate(0deg);
  }
  100% {
    -moz-transform: rotate(360deg);
  }
}

@-o-keyframes spin {
  0% {
    -o-transform: rotate(0deg);
  }
  100% {
    -o-transform: rotate(360deg);
  }
}
@-webkit-keyframes spin {
  0% {
    -webkit-transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="loader">
  <div class="centered" id="blank2"><img class="img-responsive loading-img" src="https://upload.wikimedia.org/wikipedia/commons/d/d0/Newscycle-Circle.png" />
    <p id="blank3">LOADING</p>
  </div>
  <div class="center-center">
    <h3 id="blank1">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras et ultricies risus. Sed pulvinar leo non ligula luctus aliquet.</h3>
  </div>
</div>

One can also use transform: translate, instead of a pseudo, in combination with Flexbox

Note though, it can make the text and image to overlap on smaller (low) screens

<!-- $(window).load(function () {
"use strict";

function loadingScreen() {
  $(".loader").fadeOut(2000);
}
(function() {
var counter = 3,
  h2 = document.getElementById("blank1"),
  spinningLogo = document.getElementById("blank2"),
  loadingText = document.getElementById("blank3");
setInterval(function() {
  counter -= 1;
  if (counter === 0) {
    clearInterval(counter);
    h2.innerHTML = "";
    spinningLogo.innerHTML = "";
    loadingText.innerHTML = "";
    loadingScreen();
  }
}, 1000);
}());
}); -->

/* FRONT PAGE LOADER */

.loader {
  position: fixed;
  left: 0px;
  top: 0px;
  width: 100%;
  height: 100%;
  z-index: 9999;
  background: white;
  text-align: center;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.center-center {
  position: absolute;
  top: 75%;
  width: 100%;
  left: 0;
  transform: translateY(-50%);
  text-align: center;
}

.center-center h3 {
  margin: 0;
}
.centered p {
  margin-bottom: 0;
}

.loading-img {
  width: 80px;
  height: 80px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;
}

/*SPIN THE LOGO */
@-moz-keyframes spin {
  0% {
    -moz-transform: rotate(0deg);
  }
  100% {
    -moz-transform: rotate(360deg);
  }
}

@-o-keyframes spin {
  0% {
    -o-transform: rotate(0deg);
  }
  100% {
    -o-transform: rotate(360deg);
  }
}
@-webkit-keyframes spin {
  0% {
    -webkit-transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="loader">
  <div class="centered" id="blank2"><img class="img-responsive loading-img" src="https://upload.wikimedia.org/wikipedia/commons/d/d0/Newscycle-Circle.png" />
    <p id="blank3">LOADING</p>
  </div>
  <div class="center-center">
    <h3 id="blank1">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</h3>
  </div>
</div>

One can also use transform: translate alone (it has slightly better browser support than Flexbox)

Note though, it can make the text and image to overlap on smaller (low) screens

<!-- $(window).load(function () {
"use strict";

function loadingScreen() {
  $(".loader").fadeOut(2000);
}
(function() {
var counter = 3,
  h2 = document.getElementById("blank1"),
  spinningLogo = document.getElementById("blank2"),
  loadingText = document.getElementById("blank3");
setInterval(function() {
  counter -= 1;
  if (counter === 0) {
    clearInterval(counter);
    h2.innerHTML = "";
    spinningLogo.innerHTML = "";
    loadingText.innerHTML = "";
    loadingScreen();
  }
}, 1000);
}());
}); -->

/* FRONT PAGE LOADER */

.loader {
  position: fixed;
  left: 0px;
  top: 0px;
  width: 100%;
  height: 100%;
  z-index: 9999;
  background: white;
  text-align: center;
}

.centered {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.center-center {
  position: absolute;
  top: 75%;
  width: 100%;
  left: 0;
  transform: translateY(-50%);
  text-align: center;
}

.center-center h3 {
  margin: 0;
}
.centered p {
  margin-bottom: 0;
}

.loading-img {
  width: 80px;
  height: 80px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;
}

/*SPIN THE LOGO */
@-moz-keyframes spin {
  0% {
    -moz-transform: rotate(0deg);
  }
  100% {
    -moz-transform: rotate(360deg);
  }
}

@-o-keyframes spin {
  0% {
    -o-transform: rotate(0deg);
  }
  100% {
    -o-transform: rotate(360deg);
  }
}
@-webkit-keyframes spin {
  0% {
    -webkit-transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="loader">
  <div class="centered" id="blank2"><img class="img-responsive loading-img" src="https://upload.wikimedia.org/wikipedia/commons/d/d0/Newscycle-Circle.png" />
    <p id="blank3">LOADING</p>
  </div>
  <div class="center-center">
    <h3 id="blank1">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</h3>
  </div>
</div>


问:
Replace all td's tags by th in a java String
I want to replace replace all "td" by "th" in this String

```<code>String head = "<tr>\n<td> </td>\n<td> </td>\n<td>Libelle</td>\n"
                      + "<td>Nom Table</td>\n<td>Groupe</td>\n<td> </td>\n</tr>\n"
</code>```

I tried to use :

```<code>head.replace("<td>", "<th>");
head.replace("</td>", "</th>");
</code>```

but it doesn't working.

Can you help me ?

答:
String.replace(..) will return resulting string, so you need set it back

```<code>head = head.replace("<td>", "<th>");
head = head.replace("</td>", "</th>");
</code>```

Body:
I want to replace replace all "td" by "th" in this String

String head = "
\n 	\n 	\nLibelle	\n"
                      + "Nom Table	\nGroupe	\n 	\n
\n"

I tried to use :

head.replace("", "");
head.replace("	", "	");

but it doesn't working.

Can you help me ?

Body:
String.replace(..) will return resulting string, so you need set it back

head = head.replace("<td>", "<th>");
head = head.replace("</td>", "</th>");


问:
What are `Zone.Identifier` files, and how do I prevent them from being created?
I often see files named 'blabla.exe:Zone.Identifier' when monitoring I/O with Process Monitor.

The files are seen on network-drives.

What are Zone.Identifier files?

What does the colon mean in the filename?

Is the colon related the file's extended attributes?

How do I prevent these files from being created when I copy code files from Windows Explorer to a WSL directory?

答:
The text after the colon is an identifier for an "Alternate Data Stream". ADS is used to store meta-information about the file. For example, the Zone identifier stores whether the file was downloaded from the internet.

Some specific info about URL Security Zones, Zone.Identifier Stream Name

See also Technet, Heysoft and this article about alternative data streams.

Finally, here's Streams, the Sysinternals tool for ADS.


问:
Creating graph/chart in android which support react-native
For my project I need gantt chart which support both android and ios. I want to start it with Android (java), but I dont know the way to expose it to react-native, such that I can use the graph in react-native and I don't find any related article for this.

first thing is after creating DemoChart.jar library, how can I make it available to be used with react-native (npm install DemoChart) javascript code & do I have to use C++ (android NDK) to bridge react-native and android.

Looking for a gantt chart, which has yAxis which shows a medical condition and it will have a horizontal line against it which scaling over xAxis (Dates or timePeriod), means in certain period (say a month) how often the medical condition has appeared

答: If you don't absolutely need to use native code, there is a really powerful library of components called Victory that allows you to make all kinds of charts. They also have a nice documentation here. This is compatible with both Android and iOS.</p>


问:
Programmatically generate video or animated GIF in Python?
I have a series of images that I want to create a video from.  Ideally I could specify a frame duration for each frame but a fixed frame rate would be fine too.  I'm doing this in wxPython, so I can render to a wxDC or I can save the images to files, like PNG.  Is there a Python library that will allow me to create either a video (AVI, MPG, etc) or an animated GIF from these frames?

Edit: I've already tried PIL and it doesn't seem to work.  Can someone correct me with this conclusion or suggest another toolkit?  This link seems to backup my conclusion regarding PIL: http://www.somethinkodd.com/oddthinking/2005/12/06/python-imaging-library-pil-and-animated-gifs/

答:
I was looking for a single line code and found the following to work for my application. Here is what I did:

First Step: Install ImageMagick from the link below

https://www.imagemagick.org/script/download.php

Second Step: Point the cmd line to the folder where the images (in my case .png format) are placed

Third Step: Type the following command

```<code>magick -quality 100 *.png outvideo.mpeg
</code>```

Thanks FogleBird for the idea!

Body:
I was looking for a single line code and found the following to work for my application. Here is what I did:

First Step: Install ImageMagick from the link below

https://www.imagemagick.org/script/download.php

Second Step: Point the cmd line to the folder where the images (in my case .png format) are placed

Third Step: Type the following command

magick -quality 100 *.png outvideo.mpeg

Thanks FogleBird for the idea!


问:
Split text into two sentences in C#
I want to divide a text into sentences.the sentence contains whitespace characters

For example:

```<code>Orginal sentence: 100 10 20 13
the result:
first sentence:100 10 20
second sentence:13
</code>```

I tried split but the result was :

```<code>first:100
second:10
third:20
fourth:13
</code>```

How can I do that?

答:
You can use Linq for this;

```<code>// This splits on white space
var split = original.Split(' ');

// This takes all split parts except for the last one
var first = split.Take(split.Count() - 1);
// And rejoins it
first = String.Join(" ", first);

// This gets the last one
var last = split.Last();
</code>```

Note: This is assuming that you want the first result to be every word except for the last and the second result to be only the last... If you have different requirements please clarify your question

Title: Split text into two sentences in C#

Body:
I want to divide a text into sentences.the sentence contains whitespace characters

For example:

Orginal sentence: 100 10 20 13
the result:
first sentence:100 10 20
second sentence:13

I tried split but the result was :

first:100
second:10
third:20
fourth:13

How can I do that?

Body:
You can use Linq for this;

// This splits on white space
var split = original.Split(' ');

// This takes all split parts except for the last one
var first = split.Take(split.Count() - 1);
// And rejoins it
first = String.Join(" ", first);

// This gets the last one
var last = split.Last();

Note: This is assuming that you want the first result to be every word except for the last and the second result to be only the last... If you have different requirements please clarify your question


问:
How to delete the item in Qt promote selection

Actually I have two choices but the upper one (haha.h) is does not exist, and I can't find the way to delete it. I am beginner in Qt, so someone can help me?

答:
You can remove it manually, just open the MainWindow.ui with an editor and remove the xml entry of your promoted class. You will find something like this:

```<code><customwidget>
   <class>haha</class>
   <extends>QLabel</extends>
   <header>haha.h</header>
   <container>0</container>
</customwidget>
</code>```

Check the counter, if it higher than 0, then you have to demote all the promoted widgets. Another way its to try to promote a simple QWidget an then remove it from the Qt Creator menu,

Body:
You can remove it manually, just open the MainWindow.ui with an editor and remove the xml entry of your promoted class. You will find something like this:

<customwidget>
   <class>haha</class>
   <extends>QLabel</extends>
   <header>haha.h</header>
   <container>0</container>
</customwidget>

Check the counter, if it higher than 0, then you have to demote all the promoted widgets. Another way its to try to promote a simple QWidget an then remove it from the Qt Creator menu,


问:
Setting NavigationBar and TabBar background color with gradient in objective-c
I want to set background color for NavigationBar and TabBar. It must be a gradient containing two hexadecimal colors. How can I made it in objective-c?
Thanks,</p>

答:
For the TabBar I had the same problem with my app and I came up with following:
in applicationDidFinishLaunching method I created a function to draw a gradient and used an instance of my UITabBarController to set up a correct gradient frame depending on the width of the device.

```<code>    - (UIImage *)drawGradientInView:(UITabBarController *) tabBarVC {
   CAGradientLayer *gradient = [CAGradientLayer layer];

  gradient.frame = CGRectMake(CGRectGetMinX(tabBarVC.tabBar.frame), CGRectGetMinY(tabBarVC.tabBar.frame), CGRectGetWidth(tabBarVC.view.frame), CGRectGetHeight(tabBarVC.tabBar.frame));

  gradient.colors = @[(__bridge id)[UIColor colorWithRed:220.0/255.0 green:220.0/255.0 blue:220.0/255.0 alpha:1.0].CGColor, (__bridge id)[UIColor whiteColor].CGColor];
  gradient.startPoint = CGPointMake(0.0, 0.5);
  gradient.endPoint = CGPointMake(0.5, 0.5);

  UIGraphicsBeginImageContext(gradient.bounds.size);
  [gradient renderInContext:UIGraphicsGetCurrentContext()];
  UIImage *gradientImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();

  return gradientImage;
}
</code>```

get the instance of UITabBarController

```<code>UITabBarController *tabVC = (UITabBarController *)[UIApplication sharedApplication].windows.firstObject.rootViewController;
</code>```

set your gradient

```<code>[UITabBar appearance].backgroundImage = [self drawGradientInView:tabVC];
</code>```

I'm not sure if that's a correct approach but it did work for me.

For NavigationBar, I subclassed it and customised that in layoutSubviews

```<code>- (void)layoutSubviews {
    [super layoutSubviews];

    CAGradientLayer *gradient = [CAGradientLayer layer];

    gradient.frame = CGRectMake(0, 0, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds) + CGRectGetHeight([UIApplication sharedApplication].statusBarFrame));
    gradient.colors = @[(__bridge id)[UIColor colorWithRed:220.0/255.0 green:220.0/255.0 blue:220.0/255.0 alpha:1.0].CGColor, (__bridge id)[UIColor whiteColor].CGColor];
    gradient.startPoint = CGPointMake(0.0, 0.5);
    gradient.endPoint = CGPointMake(0.5, 0.5);

    UIGraphicsBeginImageContext(gradient.bounds.size);
    [gradient renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *gradientImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    [self setBackgroundImage:gradientImage forBarMetrics:UIBarMetricsDefault];

}
</code>```

Hope this will help you..

Body:
For the TabBar I had the same problem with my app and I came up with following:
in applicationDidFinishLaunching method I created a function to draw a gradient and used an instance of my UITabBarController to set up a correct gradient frame depending on the width of the device.

    - (UIImage *)drawGradientInView:(UITabBarController *) tabBarVC {
   CAGradientLayer *gradient = [CAGradientLayer layer];

  gradient.frame = CGRectMake(CGRectGetMinX(tabBarVC.tabBar.frame), CGRectGetMinY(tabBarVC.tabBar.frame), CGRectGetWidth(tabBarVC.view.frame), CGRectGetHeight(tabBarVC.tabBar.frame));

  gradient.colors = @[(__bridge id)[UIColor colorWithRed:220.0/255.0 green:220.0/255.0 blue:220.0/255.0 alpha:1.0].CGColor, (__bridge id)[UIColor whiteColor].CGColor];
  gradient.startPoint = CGPointMake(0.0, 0.5);
  gradient.endPoint = CGPointMake(0.5, 0.5);

  UIGraphicsBeginImageContext(gradient.bounds.size);
  [gradient renderInContext:UIGraphicsGetCurrentContext()];
  UIImage *gradientImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();

  return gradientImage;
}

get the instance of UITabBarController

UITabBarController *tabVC = (UITabBarController *)[UIApplication sharedApplication].windows.firstObject.rootViewController;

set your gradient

[UITabBar appearance].backgroundImage = [self drawGradientInView:tabVC];

I'm not sure if that's a correct approach but it did work for me.

For NavigationBar, I subclassed it and customised that in layoutSubviews

- (void)layoutSubviews {
    [super layoutSubviews];

    CAGradientLayer *gradient = [CAGradientLayer layer];

    gradient.frame = CGRectMake(0, 0, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds) + CGRectGetHeight([UIApplication sharedApplication].statusBarFrame));
    gradient.colors = @[(__bridge id)[UIColor colorWithRed:220.0/255.0 green:220.0/255.0 blue:220.0/255.0 alpha:1.0].CGColor, (__bridge id)[UIColor whiteColor].CGColor];
    gradient.startPoint = CGPointMake(0.0, 0.5);
    gradient.endPoint = CGPointMake(0.5, 0.5);

    UIGraphicsBeginImageContext(gradient.bounds.size);
    [gradient renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *gradientImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    [self setBackgroundImage:gradientImage forBarMetrics:UIBarMetricsDefault];

}

Hope this will help you..


问:
Xcode warning: "Multiple build commands for output file"
I am getting an error like this:

[WARN]Warning: Multiple build commands for output file /Developer/B/Be/build/Release-iphonesimulator/BB.app/no.png

[WARN]Warning: Multiple build commands for output file /Developer/B/Be/build/Release-iphonesimulator/BB.app/d.png

[WARN]Warning: Multiple build commands for output file /Developer/B/Be/build/Release-iphonesimulator/BB.app/n.png

But I have checked Xcode and I don't see any duplicates of such files at all. As this post in the Apple Mailing Lists say, there are no duplicates.

答:
This is not an Xcode bug, though the warning message is not helpful enough to describe the real cause.

This error message occurs when you have several files in your project that have the same name. You just have to delete or rename the files with duplicate names and the problem is solved.


问:
Check if a pointer points to a valid structure
I have N statically allocated structures.

```<code>struct exemple{
     ...
}

struct exemple array[N];
struct exemple *test_ptr = 0x3; /* random address */
</code>```

Can I check if test_prt points to a valid address? i.e. it points to one "struct example" allocated.

答:
You can't. You have to know. It's not a problem if you manage your pointers correctly. A good habit is to always set pointers to 0 / NULL as soon as you destroy the object they point to. Then you can just test with if (ptr) or if (!ptr) (or, more verbose: if (ptr == NULL) / if (ptr != NULL)).

Note that your last assignment

```<code>struct exemple *test_ptr = 0x3; /* random address */
</code>```

is invalid. you can't assign an integer to a pointer. but you can cast it to the pointer type;

```<code>struct exemple *test_ptr = (struct exemple *)0x3; /* random address */
</code>```

The result will depend on your implementation / system.

Body:
I have N statically allocated structures.

struct exemple{
     ...
}

struct exemple array[N];
struct exemple *test_ptr = 0x3; /* random address */

Can I check if test_prt points to a valid address? i.e. it points to one "struct example" allocated.

Body:
You can't. You have to know. It's not a problem if you manage your pointers correctly. A good habit is to always set pointers to 0 / NULL as soon as you destroy the object they point to. Then you can just test with if (ptr) or if (!ptr) (or, more verbose: if (ptr == NULL) / if (ptr != NULL)).

Note that your last assignment

struct exemple *test_ptr = 0x3; /* random address */

is invalid. you can't assign an integer to a pointer. but you can cast it to the pointer type;

struct exemple *test_ptr = (struct exemple *)0x3; /* random address */

The result will depend on your implementation / system.


答:
In this case you can either use the replace method and the replaceAll since you are not using any regular expression and you cannot have nested modifications (something like "aaa".replace("a","b")).

Moreover, the modified String is returned by the method (rather than implicit modification), so you should reassign the head value.

So, the solution should look like this:

```<code>String head = "<tr>\n<td> </td>\n<td> </td>\n<td>Libelle</td>\n<td>Nom Table</td>\n<td>Groupe</td>\n<td> </td>\n</tr>\n";

head = head.replaceAll("<td>", "<th>");
head = head.replaceAll("</td>", "</th>");

System.out.println(head);
</code>```

EDIT1:

If you are willing to modify only these tags (and are always the same) you can use the replace method. Otherwise, you should use the replaceAll method since it can contain regex expressions. You can find more information on the difference between replace and replaceAll in Difference between String replace() and replaceAll()

Title: Replace all td's tags by th in a java String

Body:
In this case you can either use the replace method and the replaceAll since you are not using any regular expression and you cannot have nested modifications (something like "aaa".replace("a","b")).

Moreover, the modified String is returned by the method (rather than implicit modification), so you should reassign the head value.

So, the solution should look like this:

String head = "<tr>\n<td>&nbsp;</td>\n<td>&nbsp;</td>\n<td>Libelle</td>\n<td>Nom Table</td>\n<td>Groupe</td>\n<td>&nbsp;</td>\n</tr>\n";

head = head.replaceAll("<td>", "<th>");
head = head.replaceAll("</td>", "</th>");

System.out.println(head);

EDIT1:

If you are willing to modify only these tags (and are always the same) you can use the replace method. Otherwise, you should use the replaceAll method since it can contain regex expressions. You can find more information on the difference between replace and replaceAll in Difference between String replace() and replaceAll()


问:
Reading positional parameters using PHP
I am using a .php page just like a shell script. The only problem is that I do not know how to pass the positional parameters to PHP page.

```<code>#!/usr/bin/php
<?php

$myfile="balexp.xml";
</code>```

The following does not work in this php page and does work in the shell script.

```<code>myvar=$1
</code>```

How do I pass variables to a php page?

答:
if you have register_argc_argv turn on, you can use $argv

```<code>your_script.php haha hehe

<?
echo $argv[0]    <-- your_script.php
$myfile=$argv[1];
echo $myfile;    <-- return haha
?>
</code>```

more details : http://www.php.net/manual/en/features.commandline.usage.php

Title: Reading positional parameters using PHP

Body:
I am using a .php page just like a shell script. The only problem is that I do not know how to pass the positional parameters to PHP page.

#!/usr/bin/php
<?php

$myfile="balexp.xml";

The following does not work in this php page and does work in the shell script.

myvar=$1

How do I pass variables to a php page?

Body:
if you have register_argc_argv turn on, you can use $argv

your_script.php haha hehe

<?
echo $argv[0]    <-- your_script.php
$myfile=$argv[1];
echo $myfile;    <-- return haha
?>

more details : http://www.php.net/manual/en/features.commandline.usage.php