问:
Datanode keeps dying
I am running hadoop 0.20.2 (yes it's a legacy app).
I have a simple master-slave setup with 2 nodes.
I can start up the cluster fine with jps command on master:

```<code>4513 TaskTracker
4225 DataNode
4116 NameNode
4565 Jps
4329 SecondaryNameNode
4410 JobTracker
</code>```

And jps command on slave:

```<code>2409 Jps
2363 TaskTracker
2287 DataNode
</code>```

However if I run a command which interacts with hdfs like:

```<code>hadoop dfs -ls /
</code>```

it takes a couple of minutes and then one of the datanodes dies.
Looking in the log I can see this which is a known bug(the directory is already locked hadoop):

```<code>2017-07-05 16:12:59.986 INFO main org.apache.hadoop.hdfs.server.common.Storage - Cannot lock storage /srv/shared/hadoop/dfs/data. The directory is already locked.
Cannot lock storage /srv/shared/hadoop/dfs/data. The directory is already locked.
</code>```

I have tried stopping all daemons and deleting dfs/data and formatting the namenode. After doing that I can successfully start the cluster again with  everything up but as soon as I interact with hdfs or run a MR job a datanode dies.

The exact steps I am taking according to other posts are:
1. stop all daemons
2. delete dfs/data dir
3. run hadoop namenode -format
4. start all daemons

Not sure what else I can try.

答: As Remus Rusanu correctly pointed out HDFS is stored on a shared mounted folder and that is the problem. Specifying separate data.dirs solves the problem.</p>

Title: Datanode keeps dying

Body:
I am running hadoop 0.20.2 (yes it's a legacy app).
I have a simple master-slave setup with 2 nodes.
I can start up the cluster fine with jps command on master:

4513 TaskTracker
4225 DataNode
4116 NameNode
4565 Jps
4329 SecondaryNameNode
4410 JobTracker

And jps command on slave:

2409 Jps
2363 TaskTracker
2287 DataNode

However if I run a command which interacts with hdfs like:

hadoop dfs -ls /

it takes a couple of minutes and then one of the datanodes dies.
Looking in the log I can see this which is a known bug(the directory is already locked hadoop):

2017-07-05 16:12:59.986 INFO main org.apache.hadoop.hdfs.server.common.Storage - Cannot lock storage /srv/shared/hadoop/dfs/data. The directory is already locked.
Cannot lock storage /srv/shared/hadoop/dfs/data. The directory is already locked.

I have tried stopping all daemons and deleting dfs/data and formatting the namenode. After doing that I can successfully start the cluster again with  everything up but as soon as I interact with hdfs or run a MR job a datanode dies.

The exact steps I am taking according to other posts are:
1. stop all daemons
2. delete dfs/data dir
3. run hadoop namenode -format
4. start all daemons

Not sure what else I can try.


来源: stackexchange

问:
Multiple combinations logic should use switch or IF
I am trying to write a logic when a particular string are present in switch.

Ex: String

* * * * * My string will alway be in this format space between each string but the string length varies. but 5 spaces and 5 string

Other examples:
0 * * * *
* 0 * * *
* * 12/3 * *
* * 0 0 *
0 0 * * *
* * * 0 0
* * * AA 12

What I am trying here is to write switch cases when the string present other then * i will run case.

```<code>switch(true):
case '0 * * * * ':
echo 'First string has value';
case '`* * 0 0 * `':
echo '3rd & 4th string has value';
case 'A B C AA 12 ':
echo 'All string has value';
</code>```

ect...

I have many combinations but i am not sure switch is the correct way to achive it.

OR LOGIC 2:

Should I explode the string with spaces then use if condition to check 5 string?

答:
A switch statement is inherently different from an if statement:

```<code>switch(true){
  case true:
    echo 'true';
  case false:
    echo 'false';
  case 'foo':
    echo 'foo';
}
</code>```

So to answer your question it is likely you can't use a switch statement.
You can use regex as shown in ArtisticPhoenix's answer, but sometimes simplicity is good as well:

```<code>$list = [
  '0 * * * *',
  '* 0 * * *',
  '* * 12/3 * *',
  '* * 0 0 *',
  '0 0 * * *',
  '* * * 0 0',
  '* * * AA 12',
];

foreach($list as $item){
  if(count($cron = explode(' ', $item)) == 5){
    echo "Resultset of '$item'<br>";

    foreach($cron as $v){
      echo "$v<br>";
      // So I recommend if statements here.
    }
  } else {
    echo "'$item' is not in the correct format: '". implode(', ', $cron) . "'";
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to write a logic when a particular string are present in switch.

Ex: String

* * * * * My string will alway be in this format space between each string but the string length varies. but 5 spaces and 5 string

Other examples:
0 * * * *
* 0 * * *
* * 12/3 * *
* * 0 0 *
0 0 * * *
* * * 0 0
* * * AA 12

What I am trying here is to write switch cases when the string present other then * i will run case.

switch(true):
case '0 * * * * ':
echo 'First string has value';
case '`* * 0 0 * `':
echo '3rd & 4th string has value';
case 'A B C AA 12 ':
echo 'All string has value';

ect...

I have many combinations but i am not sure switch is the correct way to achive it.

OR LOGIC 2:

Should I explode the string with spaces then use if condition to check 5 string?

Body:
A switch statement is inherently different from an if statement:

switch(true){
  case true:
    echo 'true';
  case false:
    echo 'false';
  case 'foo':
    echo 'foo';
}

So to answer your question it is likely you can't use a switch statement.
You can use regex as shown in ArtisticPhoenix's answer, but sometimes simplicity is good as well:

$list = [
  '0 * * * *',
  '* 0 * * *',
  '* * 12/3 * *',
  '* * 0 0 *',
  '0 0 * * *',
  '* * * 0 0',
  '* * * AA 12',
];

foreach($list as $item){
  if(count($cron = explode(' ', $item)) == 5){
    echo "Resultset of '$item'<br>";

    foreach($cron as $v){
      echo "$v<br>";
      // So I recommend if statements here.
    }
  } else {
    echo "'$item' is not in the correct format: '". implode(', ', $cron) . "'";
  }
}


问:
How to get a std::list<T>::iterator from an element of that list?
Given a std:: list

```<code>std::list< int > myList
</code>```

and a reference (or a pointer) to an element in that list

```<code>int& myElement    |     int* pElement
</code>```

So, basically I know the address of that element

How can I get an std::list<int>::iterator to that element efficiently?

A slow yet working example is

```<code>const_iterator it
for( it = myList.begin(); it != &myElement; ++it)
{
    // do nothing, for loop terminates if "it" points to "myElem"
}
</code>```

Is there a quicker way? like

```<code>const_iterator it = magicToIteratorConverter( myList, myElem )
</code>```

Case of vector (but I need list):

For a vector, you could do the following:

```<code>const int* pStart = &myVector[0] // address of first element
const int* pElement = &myElem; // address of my element
const idx = static_cast< int >( pElement- pStart ); // no need to divide by size of an elem

std::vector< int >::iterator it = myVector.begin() + idx;
</code>```

Case of std::list:

答:
a std::list<int>::iterator is not an int*, you need to access the element in the iterator and get its address.  Also, std::find_if takes care of most of the boilerplate for you.

```<code>auto iter = std:find_if(myList.begin(), myList.end(),
                        [&myElement](const int & listElement)
                        { return &myElement == &listElement; });
</code>```

Writing the loop out yourself would look like:

```<code>auto iter = myList.end();

for(auto i = myList.begin(); i != myList.end(); ++i)
    if(&*i == &myElement)
    {
        iter = i;
        break;
    }
</code>```

Body:
Given a std:: list

std::list< int > myList

and a reference (or a pointer) to an element in that list

int& myElement    |     int* pElement

So, basically I know the address of that element

How can I get an std::list<int>::iterator to that element efficiently?

A slow yet working example is

const_iterator it
for( it = myList.begin(); it != &myElement; ++it)
{
    // do nothing, for loop terminates if "it" points to "myElem"
}

Is there a quicker way? like

const_iterator it = magicToIteratorConverter( myList, myElem )

Case of vector (but I need list):

For a vector, you could do the following:

const int* pStart = &myVector[0] // address of first element
const int* pElement = &myElem; // address of my element
const idx = static_cast< int >( pElement- pStart ); // no need to divide by size of an elem

std::vector< int >::iterator it = myVector.begin() + idx;

Case of std::list:

Body:
a std::list<int>::iterator is not an int*, you need to access the element in the iterator and get its address.  Also, std::find_if takes care of most of the boilerplate for you.

auto iter = std:find_if(myList.begin(), myList.end(),
                        [&myElement](const int & listElement)
                        { return &myElement == &listElement; });

Writing the loop out yourself would look like:

auto iter = myList.end();

for(auto i = myList.begin(); i != myList.end(); ++i)
    if(&*i == &myElement)
    {
        iter = i;
        break;
    }


问:
Angular 2: view does not update when array is updated
I have a component with two array. arrayA and arrayB. arrayB contains filtered elements of arrayA. And in the template:

```<code><div *ngFor="let elem of arrayB">{{elem.something}}</div>
</code>```

I have a button too:

```<code><button (click)="doSomething()">Do Something</button>
</code>```

In the doSomething method I use the filter method on arrayA to update arrayB.

```<code>doSomething() {
    this.arrayB = this.arrayA.filter(elem => { return ***some code***; });
}
</code>```

The problem is that the view doesn't refresh. I tried to use NgZone (ngZone.run(): I wrapped the code in the method.) and ChangeDetectorRef (detectChanges()/markForCheck(): I called this at the end of the method.) too.

What should be the solution for this?

答:
It should works ! make sure that your filter is working, please check this example:

```<code><div *ngFor="let elemB of arrayB">{{elemB}}</div>
<strong>array A :</strong>
<div *ngFor="let elemA of arrayA">{{elemA}}</div>
<button (click)="doSomething()">Do Something</button>
</code>```

TS :

```<code> arrayA = [0,1,2,3,4];
 arrayB = [];

 doSomething(){
     this.arrayB = this.arrayA.filter(x => { return x > 2; });
 }
</code>```

https://plnkr.co/edit/VQYoVIGoioPwjW1ThcFQ?p=preview

Body:
I have a component with two array. arrayA and arrayB. arrayB contains filtered elements of arrayA. And in the template:

{{elem.something}}

I have a button too:

<button (click)="doSomething()">Do Something</button>

In the doSomething method I use the filter method on arrayA to update arrayB.

doSomething() {
    this.arrayB = this.arrayA.filter(elem => { return ***some code***; });
}

The problem is that the view doesn't refresh. I tried to use NgZone (ngZone.run(): I wrapped the code in the method.) and ChangeDetectorRef (detectChanges()/markForCheck(): I called this at the end of the method.) too.

What should be the solution for this?

Body:
It should works ! make sure that your filter is working, please check this example:

<div *ngFor="let elemB of arrayB">{{elemB}}</div>
<strong>array A :</strong>
<div *ngFor="let elemA of arrayA">{{elemA}}</div>
<button (click)="doSomething()">Do Something</button>

TS :

 arrayA = [0,1,2,3,4];
 arrayB = [];

 doSomething(){
     this.arrayB = this.arrayA.filter(x => { return x > 2; });
 }

https://plnkr.co/edit/VQYoVIGoioPwjW1ThcFQ?p=preview


问:
Cannot preserve reference to array or readonly list, or list created from a non-default constructor
I came across the below question which is mostly identical to the issue I am having:

JSON.NET cannot handle simple array deserialization?

However, my situation is slightly different.  If I modify the Test class from that question to have an array property of the same type, I get the same deserialization error.

```<code>class Test
{
    public Test[] Tests;
}

var settings = new JsonSerializerSettings
{
    PreserveReferencesHandling = PreserveReferencesHandling.All
};

var o = new Test { Tests = new[] { new Test(), new Test() } };
//var o = new Test(); //this works if I leave the Tests array property null
var arr = new[] { o, o };
var ser = JsonConvert.SerializeObject(arr, settings);

arr = ((JArray)JsonConvert.DeserializeObject(ser, settings)).ToObject<Test[]>();
</code>```

I bet I am missing an important attribute on the Tests property.

答:
I think this code is nice but needs a refine

```<code> var elementType = objectType.IsArray ? objectType.GetElementType() : objectType.GetGenericArguments()[0];
</code>```

objectType.IsGenericType might be true so, we need to use GetGenericArguments()[0]

Body:
I came across the below question which is mostly identical to the issue I am having:

JSON.NET cannot handle simple array deserialization?

However, my situation is slightly different.  If I modify the Test class from that question to have an array property of the same type, I get the same deserialization error.

class Test
{
    public Test[] Tests;
}

var settings = new JsonSerializerSettings
{
    PreserveReferencesHandling = PreserveReferencesHandling.All
};

var o = new Test { Tests = new[] { new Test(), new Test() } };
//var o = new Test(); //this works if I leave the Tests array property null
var arr = new[] { o, o };
var ser = JsonConvert.SerializeObject(arr, settings);

arr = ((JArray)JsonConvert.DeserializeObject(ser, settings)).ToObject<Test[]>();

I bet I am missing an important attribute on the Tests property.

Body:
I think this code is nice but needs a refine

 var elementType = objectType.IsArray ? objectType.GetElementType() : objectType.GetGenericArguments()[0];

objectType.IsGenericType might be true so, we need to use GetGenericArguments()[0]


问:
Google+ Auth in AWS Cognito and API Gateway is unauthorized
AWS Wizards,

I've created a POC web app to test AWS Cognito and Federated Identities for a project.

I extended the POC with Google+ authentication. When a user authenticates via Google the counter for the Google Signin is increasing in Federated Identities, they are obviously being verified.

Now I am trying to use the credentials with a secured AWS API Gateway endpoint with no luck. The user will remain unauth'ed according to the gateway. I've tried the test feature in the API Gateway authorizers config, if I test with a Cognito user CognitoUserSession.idToken the test returns the claims.

If I do the same test with a Google user's idToken it is unauthenticated. After a successful Google sign in the same AWS Javascript SDK code is executed (as the Cognito user login). The credentials are updated with an identity ID and a session token but no ID token.

As I am a total noob on AWS I am probably missing something here. What should I do to get a valid idToken? Should it be done in a different way?

(GoogleLogin is a React component)

render() {
    return (
        <GoogleLogin
            clientId="44xxx11.apps.googleusercontent.com"
            buttonText="Google Login"
            onSuccess={this.responseGoogle}
            onFailure={this.responseGoogle}
        />
    )
}

responseGoogle(response) {
    console.log(response.tokenId)
    cognitoIdentityCredentials(response.tokenId)
}

cognitoIdentityCredentials(idToken) {

    const loginsObj = {
        ['accounts.google.com']: idToken
    }

    AWS.config.credentials = new AWS.CognitoIdentityCredentials({
        IdentityPoolId: IDENTITY_POOL_ID, // your identity pool id here
        Logins: loginsObj
    })

    AWS.config.credentials.get(function(err) {
        if ( err ) {
            console.log(err);
        } else {
            console.log("---- AWS credentials ----")
            console.log(AWS.config.credentials)
            // Got credentials, but no valid idToken
        }
    })
}
```

答:
The solution to this problem is that you can't really use AWS Security the way I assumed. In AWS API Gateway a generated library can be downloaded to access that API specifically and when using the lib we found that there are more fields added to the request, and yes they are signed. All of them.

It will be a pain to use different SDK libraries for different environments and apps, so we simply took one of the SDKs and made it into a general library that we can use for all requests in all web projects. There are similar projects already on Github, but they are unfortunately only working with Cognito users, not Federated Identities.

Happy Panda again.


问:
Using a TensorFlow .pb graph as a Keras Model
I've used the built-in TensorFlow tools to fine-tune the last layers of the InceptionV3 model to classify items on a custom dataset by using this tutorial. This generates a bunch of bottlenecks and a TensorFlow graph (*.pb file).

I'd like to import the *.pb TF graph into Keras, much like you would with an *.hdf5 file that contains the weights of a model. The reason being is that there are some tools written in Keras I would like to leverage while using this model.

Is this possible?

答: As of july 2017 Keras can only import Keras models and not raw tf graphs. This is because Keras has some metadata which is not itself kept as a part of the tf graph and can't be easily reconstructed.</p>


问:
How to fix js export issue with foundation-rails 6.4.1
Similar to this issue (http://foundation.zurb.com/forum/posts/53331-fresh-64-download-js-errors) but using zurb/foundation-rails. The app is built on Rails 5.1.1 and was throwing no errors until I upgraded to foundation-rails 6.4.1 and now no foundation js works at all and each foundation component is saying Uncaught ReferenceError: exports is not defined in the console. They are all referencing a line that says:

```<code>Object.defineProperty(exports, '__esModule', {
  value: true
});
</code>```

This could potentially have something to do with webpacker or babel based on my googling, but I haven't been able to see a logical next step to getting this fixed. I appreciate any guidance you can provide, thanks!

答: Paul Dodd's comment - this is currently a bug that they are aware of. https://github.com/zurb/foundation-rails/issues/231</p>

Body:
Similar to this issue (http://foundation.zurb.com/forum/posts/53331-fresh-64-download-js-errors) but using zurb/foundation-rails. The app is built on Rails 5.1.1 and was throwing no errors until I upgraded to foundation-rails 6.4.1 and now no foundation js works at all and each foundation component is saying Uncaught ReferenceError: exports is not defined in the console. They are all referencing a line that says:

Object.defineProperty(exports, '__esModule', {
  value: true
});

This could potentially have something to do with webpacker or babel based on my googling, but I haven't been able to see a logical next step to getting this fixed. I appreciate any guidance you can provide, thanks!


问:
How To Properly Create a Histogram: Displaying the Frequency of the Tweets for Each Day Spanning 2 Years
Unfortunately, I'm not experienced at all with matplotlib (and similar libraries), and I find some of the avaiable tutorials confusing.

This is my problem:

I have list of timestamps in string format, like this:

```<code>timestamp_list = ['2017-01-30 23:45', '2017-01-30 20:30', '2017-01-30 18:22', '2017-01-29 17:39', '2017-01-29 15:39', '2017-01-29 14:45', '2017-01-29 11:51', '2017-01-29 11:15', '2017-01-29 09:41', '2017-01-30 05:54', '2017-01-29 03:10']
</code>```

Each timestamp represents a tweet. I would like to build a histogram similar to this, but grouping my tweets per day. So, ultimately, I would like this histogram to show how many tweets are being tweeted on a daily basis from my list.

I have no idea how to group these tweets day by day (or any other grouping, i.e. monthly). I don't know which is the most easy and painless way to do it, and most importantly, when I'm reading posts on how to use matplotlib to create histograms (and similar things, like CDFs), I don't understand what each line specifically does, and thus, I cannot edit these posts according to my needs and expand my knowledge.

Can someone please provide a sample solution of to create such a histogram using matplotlib (or similar), but also comment each line so that I can fully understand how to produce similar plots in the future?

Thank you.

EDIT: I think that my original question wasn't clear enough, since none of the solutions suggested solve my problem. I'm sorry for not being more explicit. I will try to elaborate:

Let's say that I have a set of tweets of a specific topic spanning a duration of two years. This sums up to 730 days. timestamp_list is a list containing the unique timestamps of each tweet, in string format.

Every day in the duration of these two years is a unique day. That means that I have 730 unique days. What I want is to find out how many tweets of that specific topic were tweeted on every day of the 730 days. For instance, on 2017-01-20 there might have been 10 tweets, on 2017-01-21 45 tweets, and so on. I would like to create a histogram based on this. Some people suggested creating a dictionary.

How can I create a dictionary containing 730 keys and their respective number of tweets?

How can I plot a histogram based on the previous dictionary?

Or, if there is another, more efficient way to do (instead of using dictionaries), it's also welcome.

What I want is to somehow take this string list and create a histogram, like this, showing the number of tweets tweeted on a daily basis, spanning the duration of the dates (in my case, 2 years).

Bounty:

Thank you all for your submissions. Both @cphlewis' and @TobiasRibizel' answers are correct. However, I'm inclined to pick @TobiasRibizel' answer as the winning answer, since it doesn't use third party libraries, it is very well explained, and it produces a very nice histogram, just like the one I asked. Thank you.

答:
I am using a dict to store the date and count of tweets. The first 2 lines after the for loop are just extracting the day from the timestamp, I split the timestamp on the whitespace and take the first part to get the date then i just extract the last 2 things from that which is the date.

```<code>date_dict = {}
for dayin timestamp_list:
  day = day.split(' ')[0]
  day = day[len(day)-2:len(day)]
  if day in date_dict.keys():
    date_dict[day] += 1
  else
    date_dict[day] = 1
</code>```

now, you can get fancier by storing the month along with the date in the dict as they key as well.

Body:
Unfortunately, I'm not experienced at all with matplotlib (and similar libraries), and I find some of the avaiable tutorials confusing.

This is my problem:

I have list of timestamps in string format, like this:

timestamp_list = ['2017-01-30 23:45', '2017-01-30 20:30', '2017-01-30 18:22', '2017-01-29 17:39', '2017-01-29 15:39', '2017-01-29 14:45', '2017-01-29 11:51', '2017-01-29 11:15', '2017-01-29 09:41', '2017-01-30 05:54', '2017-01-29 03:10']

Each timestamp represents a tweet. I would like to build a histogram similar to this, but grouping my tweets per day. So, ultimately, I would like this histogram to show how many tweets are being tweeted on a daily basis from my list.

I have no idea how to group these tweets day by day (or any other grouping, i.e. monthly). I don't know which is the most easy and painless way to do it, and most importantly, when I'm reading posts on how to use matplotlib to create histograms (and similar things, like CDFs), I don't understand what each line specifically does, and thus, I cannot edit these posts according to my needs and expand my knowledge.

Can someone please provide a sample solution of to create such a histogram using matplotlib (or similar), but also comment each line so that I can fully understand how to produce similar plots in the future?

Thank you.

EDIT: I think that my original question wasn't clear enough, since none of the solutions suggested solve my problem. I'm sorry for not being more explicit. I will try to elaborate:

Let's say that I have a set of tweets of a specific topic spanning a duration of two years. This sums up to 730 days. timestamp_list is a list containing the unique timestamps of each tweet, in string format.

Every day in the duration of these two years is a unique day. That means that I have 730 unique days. What I want is to find out how many tweets of that specific topic were tweeted on every day of the 730 days. For instance, on 2017-01-20 there might have been 10 tweets, on 2017-01-21 45 tweets, and so on. I would like to create a histogram based on this. Some people suggested creating a dictionary.

How can I create a dictionary containing 730 keys and their respective number of tweets?

How can I plot a histogram based on the previous dictionary?

Or, if there is another, more efficient way to do (instead of using dictionaries), it's also welcome.

What I want is to somehow take this string list and create a histogram, like this, showing the number of tweets tweeted on a daily basis, spanning the duration of the dates (in my case, 2 years).

Bounty:

Thank you all for your submissions. Both @cphlewis' and @TobiasRibizel' answers are correct. However, I'm inclined to pick @TobiasRibizel' answer as the winning answer, since it doesn't use third party libraries, it is very well explained, and it produces a very nice histogram, just like the one I asked. Thank you.

Body:
I am using a dict to store the date and count of tweets. The first 2 lines after the for loop are just extracting the day from the timestamp, I split the timestamp on the whitespace and take the first part to get the date then i just extract the last 2 things from that which is the date.

date_dict = {}
for dayin timestamp_list:
  day = day.split(' ')[0]
  day = day[len(day)-2:len(day)]
  if day in date_dict.keys():
    date_dict[day] += 1
  else
    date_dict[day] = 1

now, you can get fancier by storing the month along with the date in the dict as they key as well.


问:
Why , in pase tree , ANTLR keep mismatching input?
I am new with ANTLR4 and I am trying to visualize the Parse Tree  of a text input in a simple form :

```<code>grammar Expr;
contract: (I WS SEND WS quantity WS asset WS TO WS beneficiary WS ON WS send_date WS)*;
asset: '$'| 'TND' | 'USD';
quantity:Q;
beneficiary: B;
send_date : day SLASH month SLASH year;
day: D ;
month: M ;
year: Y ;
B : LETTERUP (LETTERLOW+)+ LETTERLOW*;
Q : DIGITO DIGITZ*|DIGITO DIGITZ* POINT DIGITZ*;
D : DIGIT0 DIGITO|(DIGIT1|DIGIT2)DIGITZ|DIGIT3(DIGIT0|DIGIT1);
M : DIGIT0 DIGITO| DIGIT1(DIGIT0|DIGIT1|DIGIT2);
Y : DIGIT2 DIGIT0((DIGIT1(DIGIT7|DIGIT8|DIGIT9))|(DIGIT2 DIGITZ));
I: 'I';
SEND: 'send';
TO:'to' ;
ON: 'on';
LETTER : [a-zA-Z];
LETTERUP : [A-Z];
LETTERLOW : [a-z];
DIGITZ : [0-9];
DIGITO : [1-9];
DIGIT0 : [0];
DIGIT1 : [1];
DIGIT2 : [2];
DIGIT3 : [3];
DIGIT4 : [4];
DIGIT5 : [5];
DIGIT6 : [6];
DIGIT7 : [7];
DIGIT8 : [8];
DIGIT9 : [9];
SLASH:'/';
POINT:'.'|',';
WS : (' ' | '\t' |'\n' |'\r' )+ ;
</code>```

But it keeps mismatching the send_date as you can see here:

I know it is a seriously complex numerical grammar I did just want some control the 01<= day <= 31 , 01<= month <= 12 and 2017<= year <= 2029 that's all
is there any help? and thanks

答:
The problem happens because your grammar is ambiguous. 07 can match D and 2017 can match Q.

You can fix it like this:

```<code>grammar Expr;
contract: (I WS SEND WS quantity WS asset WS TO WS beneficiary WS ON WS send_date WS)*;
asset: '$'| 'TND' | 'USD';
quantity:Q;
beneficiary: B;
send_date : day month year ;
day: D ;
month:  M ;
year: Y ;

D : DIGIT0 DIGITO|(DIGIT1|DIGIT2)DIGITZ|DIGIT3(DIGIT0|DIGIT1);
M : SLASH (DIGIT0 DIGITO| DIGIT1(DIGIT0|DIGIT1|DIGIT2));
Y : SLASH (DIGIT2 DIGIT0((DIGIT1(DIGIT7|DIGIT8|DIGIT9))|(DIGIT2 DIGITZ)));
B : LETTERUP (LETTERLOW+)+ LETTERLOW*;
Q : DIGITO DIGITZ*|DIGITO DIGITZ* POINT DIGITZ*;
I: 'I';
SEND: 'send';
TO:'to' ;
ON: 'on';
LETTER : [a-zA-Z];
LETTERUP : [A-Z];
LETTERLOW : [a-z];
DIGITZ : [0-9];
DIGITO : [1-9];
DIGIT0 : [0];
DIGIT1 : [1];
DIGIT2 : [2];
DIGIT3 : [3];
DIGIT4 : [4];
DIGIT5 : [5];
DIGIT6 : [6];
DIGIT7 : [7];
DIGIT8 : [8];
DIGIT9 : [9];
SLASH:'/';
POINT:'.'|',';
WS : (' ' | '\t' |'\n' |'\r' )+ ;
</code>```

Body:
I am new with ANTLR4 and I am trying to visualize the Parse Tree  of a text input in a simple form :

grammar Expr;
contract: (I WS SEND WS quantity WS asset WS TO WS beneficiary WS ON WS send_date WS)*;
asset: '$'| 'TND' | 'USD';
quantity:Q;
beneficiary: B;
send_date : day SLASH month SLASH year;
day: D ;
month: M ;
year: Y ;
B : LETTERUP (LETTERLOW+)+ LETTERLOW*;
Q : DIGITO DIGITZ*|DIGITO DIGITZ* POINT DIGITZ*;
D : DIGIT0 DIGITO|(DIGIT1|DIGIT2)DIGITZ|DIGIT3(DIGIT0|DIGIT1);
M : DIGIT0 DIGITO| DIGIT1(DIGIT0|DIGIT1|DIGIT2);
Y : DIGIT2 DIGIT0((DIGIT1(DIGIT7|DIGIT8|DIGIT9))|(DIGIT2 DIGITZ));
I: 'I';
SEND: 'send';
TO:'to' ;
ON: 'on';
LETTER : [a-zA-Z];
LETTERUP : [A-Z];
LETTERLOW : [a-z];
DIGITZ : [0-9];
DIGITO : [1-9];
DIGIT0 : [0];
DIGIT1 : [1];
DIGIT2 : [2];
DIGIT3 : [3];
DIGIT4 : [4];
DIGIT5 : [5];
DIGIT6 : [6];
DIGIT7 : [7];
DIGIT8 : [8];
DIGIT9 : [9];
SLASH:'/';
POINT:'.'|',';
WS : (' ' | '\t' |'\n' |'\r' )+ ;

But it keeps mismatching the send_date as you can see here:

I know it is a seriously complex numerical grammar I did just want some control the 01<= day <= 31 , 01<= month <= 12 and 2017<= year <= 2029 that's all
is there any help? and thanks

Body:
The problem happens because your grammar is ambiguous. 07 can match D and 2017 can match Q.

You can fix it like this:

grammar Expr;
contract: (I WS SEND WS quantity WS asset WS TO WS beneficiary WS ON WS send_date WS)*;
asset: '$'| 'TND' | 'USD';
quantity:Q;
beneficiary: B;
send_date : day month year ;
day: D ;
month:  M ;
year: Y ;

D : DIGIT0 DIGITO|(DIGIT1|DIGIT2)DIGITZ|DIGIT3(DIGIT0|DIGIT1);
M : SLASH (DIGIT0 DIGITO| DIGIT1(DIGIT0|DIGIT1|DIGIT2));
Y : SLASH (DIGIT2 DIGIT0((DIGIT1(DIGIT7|DIGIT8|DIGIT9))|(DIGIT2 DIGITZ)));
B : LETTERUP (LETTERLOW+)+ LETTERLOW*;
Q : DIGITO DIGITZ*|DIGITO DIGITZ* POINT DIGITZ*;
I: 'I';
SEND: 'send';
TO:'to' ;
ON: 'on';
LETTER : [a-zA-Z];
LETTERUP : [A-Z];
LETTERLOW : [a-z];
DIGITZ : [0-9];
DIGITO : [1-9];
DIGIT0 : [0];
DIGIT1 : [1];
DIGIT2 : [2];
DIGIT3 : [3];
DIGIT4 : [4];
DIGIT5 : [5];
DIGIT6 : [6];
DIGIT7 : [7];
DIGIT8 : [8];
DIGIT9 : [9];
SLASH:'/';
POINT:'.'|',';
WS : (' ' | '\t' |'\n' |'\r' )+ ;

ContentLicense: CC BY-SA 4.0


问:
Generic http error handling in Angular
angular2-jwt provides an AuthHttp wrapper for the native Angular http class that automatically includes the http authorization header with each request. In my services I am usually calling a backend api like this

```<code>  getThings(): Observable<Thing[]> {
    return this.http.get(environment.apiEndpoint + '/things')
                    .map(res => res.json().data)
                    .catch(res => this.handleError(res));
  }
</code>```

with an error handler like

```<code>private handleError(error: Response | any) {
  let errMsg: string;
  if (error instanceof Response) {
    const body = error.json() || '';
    const err = body.error || JSON.stringify(body);
    errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
  } else {
    errMsg = error.message ? error.message : error.toString();
  }
  // If JWT is expired open a new window to log in again
  if (errMsg.indexOf('No JWT present or has expired') !== -1) {
    window.open(environment.apiEndpoint + '/loginToApp?expired', '_blank', 'height=570,width=520');
  }
  console.error(error);
  return Observable.throw(errMsg);
}
</code>```

I keep repeating the handleError method in all my services and I would like to know if there is a way to make this DRY. Is there a way to define a generic error handler for all http requests?

I'd like to avoid having to call catch each time if possible. Is there a way to extend the http class to automatically catch errors on each request and then in special situations I can add custom catch logic on a case by case basis?

I could export the method from another file and import it in each of my services but I think there has got to be a better way. Thanks for any suggestions.

UPDATE: I ended up extending the AuthHttp class from angular2-jwt.

```<code>import { Http, RequestOptions, Response, Request, RequestOptionsArgs } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

import { AuthHttp, AuthConfig } from 'angular2-jwt';

export class ApiHttp extends AuthHttp {

  public request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
    return super.request(url, options).catch(res => this.handleError(res));
  }

  private handleError(error: Response | any) {
    // error handling then rethrow the error
    return Observable.throw(error);
  }
}
</code>```

答:
You can create custom service CustomAuthHttp like AuthHTTP Wrapper. Like wrapper adds header, in CustomAuthHttp you can catch error. Then in your code inject CustomAuthHttp instead of AuthHTTP and use.</p>

```<code>@Injectable()
export class CustomAuthHttp {

  constructor(private http: AuthHttpWrapper) { }

  get(url: string) {
    return this.http.get(url)
      .catch(res => this.handleError(res));
  }

  private handleError(error: Response | any) {
    // your code
    return Observable.throw('');
  }
}
</code>```

Title: Generic http error handling in Angular

Body:
angular2-jwt provides an AuthHttp wrapper for the native Angular http class that automatically includes the http authorization header with each request. In my services I am usually calling a backend api like this

  getThings(): Observable<Thing[]> {
    return this.http.get(environment.apiEndpoint + '/things')
                    .map(res => res.json().data)
                    .catch(res => this.handleError(res));
  }

with an error handler like

private handleError(error: Response | any) {
  let errMsg: string;
  if (error instanceof Response) {
    const body = error.json() || '';
    const err = body.error || JSON.stringify(body);
    errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
  } else {
    errMsg = error.message ? error.message : error.toString();
  }
  // If JWT is expired open a new window to log in again
  if (errMsg.indexOf('No JWT present or has expired') !== -1) {
    window.open(environment.apiEndpoint + '/loginToApp?expired', '_blank', 'height=570,width=520');
  }
  console.error(error);
  return Observable.throw(errMsg);
}

I keep repeating the handleError method in all my services and I would like to know if there is a way to make this DRY. Is there a way to define a generic error handler for all http requests?

I'd like to avoid having to call catch each time if possible. Is there a way to extend the http class to automatically catch errors on each request and then in special situations I can add custom catch logic on a case by case basis?

I could export the method from another file and import it in each of my services but I think there has got to be a better way. Thanks for any suggestions.

UPDATE: I ended up extending the AuthHttp class from angular2-jwt.

import { Http, RequestOptions, Response, Request, RequestOptionsArgs } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

import { AuthHttp, AuthConfig } from 'angular2-jwt';

export class ApiHttp extends AuthHttp {

  public request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
    return super.request(url, options).catch(res => this.handleError(res));
  }

  private handleError(error: Response | any) {
    // error handling then rethrow the error
    return Observable.throw(error);
  }
}

Body:
You can create custom service CustomAuthHttp like AuthHTTP Wrapper. Like wrapper adds header, in CustomAuthHttp you can catch error. Then in your code inject CustomAuthHttp instead of AuthHTTP and use.

@Injectable()
export class CustomAuthHttp {

  constructor(private http: AuthHttpWrapper) { }

  get(url: string) {
    return this.http.get(url)
      .catch(res => this.handleError(res));
  }

  private handleError(error: Response | any) {
    // your code
    return Observable.throw('');
  }
}


问:
Is this a min-heap?
I want to find all pairs of numbers in a list that sum to n.

If I build a tree with the property that the children of of each node is all the values larger than itself, then I will be able to traverse it to find all the combinations that sum to n:

eg. for list [1,2,3,4]:

```<code>                   1

      2            3           4

   3     4         4

4
</code>```

What kind of data structure is this?

Is it a min-heap with no constraint on the number of children per node and duplicates permitted?

答:
Your target number is N. You can keep a hash table containing numbers you've encountered so far, and when you encounter a new number X, you can test whether you've encountered N-X in your hash table.

Pseudocode:

```<code>var encountered <- hashTable(key: integer, value: any)
var recordList <- list(value: pairs of integers)
for each element in inputList
  if encountered(N-element) then push [element, N-element] into recordList
  push element into encountered
loop
return recordList
</code>```

Title: Is this a min-heap?

Body:
I want to find all pairs of numbers in a list that sum to n.

If I build a tree with the property that the children of of each node is all the values larger than itself, then I will be able to traverse it to find all the combinations that sum to n:

eg. for list [1,2,3,4]:

                   1

      2            3           4

   3     4         4

4

What kind of data structure is this?

Is it a min-heap with no constraint on the number of children per node and duplicates permitted?

Body:
Your target number is N. You can keep a hash table containing numbers you've encountered so far, and when you encounter a new number X, you can test whether you've encountered N-X in your hash table.

Pseudocode:

var encountered <- hashTable(key: integer, value: any)
var recordList <- list(value: pairs of integers)
for each element in inputList
  if encountered(N-element) then push [element, N-element] into recordList
  push element into encountered
loop
return recordList


问:
How do I disable log4net status messages to the console?
I am using log4net in my .NET 3.5 console application and would like the log messages I generate to be seen in both the console standard out and the RollingFileAppender. The file output is working like a charm, but I am seeing a stream of status messages flowing to the console standard out when I execute. I would like to skip all the status information and only see the same messages I am programmatically generating to the log file.

Here is an example of what I see after I run my app:

```<code>log4net: XmlHierarchyConfigurator: Configuration update mode [Merge].
log4net: XmlHierarchyConfigurator: Logger [root] Level string is [DEBUG].
log4net: XmlHierarchyConfigurator: Logger [root] level set to [name="DEBUG",value=30000].
log4net: XmlHierarchyConfigurator: Loading Appender [Console] type: [log4net.Appender.ConsoleAppender]
log4net: PatternParser: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
</code>```

and it keeps on going until it describes the whole instantiation of the logger object.

How do I turn this off? Can I? I've tried all sorts of config file settings, but nothing makes these go away! Grrr...

答:
In the app I inherited, there was the line:

```<code><appSettings>
   <add key="log4net.Internal.Debug" value="true"/>
</code>```

Changing that to false fixed the problem.

OwnerDisplayName: C Morgan

LastEditorDisplayName: Chris

ContentLicense: CC BY-SA 2.5

Body:
I am using log4net in my .NET 3.5 console application and would like the log messages I generate to be seen in both the console standard out and the RollingFileAppender. The file output is working like a charm, but I am seeing a stream of status messages flowing to the console standard out when I execute. I would like to skip all the status information and only see the same messages I am programmatically generating to the log file.

Here is an example of what I see after I run my app:

log4net: XmlHierarchyConfigurator: Configuration update mode [Merge].
log4net: XmlHierarchyConfigurator: Logger [root] Level string is [DEBUG].
log4net: XmlHierarchyConfigurator: Logger [root] level set to [name="DEBUG",value=30000].
log4net: XmlHierarchyConfigurator: Loading Appender [Console] type: [log4net.Appender.ConsoleAppender]
log4net: PatternParser: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]

and it keeps on going until it describes the whole instantiation of the logger object.

How do I turn this off? Can I? I've tried all sorts of config file settings, but nothing makes these go away! Grrr...

Body:
In the app I inherited, there was the line:

<appSettings>
   <add key="log4net.Internal.Debug" value="true"/>

Changing that to false fixed the problem.


问:
oamSubmit.js not included when f:ajax is present on a page
I am running into a weird problem when using myfaces that is driving me nuts. I tried versions 2.2.10 and 2.2.12. I also use primefaces 6.0 but that might not be relevant.

Whenever I include an f:ajax tag on a page, commandLink no longer works and I get an error in the JavaScript console:

```<code>ReferenceError: myfaces is not defined
</code>```

Digging deeper it turns out that the following line is no longer generated when there is a f:ajax tag on the page:

```<code><script type="text/javascript" src="/console/javax.faces.resource/oamSubmit.js.jsf?ln=org.apache.myfaces"></script>
</code>```

When I manually add this script line everything works again! I do this by adding the folling javascript just after the  tag:

```<code><script>
if (!window.myfaces) {
  document.write(unescape('%3Cscript type="text/javascript" src="/console/javax.faces.resource/oamSubmit.js.jsf?ln=org.apache.myfaces"%3E%3C/script%3E'));
}
</script>
</code>```

Although everything seems to be working fine with this hack it gives me an uneasy feeling to have to do this. Can anyone shed a light on the cause of this issue?

答:
Same issue here. I stumbled upon mojarra is not defined when javax.faces.PROJECT_STAGE is Production
and submitForm() not defined for myfaces.JSF_JS_MODE 'minimal-modern' and found out that the issue is only present in javax.faces.PROJECT_STAGE=Production.

Adding

```<code><context-param>
    <param-name>org.apache.myfaces.JSF_JS_MODE</param-name>
    <param-value>minimal</param-value>
</context-param>
</code>```

to the web.xml fixed the issue for me.

Body:
I am running into a weird problem when using myfaces that is driving me nuts. I tried versions 2.2.10 and 2.2.12. I also use primefaces 6.0 but that might not be relevant.

Whenever I include an f:ajax tag on a page, commandLink no longer works and I get an error in the JavaScript console:

ReferenceError: myfaces is not defined

Digging deeper it turns out that the following line is no longer generated when there is a f:ajax tag on the page:

When I manually add this script line everything works again! I do this by adding the folling javascript just after the  tag:

Although everything seems to be working fine with this hack it gives me an uneasy feeling to have to do this. Can anyone shed a light on the cause of this issue?

Body:
Same issue here. I stumbled upon mojarra is not defined when javax.faces.PROJECT_STAGE is Production
and submitForm() not defined for myfaces.JSF_JS_MODE 'minimal-modern' and found out that the issue is only present in javax.faces.PROJECT_STAGE=Production.

Adding

<context-param>
    <param-name>org.apache.myfaces.JSF_JS_MODE</param-name>
    <param-value>minimal</param-value>
</context-param>

to the web.xml fixed the issue for me.


问:
How to make a simple rounded button in Storyboard?
I just started learning iOS development, cannot find how to make simple rounded button. I find resources for old versions. Do I need to set a custom background for a button? In Android, I would just use a 9 patch, but I know iOS does not have this capability.

答: While adding layer.cornerRadius in the storyboard make sure that you don't have leading or trailing spaces. If you do copy paste, you might get spaces inserted. Would be nice if XCode say some kind of warning or error.


问:
'Shadows' vs. 'Overrides' in VB.NET
What is the significance of the two keywords Shadows and Overrides? What they do and for which context is one or the other preferable?</p>

答:
The "shadows" keyword essentially says "If whoever is accessing this object knows it to be of this type or one of its descendents, use this member; otherwise use the base one."  The simplest example of this might be a base class ThingFactory, which includes a "MakeNew" method which returns a Thing, and a class CarFactory, derived from ThingFactory, whose "MakeNew" method always returns a Thing that will be of derived type Car.  If a routine knows that a ThingFactory it holds happens to, more particularly, be a CarFactory, then it will use a shadowed CarFactory.MakeNew (if one exists), which can specify the return type as Car.  If a routine doesn't know that its ThingFactory is actually a CarFactory, it will use a non-shadowed MakeNew (which should call an internal protected overridable MakeDerivedThing method).

Incidentally, another good use of shadows is to prevent derived classes from accessing Protected methods which will no longer work.  There's no way of simply hiding a member from derived classes other than assigning a new one, but one can prevent derived classes from doing anything with a protected member by declaring a new protected empty class with that name.  For example, if calling MemberwiseClone on an object would break it, one can declare:
```
  Protected Shadows Class MemberwiseClone
  End Class
```Note that this does not violate OOP principles like the Liskov Substitution Principle, since that only applies in cases where a derived class might be used in place of a base-class object.  If Foo and Bar inherits from Boz, a method which accepts a Boz parameter may legitimately be passed in a Foo or Bar instead.  On the other hand, an object of type Foo will know that its base-class object is of type Boz.  It will never be anything else (e.g. it's guaranteed not to be a Bar).

OwnerDisplayName: Jeff

Title: 'Shadows' vs. 'Overrides' in VB.NET

LastEditorDisplayName: Jeff

Body:
The "shadows" keyword essentially says "If whoever is accessing this object knows it to be of this type or one of its descendents, use this member; otherwise use the base one."  The simplest example of this might be a base class ThingFactory, which includes a "MakeNew" method which returns a Thing, and a class CarFactory, derived from ThingFactory, whose "MakeNew" method always returns a Thing that will be of derived type Car.  If a routine knows that a ThingFactory it holds happens to, more particularly, be a CarFactory, then it will use a shadowed CarFactory.MakeNew (if one exists), which can specify the return type as Car.  If a routine doesn't know that its ThingFactory is actually a CarFactory, it will use a non-shadowed MakeNew (which should call an internal protected overridable MakeDerivedThing method).

Incidentally, another good use of shadows is to prevent derived classes from accessing Protected methods which will no longer work.  There's no way of simply hiding a member from derived classes other than assigning a new one, but one can prevent derived classes from doing anything with a protected member by declaring a new protected empty class with that name.  For example, if calling MemberwiseClone on an object would break it, one can declare:

  Protected Shadows Class MemberwiseClone
  End Class

Note that this does not violate OOP principles like the Liskov Substitution Principle, since that only applies in cases where a derived class might be used in place of a base-class object.  If Foo and Bar inherits from Boz, a method which accepts a Boz parameter may legitimately be passed in a Foo or Bar instead.  On the other hand, an object of type Foo will know that its base-class object is of type Boz.  It will never be anything else (e.g. it's guaranteed not to be a Bar).


问:
Symfony 3.3.3 - default controller and container
I downloaded last stable version of Symfony (3.3.3) and on start I have error:

```<code>Attempted to call an undefined method named "getParameter" of class "AppBundle\Controller\DefaultController".
</code>```

This is:

```<code>'base_dir' => realpath($this->getParameter('kernel.project_dir')).DIRECTORY_SEPARATOR,
</code>```

Before 3.3.3 version Symfony controllers extended

Symfony\Bundle\FrameworkBundle\Controller\Controller.php

Now extends:

Symfony\Bundle\FrameworkBundle\Controller\AbstractController\AbstractController.php

So... How can I get data from container? In documentation (3.3 and 4.0 versions) Controller extends Controller, not AbstractController.

If I change AbstractController to Controller application works well, but do I should this change?

答:
Today came the version 3.3.4 that fixes this and other problems.
Here's the news: http://symfony.com/blog/symfony-3-3-4-released
To correct the error you must update with composer

```<code>composer update
</code>```

Body:
I downloaded last stable version of Symfony (3.3.3) and on start I have error:

Attempted to call an undefined method named "getParameter" of class "AppBundle\Controller\DefaultController".

This is:

'base_dir' => realpath($this->getParameter('kernel.project_dir')).DIRECTORY_SEPARATOR,

Before 3.3.3 version Symfony controllers extended

Symfony\Bundle\FrameworkBundle\Controller\Controller.php

Now extends:

Symfony\Bundle\FrameworkBundle\Controller\AbstractController\AbstractController.php

So... How can I get data from container? In documentation (3.3 and 4.0 versions) Controller extends Controller, not AbstractController.

If I change AbstractController to Controller application works well, but do I should this change?

Body:
Today came the version 3.3.4 that fixes this and other problems.
Here's the news: http://symfony.com/blog/symfony-3-3-4-released
To correct the error you must update with composer

composer update


问:
Autosys command to retrieve jobs names, status only, using job_depends
I'm using job_Depends to retrieve forecast of jobs during a time period, I'm looking to find jobs OFF_ICE or OFF_HOLD only during a time period.
current query:

job_depends -c -j %2 -F %3 -T %4>>%FileName%

brings out unnecessary(in my case) info., like showing the dependencies, conditions, etc.

```<code>                                     Start   Dependent
Job Name                         Status         Date Cond?        Cond?     Jobs?
--------                         ------      ---------------      -----   ---------
1CCS.UATQA.ACE_EXTRACT.C         ON_HOLD     Met                  No      Yes

   Dependent Job Name                            Condition
   ------------------                            ---------
   1CCS.UATQA.ACE_EXPORT.C                       SUCCESS(1CCS.UATQA.ACE_EXTRACT.C)
</code>```

All I need is Job name and current status which are 'ON_ICE' and 'ON_HOLD' jobs only.

答:
I used find and findstr features to remove the unwanted stuff.
Add required words in the below command, according to your req. The below command will remove spaces and new lines too.

```<code>type Temp.txt | find /V "ON_ICE" | find /V "Condition" | find /V "-------" | find /V "success" | find /V "______"| find /V ".FW"| find /V "(" |FINDSTR /V /R /C:"^$">FilteredFile.log
</code>```

Body:
I'm using job_Depends to retrieve forecast of jobs during a time period, I'm looking to find jobs OFF_ICE or OFF_HOLD only during a time period.
current query:

job_depends -c -j %2 -F %3 -T %4>>%FileName%

brings out unnecessary(in my case) info., like showing the dependencies, conditions, etc.

                                     Start   Dependent
Job Name                         Status         Date Cond?        Cond?     Jobs?
--------                         ------      ---------------      -----   ---------
1CCS.UATQA.ACE_EXTRACT.C         ON_HOLD     Met                  No      Yes

   Dependent Job Name                            Condition
   ------------------                            ---------
   1CCS.UATQA.ACE_EXPORT.C                       SUCCESS(1CCS.UATQA.ACE_EXTRACT.C)

All I need is Job name and current status which are 'ON_ICE' and 'ON_HOLD' jobs only.

Body:
I used find and findstr features to remove the unwanted stuff.
Add required words in the below command, according to your req. The below command will remove spaces and new lines too.

type Temp.txt | find /V "ON_ICE" | find /V "Condition" | find /V "-------" | find /V "success" | find /V "______"| find /V ".FW"| find /V "(" |FINDSTR /V /R /C:"^$">FilteredFile.log


问:
Python 2.7: Trouble Encoding to UTF-8
I have a dataframe that has a column, _text, containing the text of an article.  I'm trying to get the length of the article for each row in my dataframe.  Here's my attempt:

```<code>from bs4 import BeautifulSoup
result_df['_text'] = [BeautifulSoup(text, "lxml").get_text() for text in result_df['_text']]

text_word_length = [len(str(x).split(" ")) for x in result_df['_text']]
</code>```

Unfortunately, I get this error:

```<code>    ---------------------------------------------------------------------------
UnicodeEncodeError                        Traceback (most recent call last)
<ipython-input-8-f6c8ab83a46f> in <module>()
----> 1 text_word_length = [len(str(x).split(" ")) for x in result_df['_text']]

UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 231: ordinal not in range(128)
</code>```

Seems like I should be specifying "utf-8" somewhere, I'm just not sure where...

Thanks!

答:
Acording to the official python documentation:
Python Official Site

To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as:

```<code># coding=<encoding name>
</code>```

or (using formats recognized by popular editors):

```<code>#!/usr/bin/python
# -*- coding: <encoding name> -*-
</code>```

or:

```<code>#!/usr/bin/python
# vim: set fileencoding=<encoding name> :
</code>```

Title: Python 2.7: Trouble Encoding to UTF-8

Body:
I have a dataframe that has a column, _text, containing the text of an article.  I'm trying to get the length of the article for each row in my dataframe.  Here's my attempt:

from bs4 import BeautifulSoup
result_df['_text'] = [BeautifulSoup(text, "lxml").get_text() for text in result_df['_text']]

text_word_length = [len(str(x).split(" ")) for x in result_df['_text']]

Unfortunately, I get this error:

    ---------------------------------------------------------------------------
UnicodeEncodeError                        Traceback (most recent call last)
<ipython-input-8-f6c8ab83a46f> in <module>()
----> 1 text_word_length = [len(str(x).split(" ")) for x in result_df['_text']]

UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 231: ordinal not in range(128)

Seems like I should be specifying "utf-8" somewhere, I'm just not sure where...

Thanks!

Body:
Acording to the official python documentation:
Python Official Site

To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as:

# coding=<encoding name>

or (using formats recognized by popular editors):

#!/usr/bin/python
# -*- coding: <encoding name> -*-

or:

#!/usr/bin/python
# vim: set fileencoding=<encoding name> :


问:
Simple VBA Throwing Object Error 1004
This loops through each worksheet and inserts a VLOOKUP formula (which references a closed workbook). The code will start with the first sheet, find and open the corresponding workbook, and perform the VLOOKUP, then onto the next sheet/corresponding workbook. Everything works until I hit .Cells which is where i run into the Object error. What am I missing? I run this macro from the original workbook, then it opens the external workbook</p>

```<code>For Each ws In ThisWorkbook.Worksheets
    If (ws.Name <> "Sheet1") And (ws.Name <> "Sheet2") Then
        Set wbPath2 = Workbooks.Open("C:\MyDirectory\MyFile1.csv")
        sourceSheet = "[MySheet.csv]"

        With ws
            .Cells(Application.WorksheetFunction.Match("Account1", .Range("A:A"), 0), Application.WorksheetFunction.Match(ComboBox1.Value & " " & Year(Date), .Range("A6:BZ6"), 0)).Formula = "=VLOOKUP(""Account1 Service"",'" & Root & sourceSheet & ws.Name & " " & monthNumber & "." & lastDay & "." & Format(Now(), "yy") & "'!$A:$G,4,FALSE)"
</code>```

答:
the object seems to ComboBox1.Value .
In sheet code, it is possible to use combobox. But  in module, it is not possible. So use obleObject and link cell. And get the cell value.</p>

```<code>Dim ws As Worksheet
Dim obj As OLEObject
Dim strCombo As String
For Each ws In ThisWorkbook.Worksheets
    If (ws.Name = "Sheet1") Or (ws.Name = "Sheet2") Then
    Else
        Set wbPath2 = Workbooks.Open("C:\MyDirectory\MyFile1.csv")
        sourceSheet = "[MySheet.csv]"

        With ws
            k = .Name
            Set obj = .OLEObjects("ComboBox1")
            obj.LinkedCell = "q1" 'your  blank cell link ; this link "q1" cell
            strCombo = .Range("q1")
            .Cells(Application.WorksheetFunction.Match("Account1", .Range("A:A"), 0), Application.WorksheetFunction.Match(strCombo & " " & Year(Date), .Range("A6:BZ6"), 0)).Formula = "=VLOOKUP(""Account1 Service"",'" & Root & sourceSheet & ws.Name & " " & monthNumber & "." & lastDay & "." & Format(Now(), "yy") & "'!$A:$G,4,FALSE)"
            .Range("q1").Clear
        End With
    End If

Next
</code>```

Title: Simple VBA Throwing Object Error 1004

Body:
This loops through each worksheet and inserts a VLOOKUP formula (which references a closed workbook). The code will start with the first sheet, find and open the corresponding workbook, and perform the VLOOKUP, then onto the next sheet/corresponding workbook. Everything works until I hit .Cells which is where i run into the Object error. What am I missing? I run this macro from the original workbook, then it opens the external workbook

For Each ws In ThisWorkbook.Worksheets
    If (ws.Name <> "Sheet1") And (ws.Name <> "Sheet2") Then
        Set wbPath2 = Workbooks.Open("C:\MyDirectory\MyFile1.csv")
        sourceSheet = "[MySheet.csv]"

        With ws
            .Cells(Application.WorksheetFunction.Match("Account1", .Range("A:A"), 0), Application.WorksheetFunction.Match(ComboBox1.Value & " " & Year(Date), .Range("A6:BZ6"), 0)).Formula = "=VLOOKUP(""Account1 Service"",'" & Root & sourceSheet & ws.Name & " " & monthNumber & "." & lastDay & "." & Format(Now(), "yy") & "'!$A:$G,4,FALSE)"

Body:
the object seems to ComboBox1.Value .
In sheet code, it is possible to use combobox. But  in module, it is not possible. So use obleObject and link cell. And get the cell value.

Dim ws As Worksheet
Dim obj As OLEObject
Dim strCombo As String
For Each ws In ThisWorkbook.Worksheets
    If (ws.Name = "Sheet1") Or (ws.Name = "Sheet2") Then
    Else
        Set wbPath2 = Workbooks.Open("C:\MyDirectory\MyFile1.csv")
        sourceSheet = "[MySheet.csv]"

        With ws
            k = .Name
            Set obj = .OLEObjects("ComboBox1")
            obj.LinkedCell = "q1" 'your  blank cell link ; this link "q1" cell
            strCombo = .Range("q1")
            .Cells(Application.WorksheetFunction.Match("Account1", .Range("A:A"), 0), Application.WorksheetFunction.Match(strCombo & " " & Year(Date), .Range("A6:BZ6"), 0)).Formula = "=VLOOKUP(""Account1 Service"",'" & Root & sourceSheet & ws.Name & " " & monthNumber & "." & lastDay & "." & Format(Now(), "yy") & "'!$A:$G,4,FALSE)"
            .Range("q1").Clear
        End With
    End If

Next


问:
Shared Customers and Subscriptions in Stripe Connect
Problem Statement:

My Customers will have subscriptions with various publishers that have created their projects. I have to attach a customer to platform account and create a subscription which charges them behalf of the Connect custom accounts.
So how can I make a shared customer and subscribe them to various subscriptions in a connect account.

答:
Once you have that customer on your platform account, you can share them with a connected account by first creating a one-time use token:

```<code> $token = \Stripe\Token::create(array(
 "customer" => "cus_xxxx",
 ), array("stripe_account" => "{CONNECTED_STRIPE_ACCOUNT_ID}"));
</code>```

Once you have this token, you could (a) use it to create a charge to that customer that lands directly in the connected account, but since you want to create a subscription you want to (b) use the token to copy the customer into the connected account and then create a subscription in that connected account for the copied customer. To copy a customer from platform to connected account you can do the following:

```<code>$copiedCustomer = \Stripe\Customer::create(array(
"description" => "Customer for xxx@xxx.com",
"source" => $token // obtained with Stripe.js
), array("stripe_account" => "{CONNECTED_STRIPE_ACCOUNT_ID}"));
</code>```

This copied customer now has a new customer id in the connected account. Then you can setup the subscription on the connected account as follows:

```<code>\Stripe\Subscription::create(array(
"customer" => $copiedCustomer.id,
"plan" => "xxx"
), array("stripe_account" => "{CONNECTED_STRIPE_ACCOUNT_ID}"));
</code>```

Step 3 here mentions the above method for creating subscriptions for shared customers (but doesn't show the example, their example is a one-off charge for shared customers) https://stripe.com/docs/connect/shared-customers

Body:
Once you have that customer on your platform account, you can share them with a connected account by first creating a one-time use token:

 $token = \Stripe\Token::create(array(
 "customer" => "cus_xxxx",
 ), array("stripe_account" => "{CONNECTED_STRIPE_ACCOUNT_ID}"));

Once you have this token, you could (a) use it to create a charge to that customer that lands directly in the connected account, but since you want to create a subscription you want to (b) use the token to copy the customer into the connected account and then create a subscription in that connected account for the copied customer. To copy a customer from platform to connected account you can do the following:

$copiedCustomer = \Stripe\Customer::create(array(
"description" => "Customer for xxx@xxx.com",
"source" => $token // obtained with Stripe.js
), array("stripe_account" => "{CONNECTED_STRIPE_ACCOUNT_ID}"));

This copied customer now has a new customer id in the connected account. Then you can setup the subscription on the connected account as follows:

\Stripe\Subscription::create(array(
"customer" => $copiedCustomer.id,
"plan" => "xxx"
), array("stripe_account" => "{CONNECTED_STRIPE_ACCOUNT_ID}"));

Step 3 here mentions the above method for creating subscriptions for shared customers (but doesn't show the example, their example is a one-off charge for shared customers) https://stripe.com/docs/connect/shared-customers


问:
Keras: the difference between LSTM dropout and LSTM recurrent dropout
From the Keras documentation:

dropout: Float between 0 and 1. Fraction of the units to drop for the
 linear transformation of the inputs.

recurrent_dropout: Float between 0 and 1. Fraction of the units to
 drop for the linear transformation of the recurrent state.

Can anyone point to where on the image below each dropout happens?

答:
I suggest taking a look at (the first part of) this paper. Regular dropout is applied on the inputs and/or the outputs, meaning the vertical arrows from x_t and to h_t. In your case, if you add it as an argument to your layer, it will mask the inputs; you can add a Dropout layer after your recurrent layer to mask the outputs as well. Recurrent dropout masks (or "drops") the connections between the recurrent units; that would be the horizontal arrows in your picture.

This picture is taken from the paper above. On the left, regular dropout on inputs and outputs. On the right, regular dropout PLUS recurrent dropout:

(Ignore the colour of the arrows in this case; in the paper they are making a further point of keeping the same dropout masks at each timestep)


问:
C++98 proper check for a null pointer
C++11 introduced the nullptr keyword, which I don't have available.

I suppose there is the NULL macro from C, which I read about using in C++ from some stuff here and here, but I'm still unsure what's the proper way of checking for a null pointer in this older standard of C++.

I essentially want to be able to write this code for my test case with Boost Test:

```<code>aWrapperDataStructure x;
BOOST_CHECK_NE(x.get_ptr(), static_cast<decltype(x.get_ptr())>(nullptr));
</code>```

But maybe, as Tutorials Point suggested, something like this is more appropriate given the constraints:

```<code>BOOST_CHECK(x.get_ptr()); //true when not NULL
</code>```

Something about that throws me off though, so I'm wondering what the best practice is here. If it's somewhere online, or on SO, it's been long buried and I can't find it. Thank you!

答:
g++ use C++11 by default for some time now.

Therefore you can use nullptr and be "modern" as well as type safe.

If you have to be pre-C++11 portable NULL is best.

Title: C++98 proper check for a null pointer

Body:
C++11 introduced the nullptr keyword, which I don't have available.

I suppose there is the NULL macro from C, which I read about using in C++ from some stuff here and here, but I'm still unsure what's the proper way of checking for a null pointer in this older standard of C++.

I essentially want to be able to write this code for my test case with Boost Test:

aWrapperDataStructure x;
BOOST_CHECK_NE(x.get_ptr(), static_cast<decltype(x.get_ptr())>(nullptr));

But maybe, as Tutorials Point suggested, something like this is more appropriate given the constraints:

BOOST_CHECK(x.get_ptr()); //true when not NULL

Something about that throws me off though, so I'm wondering what the best practice is here. If it's somewhere online, or on SO, it's been long buried and I can't find it. Thank you!


问:
How to store long strings in Python during the execution of the program
I need a most efficient way to store long string (~2mb) during the execution of the program.

There is a loop and every iteration creates very long string. Lines of this string appears and I need to store them. There is also condition independent of the string. If condition is true I want to print this string. If condition is false, there is no operations. After iteration the string is no longer needed. Then next iteration creates another string.

I consider the variable. When line appears I want to add a line to the variable:

```<code>big_string = ''
while true:
    big_string += line
    [...]
    big_string += line
    if condition:
        print big_string
    big_string = ''
</code>```

Is it a good way to handle that ?

答:
The main options for data storage would be:

Variable,(as you have done)
 array,
 or a text file.

If you want to keep the strings separate and independent from one another I would recommend an array so you can independently call each index, however if that does not matter and you want to simply call the whole thing I see no issue with your current structure.

Body:
I need a most efficient way to store long string (~2mb) during the execution of the program.

There is a loop and every iteration creates very long string. Lines of this string appears and I need to store them. There is also condition independent of the string. If condition is true I want to print this string. If condition is false, there is no operations. After iteration the string is no longer needed. Then next iteration creates another string.

I consider the variable. When line appears I want to add a line to the variable:

big_string = ''
while true:
    big_string += line
    [...]
    big_string += line
    if condition:
        print big_string
    big_string = ''

Is it a good way to handle that ?


问:
Selenium - wait until synchronisation is done
I have an application that will sycnhronize data into the localstorage after logging in. See the following:

Console:

But when I run the selenium test it results in an error because the following screen isn't loaded yet. The one API call can take longer than the other (can always be different). How can I make sure the selenium test waits until all synchronization done?

答:
I think following should work, if this element is present but not visible after everything is loading. Else you need to change the condition. </p>

<p>I am not sure which language you are using, however you can convert the code to language of your choice. </p>

```<code>from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 30)
wait.until(EC.invisibility_of_element_located(driver.find_element_by_xpath("//*[conatains(text(),'Bezig')]")))
</code>```

Body:
I think following should work, if this element is present but not visible after everything is loading. Else you need to change the condition.

I am not sure which language you are using, however you can convert the code to language of your choice.

from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 30)
wait.until(EC.invisibility_of_element_located(driver.find_element_by_xpath("//*[conatains(text(),'Bezig')]")))


问:
Outputting conditionally from merge
I want to update a history file in SAS. I have new observations, which may overlap with existing data lines.

What is needed, is a file, which would have lines from dataset (new_data) where they exist and in case the lines do not exist, then from old set (old_data). What I've come up is a clunky merge operation, which is conditional on the order of the datasets. (==Works only if New_data is after Old_data. :?)

```<code>data new_data;
    input key value;
datalines;
    1 10
    1 11
    2 20
    2 21
    ;
run;

data old_data;
    input key value;
    datalines;
    2 50
    2 51
    3 30
    3 31
    ;
run;
</code>```

So I'd like to have the following:

```<code>key value
1 10
1 11
2 20
2 21
3 30
3 31
</code>```

However the following does not work. It produces the output below it.

```<code>data updated_history;
    merge New_data(in=a) old_data(in=b) ;
    by key;
    if a or (b and not a );
run;

....
2 50
2 51
...
</code>```

But for some reason this does:

```<code>data updated_history;
    merge old_data(in=b) New_data(in=a);
    by key;
    if a or (b and not a );
run;
</code>```

Question: Is there an intelligent way to manage from which dataset the values are select from. Something like: if a then value_from_dataset a;

答:
Since you have multiple observations per key value you probably do NOT want to use MERGE to combine these files.  You could do it using SET by reading the data twice using two DOW loops.  In that case it won't matter the order of the dataset in the SET statement since the records are interleaved instead of being joined. This first loop will calculate which of the two input datasets have any observations for this KEY value.

```<code>data want ;
  anyold=0;
  anynew=0;
  do until (last.key);
    set old_data (in=inold) new_data(in=innew);
    by key ;
    if inold then anyold=1;
    if innew then anynew=1;
  end;
  do until (last.key);
    set old_data (in=inold) new_data(in=innew);
    by key ;
    if not (anyold and anynew and inold) then output;
  end;
  drop anyold anynew;
run;
</code>```

This type of combination is probably easier to code using SQL.

```<code>proc sql ;
  create table want as
    select key,value from new_data
    union
    select key,value from old_data
    where key in (select key from old_data except select key from new_data)
    order by 1
  ;
quit;
</code>```

Title: Outputting conditionally from merge

Body:
I want to update a history file in SAS. I have new observations, which may overlap with existing data lines.

What is needed, is a file, which would have lines from dataset (new_data) where they exist and in case the lines do not exist, then from old set (old_data). What I've come up is a clunky merge operation, which is conditional on the order of the datasets. (==Works only if New_data is after Old_data. :?)

data new_data;
    input key value;
datalines;
    1 10
    1 11
    2 20
    2 21
    ;
run;

data old_data;
    input key value;
    datalines;
    2 50
    2 51
    3 30
    3 31
    ;
run;

So I'd like to have the following:

key value
1 10
1 11
2 20
2 21
3 30
3 31

However the following does not work. It produces the output below it.

data updated_history;
    merge New_data(in=a) old_data(in=b) ;
    by key;
    if a or (b and not a );
run;

....
2 50
2 51
...

But for some reason this does:

data updated_history;
    merge old_data(in=b) New_data(in=a);
    by key;
    if a or (b and not a );
run;

Question: Is there an intelligent way to manage from which dataset the values are select from. Something like: if a then value_from_dataset a;

Body:
Since you have multiple observations per key value you probably do NOT want to use MERGE to combine these files.  You could do it using SET by reading the data twice using two DOW loops.  In that case it won't matter the order of the dataset in the SET statement since the records are interleaved instead of being joined. This first loop will calculate which of the two input datasets have any observations for this KEY value.

data want ;
  anyold=0;
  anynew=0;
  do until (last.key);
    set old_data (in=inold) new_data(in=innew);
    by key ;
    if inold then anyold=1;
    if innew then anynew=1;
  end;
  do until (last.key);
    set old_data (in=inold) new_data(in=innew);
    by key ;
    if not (anyold and anynew and inold) then output;
  end;
  drop anyold anynew;
run;

This type of combination is probably easier to code using SQL.

proc sql ;
  create table want as
    select key,value from new_data
    union
    select key,value from old_data
    where key in (select key from old_data except select key from new_data)
    order by 1
  ;
quit;


问:
Using a React component in a regular web page
This is a very simplified version of my React component:

my-panel.js (my-panel-bundle.js)

```<code>import React from 'react'
import { render } from 'react-dom'

class MyPanel extends React.Component {
  render () {
    <input type='text' />
  }
}

export default MyPanel
</code>```

The full version is composed by several other components. I am using webpack to create a bundle file for the component. Now I want to use this component in an existing web application, which is not implemented using React. My challenge is, how do I load the React module, and create an instance of this component in a web page?

I have tried to use RequireJS, like this:

index.html

```<code><!DOCTYPE html>
<html>
    <body>
        <div id='root'></div>
        <script src="require.js" data-main="index.js"></script>
    </body>
</html>
</code>```

index.js

```<code>require.config({
    paths: {
        react: 'react',
        reactDom: 'react-dom',
        myPanel: 'my-panel'
    }
})

require(['react', 'reactDom', 'myPanel'], function(React, ReactDOM, MyPanel) {
    ReactDOM.render(
        React.createElement(MyPanel),
        document.getElementById('root')
    )
})
</code>```

The code fails reporting that MyPanel is undefined. Can anyone please help me identify the missing pieces?

答:
Firstly, you forgot the return value in render function of your MyPanel component.

```<code>class MyPanel extends React.Component {
  render () {
    return <input type='text' />
  }
}
</code>```

Coming to the main question. MyPanel is undefined because the path to the bundle is incorrect. Assuming that your project directory is something like the following:

```<code>- project/
    - index.html
    - index.js
    - bundle/
        - my-panel-bundle.js
    /... the rest
</code>```

your require config should look like:

```<code>require.config({
    paths: {
        react: 'react',
        reactDom: 'react-dom',
        bundle: 'bundle'
    }
})

require(['react', 'reactDom', 'bundle/my-panel-bundle'], function(React, ReactDOM, MyPanel) {
    ReactDOM.render(
        React.createElement(MyPanel),
        document.getElementById('root')
    )
})
</code>```

Alternatively, you don't actually need require.js if you use webpack. Instead of export default ..., put the ReactDOM render code:

```<code>ReactDOM.render(
  React.createElement(MyPanel),
  document.getElementById('root')
)
</code>```

after the class definition and include the bundle script in your html.

```<code><!DOCTYPE html>
<html>
    <body>
        <div id='root'></div>
        <script src="./bundle/my-panel-bundle.js"></script>
    </body>
</html>
</code>```

Body:
This is a very simplified version of my React component:

my-panel.js (my-panel-bundle.js)

import React from 'react'
import { render } from 'react-dom'

class MyPanel extends React.Component {
  render () {
    <input type='text' />
  }
}

export default MyPanel

The full version is composed by several other components. I am using webpack to create a bundle file for the component. Now I want to use this component in an existing web application, which is not implemented using React. My challenge is, how do I load the React module, and create an instance of this component in a web page?

I have tried to use RequireJS, like this:

index.html

<!DOCTYPE html>

index.js

require.config({
    paths: {
        react: 'react',
        reactDom: 'react-dom',
        myPanel: 'my-panel'
    }
})

require(['react', 'reactDom', 'myPanel'], function(React, ReactDOM, MyPanel) {
    ReactDOM.render(
        React.createElement(MyPanel),
        document.getElementById('root')
    )
})

The code fails reporting that MyPanel is undefined. Can anyone please help me identify the missing pieces?

Body:
Firstly, you forgot the return value in render function of your MyPanel component.

class MyPanel extends React.Component {
  render () {
    return <input type='text' />
  }
}

Coming to the main question. MyPanel is undefined because the path to the bundle is incorrect. Assuming that your project directory is something like the following:

- project/
    - index.html
    - index.js
    - bundle/
        - my-panel-bundle.js
    /... the rest

your require config should look like:

require.config({
    paths: {
        react: 'react',
        reactDom: 'react-dom',
        bundle: 'bundle'
    }
})

require(['react', 'reactDom', 'bundle/my-panel-bundle'], function(React, ReactDOM, MyPanel) {
    ReactDOM.render(
        React.createElement(MyPanel),
        document.getElementById('root')
    )
})

Alternatively, you don't actually need require.js if you use webpack. Instead of export default ..., put the ReactDOM render code:

ReactDOM.render(
  React.createElement(MyPanel),
  document.getElementById('root')
)

after the class definition and include the bundle script in your html.

<!DOCTYPE html>
<html>
    <body>
        <div id='root'></div>
        <script src="./bundle/my-panel-bundle.js"></script>
    </body>
</html>


问:
running multiple models on a distributed tensorflow train steps messd
I'm trying to build a distribute tensorflow framwork template, but there are serval problems confused me.

when I used --sync_replas=True in the script,does it mean I use Synchronous training as in doc?

why the global step in worker_0.log and worker_1.log
is not successively increment?

why the global step not start with 0 but like this

1499169072.773628: Worker 0: training step 1 done (global step: 339)

what's the relation between training step and global step?

As you can see from the create cluster script, I created an independent cluster.Can I run multiple different models on this cluster at the same time?

答:
Probably but depends on the particular library

During distributed training it's possible to have race conditions so the increments and reads of the global step are not fully ordered. This is fine.

This is probably because you're loading from a checkpoint?

Unclear, depends on the library you're using

One model per cluster is much easier to manage. It's fine to create multiple tf clusters on the same set of machines, though.


问:
Make Dropdown menu Disappear
I have a code from W3schools, in which we get dropdown menu after clicked on a button.

Dropdown menu don't disappear when we click anywhere else.
I have surfed a bit but it seems confusing as am new to js.

It would be much helpful if anyone could suggest how do we make it disappear?

Code Link

答:
Add the following code somewhere:

```<code>document.getElementById("myBtn").onblur = function() {
  document.getElementById("myDropdown").classList.remove("show");
};
</code>```

The original code that you wrote triggers the addition or removal of the "show" class on the element of id "myBtn" only when this element itself is clicked:

document.getElementById("myBtn").onclick = function() {
      document.getElementById("myDropdown").classList.toggle("show");
    };

But it does nothing if you click outside, that's the role of the onblur event.

Title: Make Dropdown menu Disappear

Body:
Add the following code somewhere:

document.getElementById("myBtn").onblur = function() {
  document.getElementById("myDropdown").classList.remove("show");
};

The original code that you wrote triggers the addition or removal of the "show" class on the element of id "myBtn" only when this element itself is clicked:

document.getElementById("myBtn").onclick = function() {
      document.getElementById("myDropdown").classList.toggle("show");
    };

But it does nothing if you click outside, that's the role of the onblur event.


问:
Encode Decode using python
I have this function in python

```<code>Str = "Ã¼";
print Str

def correctText( str ):
  str = str.upper()
  correctedText = str.decode('UTF8').encode('Windows-1252')
  return correctedText;

corText = correctText(Str);
print corText
</code>```

It works and converts characters like Ã¼ and Ã© however it fails when i try Ã? and Â¶

Is there a way i can fix it?

答: According to UTF8, Ã and Â¶ are not valid characters, meaning that don't have a number of bytes divisible by 4 (usually). What you need to do is either use some other kind of encoding or strip out errors in your str by using the unicode() function. I recommend using the ladder.</p>

Title: Encode Decode using python

Body:
I have this function in python

Str = "Ã¼";
print Str

def correctText( str ):
  str = str.upper()
  correctedText = str.decode('UTF8').encode('Windows-1252')
  return correctedText;

corText = correctText(Str);
print corText

It works and converts characters like Ã¼ and Ã© however it fails when i try Ã? and Â¶

Is there a way i can fix it?


问:
Does resnet have fully connected layers?
In my understanding, fully connected layer(fc in short) is used for predicting.

For example, VGG Net used 2 fc layers, which are both 4096 dimension. The last layer for softmax has dimension same with classes num:1000.

But for resnet, it used global average pooling, and use the pooled result of last convolution layer as the input.

But they still has a fc layer! Does this layer a really fc layer? Or this layer is only to make input into a vector of features which number is classes number? Does this layer has function for prediction result?

In a word, how many fc layers do resnet and VGGnet have? Does VGGnet's 1st 2nd 3rd fc layer has different function?

答:
In essence the guys at microsoft (ResNet) favor more convolutional layers instead of fully connected ones and therefore ommit fully connected layers. GlobalAveragePooling also decreases the feature size dramatically and therefore reduces the number of parameters going from the convolutional part to the fully connected part.

I would argue that the performance difference is quite slim, but one of their main accomplishments, by introducing ResNets is the dramatic reduction of parameters and those two points helped them accomplish that.


问:
Pentaho storage folder variable
Pentaho stores files created by job or transformation under /data-integration folder. Do you know the variable which I can overwrite and save my files under other directory?</p>

答:
The PDI solution for this is to define the filename as ${my_dir}/my_file,
where my_dir is a variable to be replaced at runtime by its value.

To define a variable, right-click anywhere in spoon main screen to bring the dropmenu, select Properties then Parameters, and add my-dir in the table, optionally with a default value.

When you run the job/transformation, you are presented a table of parameters, among which my_dir, to you have the opportunity to change the default.

There are many others ways to define a variable. For example, the Set variable / Get Variable let you change the variable from transformation to transformations in a job.

An other (very) usefull way is to define the variable in the kettle.properties that you can access from the main menu/edit/ and is staranard file in the .kettle directory in c:\User\yourname\ (Windows) directory or you installation directory (linux). The properties will overwrite the default values at runtime. The magic of this approach is that you can have a kettle.properties on your dev-machine, different from the one on the prod-server or the ones of your co-workers. A pretty handy solution especially for databases and url connections and passwords.

There is much more to say, because the PDI machinery goes ways further than rewriting an environment variable (which I guess is ${user.dir}).

And one more thing: you can popup a selectable list of variables almost anywhere it makes sense by pressing Crtl+Space.

Title: Pentaho storage folder variable


问:
Perl, global match and append something after the matched string
I have a problem in the case of performing a global match.  How can I substitute the matched string for a new string, which is made up from the original string plus a new string.  The string is like:

```<code>$string = "t123:apple;t456:pear;t789:banana";
</code>```

Then I have a hash like this:

```<code>my %hash = (
    t123 => 'fruit1',
    t456 => 'fruit2',
    t789 => 'fruit3',
);
</code>```

How can I then obtain a new string such as:

```<code>$newstring = "t123 fruit1:apple;t456 fruit2:pear;t789 fruit3:banana";
</code>```

Now, my perl code is:

```<code>while($string =~ /t\d{3}/g){
    if (exists $hash{"$&"}) {
        my $match = $&;
        $string =~ s/$&/$match.$hash{"$&"}/;
    }
}
</code>```

It doesn't work though, because the match always starts from the first character. I think I should use pos(string) or something to make it have an offset, but I don't know how to do this.

答:
The easy way is rather easy:

```<code>#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';

my $string = "t123:apple;t456:pear;t789:banana";

my %hash = (
    t123 => 'fruit1',
    t456 => 'fruit2',
    t789 => 'fruit3',
);

$string =~ s/(t\d+)/$1 $hash{$1}/g;

say $string;
</code>```

But this doesn't ensure that everything that matches t\d{3} is a valid key in your hash. So let's explicitly search for those keys.

```<code>#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';

my $string = "t123:apple;t456:pear;t789:banana";

my %hash = (
    t123 => 'fruit1',
    t456 => 'fruit2',
    t789 => 'fruit3',
);

my $match = join '|', map quotemeta, keys %hash;

$string =~ s/($match)/$1 $hash{$1}/g;

say $string;
</code>```

Body:
I have a problem in the case of performing a global match.  How can I substitute the matched string for a new string, which is made up from the original string plus a new string.  The string is like:

$string = "t123:apple;t456:pear;t789:banana";

Then I have a hash like this:

my %hash = (
    t123 => 'fruit1',
    t456 => 'fruit2',
    t789 => 'fruit3',
);

How can I then obtain a new string such as:

$newstring = "t123 fruit1:apple;t456 fruit2:pear;t789 fruit3:banana";

Now, my perl code is:

while($string =~ /t\d{3}/g){
    if (exists $hash{"$&"}) {
        my $match = $&;
        $string =~ s/$&/$match.$hash{"$&"}/;
    }
}

It doesn't work though, because the match always starts from the first character. I think I should use pos(string) or something to make it have an offset, but I don't know how to do this.

Body:
The easy way is rather easy:

#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';

my $string = "t123:apple;t456:pear;t789:banana";

my %hash = (
    t123 => 'fruit1',
    t456 => 'fruit2',
    t789 => 'fruit3',
);

$string =~ s/(t\d+)/$1 $hash{$1}/g;

say $string;

But this doesn't ensure that everything that matches t\d{3} is a valid key in your hash. So let's explicitly search for those keys.

#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';

my $string = "t123:apple;t456:pear;t789:banana";

my %hash = (
    t123 => 'fruit1',
    t456 => 'fruit2',
    t789 => 'fruit3',
);

my $match = join '|', map quotemeta, keys %hash;

$string =~ s/($match)/$1 $hash{$1}/g;

say $string;


问:
Expo: Can we use node modules like mqtt.js?
If Expo (create-react-native-app) is pure JavaScript, can I use other node modules in my Expo app?</p>

答:
in Expo, you can use any client based Javascript module, that you find in npm or that you created yourself.

But you can't use any kind of modules that has native parts in it. (Packages that you need to link to your react native projects can't be used) Although, Expo has its own SDK for your native needs.

The package you are talking about (mqtt.js) is a nodejs module, which can't be used with react native or in your case with Expo.

Just a guess, if you are trying to have a browser in your react native or Expo project, react native has a builtin in-app browser you might want to check out; https://facebook.github.io/react-native/docs/webview.html


问:
PhoneGap Build and OneSignal - Ios Certificates and Provisioning profiles
I have used OneSignals Provisonator to generate a .p12 and .cer file.
The problem comes when I have to upload the certificate to PhoneGap build, because PhoneGap Build also wants a Provisioning Profile.

On the Apple Developer website, I create a provisioning profile but I do not see the certificate created by the provisonator.

I have no idea how to create it using the certificate created previously. Also because the Provisonator does not give me a .csr file :(

Any help...PLEASEEEE!!

答:
OneSignal's Provisionator is used to generate a certificate for push notifications, not for code signing apps. You need separate code signing certificate for development and distribution.  You cannot set up a provisioning profile with an APNS (Apple Push Notification Service) certificate.  </p>

<p>If you look in the Phonegap documentation, it will explain how to set up your code signing. </p>

Body:
OneSignal's Provisionator is used to generate a certificate for push notifications, not for code signing apps. You need separate code signing certificate for development and distribution.  You cannot set up a provisioning profile with an APNS (Apple Push Notification Service) certificate.

If you look in the Phonegap documentation, it will explain how to set up your code signing.


问:
How to find the indexes of 10% of the highest samples in a vector in Matlab?
I have a vector with real numbers only. The length of the vector is 5000 samples. I would like to find the indexes of the 10% of the highest samples (meaning 500 samples in total). Any idea of how to do that in Matlab?</p>

答:
first of all sort the sample in descending order and then select the top 10 percent:</p>

```<code>[sortedVector, idxs] = sort(vector,'descend');
sampleRange = 1:floor(0.1*length(vector));
sample = sortedVector(sampleRange);
idxsSample = idxs(sampleRange);
</code>```

Body:
first of all sort the sample in descending order and then select the top 10 percent:

[sortedVector, idxs] = sort(vector,'descend');
sampleRange = 1:floor(0.1*length(vector));
sample = sortedVector(sampleRange);
idxsSample = idxs(sampleRange);


问:
Failing to search for full names while querying mysql with php
First time asking on SO. I currently am trying to search a database where the first and last names are seperate. Example:

```<code>player_id | first_name   | last_name
   191         John          Smith
   192         Larry         Citizen
   193         Benjamin      Example
</code>```

I am trying to allow users to search this list using a full name only. I currently have the following code once the user hits submit, it calls usersearch.php.

```<code>session_start();

include '../con.php';

$player = $_POST['name'];

$sql = "SELECT * FROM characters WHERE (concat(first_name,' ',last_name)) = ($player)";

$result = mysqli_query($conn, $sql);

if (!$row = mysqli_fetch_assoc($result)) {

    echo "Found no-one with the name $player. <a href='../search.php'>Try Again?</a>";

} else {

    $_SESSION['selplate'] = $row['plate'];
    $_SESSION['selname'] = $row['first_name, last_name'];

    header("Location: ../profile.php?player=$player");

}
</code>```

No matter the query it will not find users and always returns "Found no-one with the name $player. Try again?"

This was supposed to be the easy part of this project and I am pulling my hair out.

I have spent over an hour searching SO and Google to no avail so it must be my code? afaik it should work.

答:
delete the white-space from concat function in query and other thing is use $player = str_replace(' ','',trim($_POST['name'])) instead of $player = $_POST['name'].

$SQL = "SELECT * FROM TABLE_NAME WHERE concat(first_name,last_name) = '".$player."'"

i suggest PDO with prepared statements...

assume you are searching 'benjamin example' and query will check for 'benjamin example' so str_replace will output as benjaminexample.and the concated first_name and last_name will match it.

hope it help.
ignore if it sound silly.

Body:
First time asking on SO. I currently am trying to search a database where the first and last names are seperate. Example:

player_id | first_name   | last_name
   191         John          Smith
   192         Larry         Citizen
   193         Benjamin      Example

I am trying to allow users to search this list using a full name only. I currently have the following code once the user hits submit, it calls usersearch.php.

session_start();

include '../con.php';

$player = $_POST['name'];

$sql = "SELECT * FROM characters WHERE (concat(first_name,' ',last_name)) = ($player)";

$result = mysqli_query($conn, $sql);

if (!$row = mysqli_fetch_assoc($result)) {

    echo "Found no-one with the name $player. Try Again?";

} else {

    $_SESSION['selplate'] = $row['plate'];
    $_SESSION['selname'] = $row['first_name, last_name'];

    header("Location: ../profile.php?player=$player");

}

No matter the query it will not find users and always returns "Found no-one with the name $player. Try again?"

This was supposed to be the easy part of this project and I am pulling my hair out.

I have spent over an hour searching SO and Google to no avail so it must be my code? afaik it should work.


问:
Detailed Explanation for Dense Rank Explanation
I am trying to understand Dense rank function when multiple arguments were uses. Could some one help me in understanding with the below example or any other example?

Thanks a ton in Advance!

Calculated Column: DenseRank([Country],[Event Identifier])

答:
From the Help Pages

DenseRank(Arg1, Arg2, Arg3...)

Returns an integer value ranking of the values in the selected column.
  The first argument is the column to be ranked. An optional argument is
  a string determining whether to use an ascending (default)  or a
  descending ranking.  For the highest value to retrieve rank 1, use the
  argument "desc",  for the lowest value to retrieve rank 1, use "asc".

Ties are given the same rank value and the highest ranking number
  equals the number of unique values in the column.

Additional column arguments (optional) can be used when the column
  should be split into separately ranked categories.

Examples:

DenseRank([Sales])

DenseRank([Sales], "desc", [Region])

So, in your example you are ranking the Country grouped by / partitioned by the Even Identifier with a default "asc" order. This is done alphabetically, thus, if we look at Interim 1 we will see 4 ranks, 1-4 since you have 4 countries for Interim 1, in alphabetical order (ascending). Each "group", which is the 3rd argument and in your case Event Identifier, will get a set of rankings from 1 - n where n is the number of distinct values. If you remove this argument, the entire data set will be ranked without consideration of Event Identifier


问:
how to change my android app's window appearance in apps list when my app is in background?
I'll try to explain my question:

I have an app developed by me, that is now open on my android device with some activity that contains some data.

I want to hide this data if my app goes to background and I have some other apps open and looking on the open apps list.

Is there any way to change current activity's layout (I have many activities) when the app goes to background? For example to blur it or just show some default layout/image instead of current activity with the real data that I have?

viewing open apps

答: you can use the onPause() methode cause it's the last executed method before the application goes background