问:
Key-Value-Observing a to-many relationship in Cocoa
I am trying to get key-value-observing to work for an NSMutableArray. Below is the .h file for MyObservee, the observed class:

```<code>@interface MyObservee : NSObject {
    @private int someValue;
    @private NSMutableArray *someArray;
}

@property (readwrite,assign) int someValue;
- (NSMutableArray *)someArray;
@end
</code>```

The class MyObserver implements observeValueForKeyPath:ofObject:change:context:. Here is how I add the observer:

```<code>MyObservee *moe = [[MyObservee alloc] init];
MyObserver *mobs = [[MyObserver alloc] init];

[moe addObserver:mobs
      forKeyPath:@"someArray"
         options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld)
         context:NULL];

[moe.someArray addObject:@"hi there"];
</code>```

How come the addObject: message isn't triggering as a change to the someArray key path? I have a feeling there's something I don't fully understand here.

答:
Unfortunately, The NSArray classes are note KVO compliant. They are KVC compliant, but you can't observe them directly like you're trying to do here. The easiest way to get this functionality would be to use an NSArrayController. The NSArray controller is KVO compliant and will alert you when items are added or removed. In your example, your observer would be notified if you actually changed the array itself. For instance, if you did something like this:

```<code>[moe setSomeArray:[NSMutableArray array]];
</code>```

Which is probably not what you wanted at all :) Just as an aside, NSDictionary is actually KVO compliant so you could use that, if you chose. Or you could write a wrapper subclass of NSMutableArray that just creates a real mutable array as its backing store but just forwards on all messages to it except addObject and removeObject which you could override to trigger notifications.

OwnerDisplayName: Sam Lee

Body:
I am trying to get key-value-observing to work for an NSMutableArray. Below is the .h file for MyObservee, the observed class:

@interface MyObservee : NSObject {
    @private int someValue;
    @private NSMutableArray *someArray;
}

@property (readwrite,assign) int someValue;
- (NSMutableArray *)someArray;
@end

The class MyObserver implements observeValueForKeyPath:ofObject:change:context:. Here is how I add the observer:

MyObservee *moe = [[MyObservee alloc] init];
MyObserver *mobs = [[MyObserver alloc] init];

[moe addObserver:mobs
      forKeyPath:@"someArray"
         options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld)
         context:NULL];

[moe.someArray addObject:@"hi there"];

How come the addObject: message isn't triggering as a change to the someArray key path? I have a feeling there's something I don't fully understand here.

Body:
Unfortunately, The NSArray classes are note KVO compliant. They are KVC compliant, but you can't observe them directly like you're trying to do here. The easiest way to get this functionality would be to use an NSArrayController. The NSArray controller is KVO compliant and will alert you when items are added or removed. In your example, your observer would be notified if you actually changed the array itself. For instance, if you did something like this:

[moe setSomeArray:[NSMutableArray array]];

Which is probably not what you wanted at all :) Just as an aside, NSDictionary is actually KVO compliant so you could use that, if you chose. Or you could write a wrapper subclass of NSMutableArray that just creates a real mutable array as its backing store but just forwards on all messages to it except addObject and removeObject which you could override to trigger notifications.

OwnerDisplayName: Jason Coco


来源: stackexchange

问:
Anybody know a valid mechanism to detect the degree of similarity between two strings
I need to know how far the two strings are similar in terms of some measuring index</p>

答:
Probably the most commonly used metric is something called Levenshtein Distance, sometimes called "Edit Distance". In simple terms, it measures the number of edits (additions, deletions, or in a generalized method, also transpositions) that you need to make the strings in the comparison identical.

The algorithm has simple, efficient, and well-known realizations here's the pseudo code directly from the Wikipedia article linked earlier:

```<code> int LevenshteinDistance(char s[1..m], char t[1..n])
 {
   // for all i and j, d[i,j] will hold the Levenshtein distance between
   // the first i characters of s and the first j characters of t;
   // note that d has (m+1)x(n+1) values
   declare int d[0..m, 0..n]

   for i from 0 to m
     d[i, 0] := i // the distance of any first string to an empty second string
   for j from 0 to n
     d[0, j] := j // the distance of any second string to an empty first string

   for j from 1 to n
   {
     for i from 1 to m
     {
       if s[i] = t[j] then
         d[i, j] := d[i-1, j-1]       // no operation required
       else
         d[i, j] := minimum
                    (
                      d[i-1, j] + 1,  // a deletion
                      d[i, j-1] + 1,  // an insertion
                      d[i-1, j-1] + 1 // a substitution
                    )
     }
   }

   return d[m,n]
 }
</code>```

See also this related SO question: Good Python modules for fuzzy string comparison?

ContentLicense: CC BY-SA 2.5

Body:
Probably the most commonly used metric is something called Levenshtein Distance, sometimes called "Edit Distance". In simple terms, it measures the number of edits (additions, deletions, or in a generalized method, also transpositions) that you need to make the strings in the comparison identical.

The algorithm has simple, efficient, and well-known realizations here's the pseudo code directly from the Wikipedia article linked earlier:

 int LevenshteinDistance(char s[1..m], char t[1..n])
 {
   // for all i and j, d[i,j] will hold the Levenshtein distance between
   // the first i characters of s and the first j characters of t;
   // note that d has (m+1)x(n+1) values
   declare int d[0..m, 0..n]

   for i from 0 to m
     d[i, 0] := i // the distance of any first string to an empty second string
   for j from 0 to n
     d[0, j] := j // the distance of any second string to an empty first string

   for j from 1 to n
   {
     for i from 1 to m
     {
       if s[i] = t[j] then
         d[i, j] := d[i-1, j-1]       // no operation required
       else
         d[i, j] := minimum
                    (
                      d[i-1, j] + 1,  // a deletion
                      d[i, j-1] + 1,  // an insertion
                      d[i-1, j-1] + 1 // a substitution
                    )
     }
   }

   return d[m,n]
 }

See also this related SO question: Good Python modules for fuzzy string comparison?


问:
I need answer of one jade agent to depend on information from others and don't know how to do it
I'm new to jade and I have 5 agents in eclipse that have formula for finding an average and the question is how to send information from agent to this formula for calculation?
I'll be glad if someone can help me with this.
For example, there is one of my agents. There's no formula, because I don't know how to represent it. This is math expression of it: n+=alfa(y(1,2)-y(1,1))

```<code>public class FirstAgent extends Agent {
private Logger myLogger = Logger.getMyLogger(getClass().getName());

public class WaitInfoAndReplyBehaviour extends CyclicBehaviour {

    public WaitInfoAndReplyBehaviour(Agent a) {
        super(a);
    }

    public void action() {
        ACLMessage  msg = myAgent.receive();
        if(msg != null){
            ACLMessage reply = msg.createReply();

            if(msg.getPerformative()== ACLMessage.REQUEST){
                String content = msg.getContent();
                if ((content != null) && (content.indexOf("What is your number?") != -1)){
                    myLogger.log(Logger.INFO, "Agent "+getLocalName()+" - Received Info Request from "+msg.getSender().getLocalName());
                    reply.setPerformative(ACLMessage.INFORM);
                    try {
                        reply.setContentObject(7);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                else{
                    myLogger.log(Logger.INFO, "Agent "+getLocalName()+" - Unexpected request ["+content+"] received from "+msg.getSender().getLocalName());
                    reply.setPerformative(ACLMessage.REFUSE);
                    reply.setContent("( UnexpectedContent ("+content+"))");
                }

            }
            else {
                myLogger.log(Logger.INFO, "Agent "+getLocalName()+" - Unexpected message ["+ACLMessage.getPerformative(msg.getPerformative())+"] received from "+msg.getSender().getLocalName());
                reply.setPerformative(ACLMessage.NOT_UNDERSTOOD);
                reply.setContent("( (Unexpected-act "+ACLMessage.getPerformative(msg.getPerformative())+") )");
            }
            send(reply);
        }
        else {
            block();
        }
    }
</code>```

}

答:
So from what I can make out you want to (1) send a formula/task to multiple platforms, (2) have them performed locally, (3) and have the results communicated back.

I think there are atleast two ways of doing this:

The first is sending an object in an ACLMessage using Java Serialisation. This is a more OOP approach and not very "Agenty".

The second being the cloning or creating a local task agent.

Using Java SerialZation. (Solution 1)

Create an object for the calculation

```<code>class CalculationTask implements serialization
{   int n;
    int calculate(){
    n+=alfa(y(1,2)-y(1,1));
      }
}
</code>```

send the calculation object via ACLMESSAGE from the senderAgent.

```<code>request.setContentObject(new CalculationTask())
</code>```

recieve the calculation object by recieverAgent  and perform calculation on the object. Then response setting the complete task in the response.

```<code>CalculationTask myTask = request.getContentObject();
myTask.calculate();
ACLMESSAGE response = request.createReply();
response.setContentObject(myTask());
response.setPerformative(ACLMESSAGE.INFORM)
send(response)
</code>```

The senderAgent then receives the complete job.
ACLMESSAGE inform = getMessage();

```<code>CalculationTask completeTask = inform.getContentObject();
completeTask.process()
</code>```

Creating local Task Agents (Solution 2)
The Agent Orientated way of doing it would be to launch a task agent on each platform. Have each task agent complete the task and respond appropriately.

ContentLicense: CC BY-SA 3.0

Body:
I'm new to jade and I have 5 agents in eclipse that have formula for finding an average and the question is how to send information from agent to this formula for calculation?
I'll be glad if someone can help me with this.
For example, there is one of my agents. There's no formula, because I don't know how to represent it. This is math expression of it: n+=alfa(y(1,2)-y(1,1))

public class FirstAgent extends Agent {
private Logger myLogger = Logger.getMyLogger(getClass().getName());

public class WaitInfoAndReplyBehaviour extends CyclicBehaviour {

    public WaitInfoAndReplyBehaviour(Agent a) {
        super(a);
    }

    public void action() {
        ACLMessage  msg = myAgent.receive();
        if(msg != null){
            ACLMessage reply = msg.createReply();

            if(msg.getPerformative()== ACLMessage.REQUEST){
                String content = msg.getContent();
                if ((content != null) && (content.indexOf("What is your number?") != -1)){
                    myLogger.log(Logger.INFO, "Agent "+getLocalName()+" - Received Info Request from "+msg.getSender().getLocalName());
                    reply.setPerformative(ACLMessage.INFORM);
                    try {
                        reply.setContentObject(7);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                else{
                    myLogger.log(Logger.INFO, "Agent "+getLocalName()+" - Unexpected request ["+content+"] received from "+msg.getSender().getLocalName());
                    reply.setPerformative(ACLMessage.REFUSE);
                    reply.setContent("( UnexpectedContent ("+content+"))");
                }

            }
            else {
                myLogger.log(Logger.INFO, "Agent "+getLocalName()+" - Unexpected message ["+ACLMessage.getPerformative(msg.getPerformative())+"] received from "+msg.getSender().getLocalName());
                reply.setPerformative(ACLMessage.NOT_UNDERSTOOD);
                reply.setContent("( (Unexpected-act "+ACLMessage.getPerformative(msg.getPerformative())+") )");
            }
            send(reply);
        }
        else {
            block();
        }
    }

}

Body:
So from what I can make out you want to (1) send a formula/task to multiple platforms, (2) have them performed locally, (3) and have the results communicated back.

I think there are atleast two ways of doing this:

The first is sending an object in an ACLMessage using Java Serialisation. This is a more OOP approach and not very "Agenty".

The second being the cloning or creating a local task agent.

Using Java SerialZation. (Solution 1)

Create an object for the calculation

class CalculationTask implements serialization
{   int n;
    int calculate(){
    n+=alfa(y(1,2)-y(1,1));
      }
}

send the calculation object via ACLMESSAGE from the senderAgent.

request.setContentObject(new CalculationTask())

recieve the calculation object by recieverAgent  and perform calculation on the object. Then response setting the complete task in the response.

CalculationTask myTask = request.getContentObject();
myTask.calculate();
ACLMESSAGE response = request.createReply();
response.setContentObject(myTask());
response.setPerformative(ACLMESSAGE.INFORM)
send(response)

The senderAgent then receives the complete job.
ACLMESSAGE inform = getMessage();

CalculationTask completeTask = inform.getContentObject();
completeTask.process()

Creating local Task Agents (Solution 2)
The Agent Orientated way of doing it would be to launch a task agent on each platform. Have each task agent complete the task and respond appropriately.


问:
Google API Client for Android - how do I request an account?
In my app, I give the user an option to backup his/her data (a db and a few audio files) to their Google Drive account in the app's folder. To allow that, the user has to "choose account for MyApp" in the following dialog:

That dialog is shown after I create the connection this way:

```<code>mGAPIClient = new GoogleApiClient.Builder(mACA)
                .enableAutoManage(mACA, this)
                .addApi(Drive.API)
                .addScope(Drive.SCOPE_APPFOLDER)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
</code>```

After that, I start the backup process.

However, if the user taps somewhere outside that dialog, it disappears and the connection is not made - and the dialog is not shown again.

How can I prompt the system to show him/her that dialog again when that happens? Among other things, I've tried seting the GoogleApiClient instance to null and building it up again, but that didn't work.

答:
I've used the latest GoogleApi client as suggested in this official blog post, and I have used AGP 3.0.1 and Gradle 4.2.1.

Add this classpath to project build.gradle dependencies

```<code>classpath 'com.google.gms:google-services:3.1.2'
</code>```

Add those dependencies to app build.gradle

```<code>implementation 'com.google.android.gms:play-services-auth:11.6.2'
implementation 'com.google.android.gms:play-services-drive:11.6.2'
</code>```

Add plugin line at the bottom of the app build.gradle file

```<code>apply plugin: 'com.google.gms.google-services'
</code>```

Then in my example Activity i have:

```<code>public class MainActivity extends AppCompatActivity {

    private static final int RC_SIGN_IN = 9001;

    private GoogleSignInClient mSignInClient;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //request access to drive
        GoogleSignInOptions options =
                new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                        .requestScopes(Drive.SCOPE_FILE)
                        .build();

        mSignInClient = GoogleSignIn.getClient(this, options);
        //button to launch the signIn flow
        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(view -> signIn());
    }

    private void signIn() {
        // Launches the sign in flow, the result is returned in onActivityResult
        Intent intent = mSignInClient.getSignInIntent();
        startActivityForResult(intent, RC_SIGN_IN);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RC_SIGN_IN) {
            Task<GoogleSignInAccount> task =
                    GoogleSignIn.getSignedInAccountFromIntent(data);
            if (task.isSuccessful()) {
                // Sign in succeeded, proceed with account
                GoogleSignInAccount acct = task.getResult();
                // proceed with your logic
            } else {
                // Sign in failed, handle failure and update UI
                // we should probably show a motivation screen to the user before showing
                // the account selection again, but for example purposes we launch the
                // sign-in flow immediately
                signIn();
            }
        }
    }
}
</code>```

For me this is working fine. Let me know if it works for you too.

Body:
In my app, I give the user an option to backup his/her data (a db and a few audio files) to their Google Drive account in the app's folder. To allow that, the user has to "choose account for MyApp" in the following dialog:

That dialog is shown after I create the connection this way:

mGAPIClient = new GoogleApiClient.Builder(mACA)
                .enableAutoManage(mACA, this)
                .addApi(Drive.API)
                .addScope(Drive.SCOPE_APPFOLDER)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

After that, I start the backup process.

However, if the user taps somewhere outside that dialog, it disappears and the connection is not made - and the dialog is not shown again.

How can I prompt the system to show him/her that dialog again when that happens? Among other things, I've tried seting the GoogleApiClient instance to null and building it up again, but that didn't work.

Body:
I've used the latest GoogleApi client as suggested in this official blog post, and I have used AGP 3.0.1 and Gradle 4.2.1.

Add this classpath to project build.gradle dependencies

classpath 'com.google.gms:google-services:3.1.2'

Add those dependencies to app build.gradle

implementation 'com.google.android.gms:play-services-auth:11.6.2'
implementation 'com.google.android.gms:play-services-drive:11.6.2'

Add plugin line at the bottom of the app build.gradle file

apply plugin: 'com.google.gms.google-services'

Then in my example Activity i have:

public class MainActivity extends AppCompatActivity {

    private static final int RC_SIGN_IN = 9001;

    private GoogleSignInClient mSignInClient;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //request access to drive
        GoogleSignInOptions options =
                new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                        .requestScopes(Drive.SCOPE_FILE)
                        .build();

        mSignInClient = GoogleSignIn.getClient(this, options);
        //button to launch the signIn flow
        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(view -> signIn());
    }

    private void signIn() {
        // Launches the sign in flow, the result is returned in onActivityResult
        Intent intent = mSignInClient.getSignInIntent();
        startActivityForResult(intent, RC_SIGN_IN);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RC_SIGN_IN) {
            Task<GoogleSignInAccount> task =
                    GoogleSignIn.getSignedInAccountFromIntent(data);
            if (task.isSuccessful()) {
                // Sign in succeeded, proceed with account
                GoogleSignInAccount acct = task.getResult();
                // proceed with your logic
            } else {
                // Sign in failed, handle failure and update UI
                // we should probably show a motivation screen to the user before showing
                // the account selection again, but for example purposes we launch the
                // sign-in flow immediately
                signIn();
            }
        }
    }
}

For me this is working fine. Let me know if it works for you too.


问:
how do you git push only the new commit

Because Git is distributed, and committers can commit within their own
  repositories, they can make a series of commits, then git squash the
  series of commits to make a new commit, then git push only the new
  commit. In this case you don't have the original commits anywhere:
  they are only in the committer's repository, not on GitHub and not in
  your clone either.

How do you "git push only the new commit" ?

答:
It is just a normal push. I am pretty sure what they mean there: you push just the squashed commit - not the commits that existed before the squash.
Lets say you made commit 1/2/3 and squashed to 4 - then you push with a normal git push - then commit 4 is pushed and exists remote (e.g. on github) and 1/2/3 only exist locally

Title: how do you git push only the new commit


问:
How does Lifecycle policy for moving s3 to glacier work?
I have created a lifecycle policy for one of my buckets as below:

Name and scope

Name MoveToGlacierAndDeleteAfterSixMonths

Scope Whole bucket

Transitions
For previous versions of objects Transition to Amazon Glacier after 1 days

Expiration Permanently delete after 360 days

Clean up incomplete multipart uploads after 7 days

I would like to get answer for the following questions:

When would the data be deleted from s3 as per this policy ?

Do i have to do anything on the glacier end inorder to move my s3 bucket to glacier ?

My s3 bucket is 6 years old and all the versions of the bucket are even older. But i am not able to see any data in the glacier console though my transition policy is set to move to glacier after 1 day from the creation of the data. Please explain this behavior.

Does this policy affect only new files which will be added to the bucket post lifepolicy creation or does this affect all the files in s3 bucket ?

Please answer these questions.

答:
When would the data be deleted from s3 as per this policy ?

Never, for current versions. A lifecycle policy to transition objects to Glacier doesn't delete the data from S3 -- it migrates it out of S3 primary storage and over into Glacier storage -- but it technically remains an S3 object.

Think of it as S3 having its own Glacier account and storing data in that separate account on your behalf.  You will not see these objects in the Glacier console -- they will remain in the S3 console, but if you examine an object that has transitioned, is storage class will change from whatever it was, e.g. STANDARD and will instead say GLACIER.

Do i have to do anything on the glacier end inorder to move my s3 bucket to glacier ?

No, you don't.  As mentioned above, it isn't "your" Glacier account that will store the objects.  On your AWS bill, the charges will appear under S3, but labeled as Glacier, and the price will be the same as the published pricing for Glacier.

My s3 bucket is 6 years old and all the versions of the bucket are even older. But i am not able to see any data in the glacier console though my transition policy is set to move to glacier after 1 day from the creation of the data. Please explain this behavior.

Two parts: first, check the object storage class displayed in the console or with aws s3api list-objects --output=text.  See if you don't see some GLACIER-class objects.  Second, it's a background process.  It won't happen immediately but you should see things changing within 24 to 48 hours of creating the policy.  If you have logging enabled on your bucket, I believe the transition events will also be logged.

Does this policy affect only new files which will be added to the bucket post lifepolicy creation or does this affect all the files in s3 bucket ?

This affects all objects in the bucket.


问:
Twitter - Time Zone of the Tweeet
What is the time zone used for tweets in Twitter API?</p>

答:
The timezone of each tweet is automatically converted to the local timezone. If you need UTC, you can use the .ToUniversalTime() method, for example:

myTweet.CreatedDate.ToUniversalTime();

Title: Twitter - Time Zone of the Tweeet


问:
selectizejs set active option
I'm having an issue with selectizejs and it's selected active option functionality.

If you want an example, a good example is the "Performance" example from selectizejs' github repo.  If you clone it and load it, you'll see what I'm about to explain.

What happens is when you start typing in something, Selectize will set the first option as active and as you type, if that item does not leave the list, it will stay active until it disappears from the list.  What happens is that when you have a larger group (where the options are actually scrolled within a div below the input) the scrolled div will not select the first option when you match against potentially 100 different options and you end up having to scroll up in the div to get back to the first option.

I'm lazy so I'm not linking a jsfiddle that illustrates this.  Rather I'm pointing to their performance example.  Here's how to demonstrate what I'm talking about with that example.  If you type in caa and then push down (to select the second one) then push delete for ca you'll see the active option fall to the bottom of the list.  What I want is that every time the person types in a letter, the first option is always selected whenever the list is refreshed.  Here's the example code from their repo:

```<code>var letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUV';
var options = [];
for (var i = 0; i < 25000; i++) {
    var title = [];
    for (var j = 0; j < 8; j++) {
        title.push(letters.charAt(Math.round((letters.length - 1) * Math.random())));
    }
    options.push({
        id: i,
        title: title.join('')
    });
}
$('#select-junk').selectize({
    maxItems: null,
    maxOptions: 100,
    valueField: 'id',
    labelField: 'title',
    searchField: 'title',
    sortField: 'title',
    options: options,
    create: false
});
</code>```

Is there a detail I'm missing?  What I tried to do is below to configure this:

```<code>        onType: function() {
            //console.log(this.$dropdown);
            var $options = $('.option', this.$dropdown);
            $options.each(function() {
                $(this).removeClass('active');
            });
            $($options[0]).addClass('active');
            $('.selectize-dropdown-content', this.$dropdown).scrollTop(0);
            this.setValue($($options[0]).text());
        }
</code>```

This works for the most part except that when I push enter it selects the active item PRIOR to me forcing the active option to being the first one.  Is there a quick way to make this happen rather than digging into the plugin to customize it?  Thanks for your input!

答:
I figured it out just for someone else in the future.  After analyzing the plugin, I found setActiveOption and this works:

```<code>        onType: function() {
            var $options = $('.option', this.$dropdown);
            this.setActiveOption($($options[0]));
        }
</code>```

Set the active option to the first element.

Title: selectizejs set active option

Body:
I'm having an issue with selectizejs and it's selected active option functionality.

If you want an example, a good example is the "Performance" example from selectizejs' github repo.  If you clone it and load it, you'll see what I'm about to explain.

What happens is when you start typing in something, Selectize will set the first option as active and as you type, if that item does not leave the list, it will stay active until it disappears from the list.  What happens is that when you have a larger group (where the options are actually scrolled within a div below the input) the scrolled div will not select the first option when you match against potentially 100 different options and you end up having to scroll up in the div to get back to the first option.

I'm lazy so I'm not linking a jsfiddle that illustrates this.  Rather I'm pointing to their performance example.  Here's how to demonstrate what I'm talking about with that example.  If you type in caa and then push down (to select the second one) then push delete for ca you'll see the active option fall to the bottom of the list.  What I want is that every time the person types in a letter, the first option is always selected whenever the list is refreshed.  Here's the example code from their repo:

var letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUV';
var options = [];
for (var i = 0; i < 25000; i++) {
    var title = [];
    for (var j = 0; j < 8; j++) {
        title.push(letters.charAt(Math.round((letters.length - 1) * Math.random())));
    }
    options.push({
        id: i,
        title: title.join('')
    });
}
$('#select-junk').selectize({
    maxItems: null,
    maxOptions: 100,
    valueField: 'id',
    labelField: 'title',
    searchField: 'title',
    sortField: 'title',
    options: options,
    create: false
});

Is there a detail I'm missing?  What I tried to do is below to configure this:

        onType: function() {
            //console.log(this.$dropdown);
            var $options = $('.option', this.$dropdown);
            $options.each(function() {
                $(this).removeClass('active');
            });
            $($options[0]).addClass('active');
            $('.selectize-dropdown-content', this.$dropdown).scrollTop(0);
            this.setValue($($options[0]).text());
        }

This works for the most part except that when I push enter it selects the active item PRIOR to me forcing the active option to being the first one.  Is there a quick way to make this happen rather than digging into the plugin to customize it?  Thanks for your input!

Body:
I figured it out just for someone else in the future.  After analyzing the plugin, I found setActiveOption and this works:

        onType: function() {
            var $options = $('.option', this.$dropdown);
            this.setActiveOption($($options[0]));
        }

Set the active option to the first element.


问:
Pandas - set datetime / Timestamp value with apply
Lets consider the following dataframe:

```<code>a=pd.DataFrame(data=list(range(10)))
</code>```

Trying to create a new column from it with apply:
The column is supposed to contain Timestamp object

```<code>def test(x):
    x["date"]=pd.Timestamp("2017-01-01")
    return x

a.apply(test,axis=1)
</code>```

However this result in a dataframe containing the .value numerical attribute of the timestamp:

```<code>    0   date
0   0   1483228800000000000
1   1   1483228800000000000
2   2   1483228800000000000
3   3   1483228800000000000
4   4   1483228800000000000
5   5   1483228800000000000
6   6   1483228800000000000
7   7   1483228800000000000
8   8   1483228800000000000
9   9   1483228800000000000
</code>```

How come it is so? How can I get the correct Timestamp in the DataFrame?

Edit: here the full code that is giving me problem:
This is for respondant to understand that i am not trying to set a simply formed list of datetimes to a new column:

```<code>def mae(x):
    entry=x.name[0]
    exit=x.name[1]
    m=d.loc[entry:exit,"close"]
    if x.dir==-1:
        r=(m.sub(m[::-1].cummax()[::-1])).abs().max()
        imax=(m.sub(m[::-1].cummax()[::-1])).idxmin()
    elif x.dir==1:
        r=(m.sub(m[::-1].cummin()[::-1])).abs().max()
        imax=(m.sub(m[::-1].cummin()[::-1])).idxmax()
    else: r=0
    x['mae']=r*gbp['multiplier']
    x['peak']=imax
    return x

k=g.head().apply(mae,axis=1)
</code>```

This takes as input another dataframe and some financial prices data stored in a database - so a bit difficult to invent an example that at the same time is simple enough for people to grab it quickly and complicated enough as to justify the use of .apply.

I think there is something i dont understand / or a bug in the .apply function - this is what i would like to have input and help on. Thanks guys!

答:
a few rounds of debugging with your code and further into pandas, it seems there was something you can improve in your code.

you can read more details in _setitem_with_indexer, line 387-393
and in numpy.concatenate

In short, _setitem_with_indexer makes use of numpy.concatenate as part of setting new values using indexer.

Because your first column in a had only integers and your new column a['date'] was trying to concatenate an integer, with a pandas.Timestamp(it's actually a numpy.datetime64),
numpy simply refused to do that.

to show that this is the case, we can illustrate by following examples.

Setup

```<code>import pandas as pd
import numpy as np

s1 = [1]

s2 = np.array([np.datetime64("2017-01-01")])

s3 = [pd.Timestamp("2017-01-01")]

a = pd.DataFrame(data=pd.date_range("01-01-2017", "01-06-2017"))

b = pd.DataFrame(data=["d", "c", "d", "d"])

c = pd.DataFrame(data=list(range(10)))

def test(x):
    x["date"]=pd.Timestamp("2017-01-01")
    return x
</code>```

Trials

```<code>a.apply(test, axis=1)

# output

           0       date
0 2017-01-01 2017-01-01
1 2017-01-02 2017-01-01
2 2017-01-03 2017-01-01
3 2017-01-04 2017-01-01
4 2017-01-05 2017-01-01
5 2017-01-06 2017-01-01

b.apply(test, axis=1)

# output

   0                 date
0  d  1483228800000000000
1  c  1483228800000000000
2  d  1483228800000000000
3  d  1483228800000000000

c.apply(test,axis=1)

# output

   0                 date
0  0  1483228800000000000
1  1  1483228800000000000
2  2  1483228800000000000
3  3  1483228800000000000
4  4  1483228800000000000
5  5  1483228800000000000
6  6  1483228800000000000
7  7  1483228800000000000
8  8  1483228800000000000
9  9  1483228800000000000
</code>```

I think this is more behaviour of numpy.concatenate. if we choose to
use pd.Timestamp we will observe different behaviour, which essentially would succeed in concatenation; but not the same with numpy.datetime64, which is what's used inside _setitem_with_indexer.

Observation

```<code>np.concatenate([s1,s2])

# output
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: invalid type promotion
invalid type promotion

np.concatenate([s1,s3])

# output

array([1, Timestamp('2017-01-01 00:00:00')], dtype=object)
***please note here dtype is object***
</code>```

As for cleanness or elegance, I think Wen's comment is already very minimal, but you might have a reason for using apply.

one more thing to point out is, apply takes in a function that does something on each column/row, but it seems you were trying to use the function arg as a DataFrame.

Body:
Lets consider the following dataframe:

a=pd.DataFrame(data=list(range(10)))

Trying to create a new column from it with apply:
The column is supposed to contain Timestamp object

def test(x):
    x["date"]=pd.Timestamp("2017-01-01")
    return x

a.apply(test,axis=1)

However this result in a dataframe containing the .value numerical attribute of the timestamp:

    0   date
0   0   1483228800000000000
1   1   1483228800000000000
2   2   1483228800000000000
3   3   1483228800000000000
4   4   1483228800000000000
5   5   1483228800000000000
6   6   1483228800000000000
7   7   1483228800000000000
8   8   1483228800000000000
9   9   1483228800000000000

How come it is so? How can I get the correct Timestamp in the DataFrame?

Edit: here the full code that is giving me problem:
This is for respondant to understand that i am not trying to set a simply formed list of datetimes to a new column:

def mae(x):
    entry=x.name[0]
    exit=x.name[1]
    m=d.loc[entry:exit,"close"]
    if x.dir==-1:
        r=(m.sub(m[::-1].cummax()[::-1])).abs().max()
        imax=(m.sub(m[::-1].cummax()[::-1])).idxmin()
    elif x.dir==1:
        r=(m.sub(m[::-1].cummin()[::-1])).abs().max()
        imax=(m.sub(m[::-1].cummin()[::-1])).idxmax()
    else: r=0
    x['mae']=r*gbp['multiplier']
    x['peak']=imax
    return x

k=g.head().apply(mae,axis=1)

This takes as input another dataframe and some financial prices data stored in a database - so a bit difficult to invent an example that at the same time is simple enough for people to grab it quickly and complicated enough as to justify the use of .apply.

I think there is something i dont understand / or a bug in the .apply function - this is what i would like to have input and help on. Thanks guys!

Body:
a few rounds of debugging with your code and further into pandas, it seems there was something you can improve in your code.

you can read more details in _setitem_with_indexer, line 387-393
and in numpy.concatenate

In short, _setitem_with_indexer makes use of numpy.concatenate as part of setting new values using indexer.

Because your first column in a had only integers and your new column a['date'] was trying to concatenate an integer, with a pandas.Timestamp(it's actually a numpy.datetime64),
numpy simply refused to do that.

to show that this is the case, we can illustrate by following examples.

Setup

import pandas as pd
import numpy as np

s1 = [1]

s2 = np.array([np.datetime64("2017-01-01")])

s3 = [pd.Timestamp("2017-01-01")]

a = pd.DataFrame(data=pd.date_range("01-01-2017", "01-06-2017"))

b = pd.DataFrame(data=["d", "c", "d", "d"])

c = pd.DataFrame(data=list(range(10)))

def test(x):
    x["date"]=pd.Timestamp("2017-01-01")
    return x

Trials

a.apply(test, axis=1)

# output

           0       date
0 2017-01-01 2017-01-01
1 2017-01-02 2017-01-01
2 2017-01-03 2017-01-01
3 2017-01-04 2017-01-01
4 2017-01-05 2017-01-01
5 2017-01-06 2017-01-01

b.apply(test, axis=1)

# output

   0                 date
0  d  1483228800000000000
1  c  1483228800000000000
2  d  1483228800000000000
3  d  1483228800000000000

c.apply(test,axis=1)

# output

   0                 date
0  0  1483228800000000000
1  1  1483228800000000000
2  2  1483228800000000000
3  3  1483228800000000000
4  4  1483228800000000000
5  5  1483228800000000000
6  6  1483228800000000000
7  7  1483228800000000000
8  8  1483228800000000000
9  9  1483228800000000000

I think this is more behaviour of numpy.concatenate. if we choose to
use pd.Timestamp we will observe different behaviour, which essentially would succeed in concatenation; but not the same with numpy.datetime64, which is what's used inside _setitem_with_indexer.

Observation

np.concatenate([s1,s2])

# output
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: invalid type promotion
invalid type promotion

np.concatenate([s1,s3])

# output

array([1, Timestamp('2017-01-01 00:00:00')], dtype=object)
***please note here dtype is object***

As for cleanness or elegance, I think Wen's comment is already very minimal, but you might have a reason for using apply.

one more thing to point out is, apply takes in a function that does something on each column/row, but it seems you were trying to use the function arg as a DataFrame.


问:
summing dict value of list to single integer
I am trying to do something pretty simple but cant seem to get it. I have a dictionary where the value is a list. I am trying to just sum the list and assign the value back to the same key as an int. Using the code below the first line doesn't do anything, the second as it says puts the value back but in a list. All other things ive tried has given me an error can only assign iterable. As far as i know iterables are anything that can be iterated on such as list and not int. Why can I only use iterable and how can i fix this issue ? The dict im using is here (https://gist.github.com/ishikawa-rei/53c100449605e370ef66f1c06f15b62e)</p>

```<code>for i in dict.values():
    i = sum(i)
    #i[:] = [sum(i) / 3600] # puts answer into dict but as a list
</code>```

答:
You can use simple dictionary comprehension if your dict values are all lists</p>

```<code>{k:sum(v) for k, v in dict.items()}
</code>```

Body:
I am trying to do something pretty simple but cant seem to get it. I have a dictionary where the value is a list. I am trying to just sum the list and assign the value back to the same key as an int. Using the code below the first line doesn't do anything, the second as it says puts the value back but in a list. All other things ive tried has given me an error can only assign iterable. As far as i know iterables are anything that can be iterated on such as list and not int. Why can I only use iterable and how can i fix this issue ? The dict im using is here (https://gist.github.com/ishikawa-rei/53c100449605e370ef66f1c06f15b62e)

for i in dict.values():
    i = sum(i)
    #i[:] = [sum(i) / 3600] # puts answer into dict but as a list

Body:
You can use simple dictionary comprehension if your dict values are all lists

{k:sum(v) for k, v in dict.items()}


问:
Angular 2/4 & RxJS - Subscriptions within forEach - Ensuring flow control doesn't continue until all Observables are complete
The goal is to iterate through a collection of IDs, making an HTTP call for each ID. For each ID, I'm using a service with a get() method that returns an Observable. Each time the get() method is called, I'm subscribing to the returning Observable and trying to push the result into an array, which will eventually get passed on to a different method for a new operation.

Relevant service method:

```<code>public get(departmentId: number): Observable<IDepartmentModel> {
    return super.get<IDepartmentModel>(departmentId);
}
</code>```

note: the super class is leveraging Angular Http, which is well tested and confirmed to be working correctly. The problem with the logic isn't here...

Relevant component methods:
note the departmentService.get() call that's being called several times within the forEach.

```<code> setInitialDepartmentsAssignedGridData(): void {
    this.settingsForDropdownSelectedCompanyId = this.userForm.get('defaultCompany').get('defaultCompanyId').value;

    let departments: IDepartmentModel[] = [];

    this.userService.user.getValue() //confirmed: valid user is being pulled back from the userService (logic is fine here..)
        .userCompanies.find(comp => comp.companyId === this.settingsForDropdownSelectedCompanyId) // getting a valid match here (logic is fine here..)
        .departmentIds.forEach(deptId => this.departmentService.get(deptId).first().subscribe(dept => { // getting a valid department back here (logic is fine here...)
            departments.push(dept); // HERE LIES THE PROBLEM
    }));

    this.setDepartmentsAssignedRowData(departments);
}

 setDepartmentsAssignedRowData(departments: IDepartmentModel[]): void {
    console.log('setDeptAssignedRowData called'); // confirmed: method is getting called...
    console.log(departments); // confirmed: fully-composed collection of departments logged to the console...

    departments.forEach(dept => {
        console.log(dept);
    }); // Y U NO WORK!?

    departments.map((department) => {
        console.log(department); // Y U NO WORK?
        this.departmentAssignedRowData.push({
            departmentId: department.id,
            departmentName: department.name
        });
    });

    this.departmentAssignedGridOptions.api.setRowData(this.departmentAssignedRowData);
}
</code>```

The problem is, although what's getting logged to the console is a fully-composed department-objects array, it's not TRULY "there"; what's getting passed to setDepartmentsAssignedRowData is an empty array.

I'm sure what's happening is that the async operations are not complete before the departments array gets passed to the second method. Some of what I've read online says to use forkJoin, but I can't see how that will look in this context. I've also read concatMap may work, but again, in this context, I'm not sure how to make that work...

In this context, how do I leverage RxJS to make sure the intended, fully-composed departments array is truly ready to be passed?

thanks for any insight you can provide. help is much appreciated!

答:
You are correct, you need forkJoin

```<code>let observableArray = this.userService.user.getValue()
    .userCompanies.find(comp => comp.companyId === this.settingsForDropdownSelectedCompanyId)
    .departmentIds.map(deptId => this.departmentService.get(deptId)) // map is building out an array of observables
</code>```

This will be an array of http request observables that you want to make in parallel. Now you can pass this array to forkJoin.

```<code>Observable.forkJoin(...observableArray)
</code>```

The return of forkJoin will be an array of results from observableArray. forkJoin will not emit to the next operator in the sequence until all of the observables in observableArray have completed (so when all of the http requests have finished)

So altogether the code will be

```<code>let observableArray = this.userService.user.getValue()
    .userCompanies.find(comp => comp.companyId === this.settingsForDropdownSelectedCompanyId)
    .departmentIds.map(deptId => this.departmentService.get(deptId));

Observable.forkJoin(...observableArray).subscribe(res => {
    // res = [resId0, resId1, resId2, ..., resIdX];
});
</code>```

You mentioned passing the result to another operator. If that operator is another http request where you pass an array of data (from forkJoin), then you can use the flatMap operator.

```<code>Observable.forkJoin(...observableArray)
    .flatMap(res => {
        return this.otherApi(res);
    })
    .subscribe(res => {
        // res is the result of the otherApi call
    });
</code>```

flatMap will chain your api requests together. So altogether what is happening is

run array of observables in parallel

once complete, run second api (otherApi)

Body:
The goal is to iterate through a collection of IDs, making an HTTP call for each ID. For each ID, I'm using a service with a get() method that returns an Observable. Each time the get() method is called, I'm subscribing to the returning Observable and trying to push the result into an array, which will eventually get passed on to a different method for a new operation.

Relevant service method:

public get(departmentId: number): Observable<IDepartmentModel> {
    return super.get<IDepartmentModel>(departmentId);
}

note: the super class is leveraging Angular Http, which is well tested and confirmed to be working correctly. The problem with the logic isn't here...

Relevant component methods:
note the departmentService.get() call that's being called several times within the forEach.

 setInitialDepartmentsAssignedGridData(): void {
    this.settingsForDropdownSelectedCompanyId = this.userForm.get('defaultCompany').get('defaultCompanyId').value;

    let departments: IDepartmentModel[] = [];

    this.userService.user.getValue() //confirmed: valid user is being pulled back from the userService (logic is fine here..)
        .userCompanies.find(comp => comp.companyId === this.settingsForDropdownSelectedCompanyId) // getting a valid match here (logic is fine here..)
        .departmentIds.forEach(deptId => this.departmentService.get(deptId).first().subscribe(dept => { // getting a valid department back here (logic is fine here...)
            departments.push(dept); // HERE LIES THE PROBLEM
    }));

    this.setDepartmentsAssignedRowData(departments);
}

 setDepartmentsAssignedRowData(departments: IDepartmentModel[]): void {
    console.log('setDeptAssignedRowData called'); // confirmed: method is getting called...
    console.log(departments); // confirmed: fully-composed collection of departments logged to the console...

    departments.forEach(dept => {
        console.log(dept);
    }); // Y U NO WORK!?

    departments.map((department) => {
        console.log(department); // Y U NO WORK?
        this.departmentAssignedRowData.push({
            departmentId: department.id,
            departmentName: department.name
        });
    });

    this.departmentAssignedGridOptions.api.setRowData(this.departmentAssignedRowData);
}

The problem is, although what's getting logged to the console is a fully-composed department-objects array, it's not TRULY "there"; what's getting passed to setDepartmentsAssignedRowData is an empty array.

I'm sure what's happening is that the async operations are not complete before the departments array gets passed to the second method. Some of what I've read online says to use forkJoin, but I can't see how that will look in this context. I've also read concatMap may work, but again, in this context, I'm not sure how to make that work...

In this context, how do I leverage RxJS to make sure the intended, fully-composed departments array is truly ready to be passed?

thanks for any insight you can provide. help is much appreciated!

Body:
You are correct, you need forkJoin

let observableArray = this.userService.user.getValue()
    .userCompanies.find(comp => comp.companyId === this.settingsForDropdownSelectedCompanyId)
    .departmentIds.map(deptId => this.departmentService.get(deptId)) // map is building out an array of observables

This will be an array of http request observables that you want to make in parallel. Now you can pass this array to forkJoin.

Observable.forkJoin(...observableArray)

The return of forkJoin will be an array of results from observableArray. forkJoin will not emit to the next operator in the sequence until all of the observables in observableArray have completed (so when all of the http requests have finished)

So altogether the code will be

let observableArray = this.userService.user.getValue()
    .userCompanies.find(comp => comp.companyId === this.settingsForDropdownSelectedCompanyId)
    .departmentIds.map(deptId => this.departmentService.get(deptId));

Observable.forkJoin(...observableArray).subscribe(res => {
    // res = [resId0, resId1, resId2, ..., resIdX];
});

You mentioned passing the result to another operator. If that operator is another http request where you pass an array of data (from forkJoin), then you can use the flatMap operator.

Observable.forkJoin(...observableArray)
    .flatMap(res => {
        return this.otherApi(res);
    })
    .subscribe(res => {
        // res is the result of the otherApi call
    });

flatMap will chain your api requests together. So altogether what is happening is

run array of observables in parallel

once complete, run second api (otherApi)


问:
Set operation to divide lists by one another in Scala
Right now I have 2 lists in Scala:

```<code>val one = List(50, 10, 17, 8, 16)
val two = List(582, 180, 174, 159, 158)
</code>```

These lists are going to be of the same length, and right now I'm looking to divide each element of the first list by a corresponding element in the second. In other words, I want a list that consists of:

```<code>List(50/582, 10/180, etc...)
</code>```

Is there a set operation that accomplishes this that can be done without looping?

Thank you!

答:
You can use the zip function.</p>

```<code>val one = List(50, 10, 17, 8, 16)
val two = List(582, 180, 174, 159, 158)
one.zip(two).map {
      case (a, b) => a.toDouble/b.toDouble
     }
</code>```

Body:
Right now I have 2 lists in Scala:

val one = List(50, 10, 17, 8, 16)
val two = List(582, 180, 174, 159, 158)

These lists are going to be of the same length, and right now I'm looking to divide each element of the first list by a corresponding element in the second. In other words, I want a list that consists of:

List(50/582, 10/180, etc...)

Is there a set operation that accomplishes this that can be done without looping?

Thank you!

Body:
You can use the zip function.

val one = List(50, 10, 17, 8, 16)
val two = List(582, 180, 174, 159, 158)
one.zip(two).map {
      case (a, b) => a.toDouble/b.toDouble
     }


问:
How to connect to two databases in rake task
I need to create a rake task to migrate some information from an older web app to our new web app, so in the task I need to connect to two databases, how can I open a connection to another database without using active record?</p>

答:
If you want to use mysql then you can do like this

```<code>require 'mysql'

mysql = Mysql.init()
mysql.connect('localhost')

mysql.select_db('test')

results = mysql.query("SELECT now();")

results.each{|row|; puts row;}

mysql.close()
</code>```

Hope this will help you.

Body:
If you want to use mysql then you can do like this

require 'mysql'

mysql = Mysql.init()
mysql.connect('localhost')

mysql.select_db('test')

results = mysql.query("SELECT now();")

results.each{|row|; puts row;}

mysql.close()

Hope this will help you.


问:
BeautifulSoup: find all tags before stopping condition is met
I'm trying to extract a class tag from an HTML file, but only if it is located before a given stopping point. What I have is:

```<code>import requests
from bs4 import BeautifulSoup

page = requests.get("https://mysite")
soup = BeautifulSoup(page.content, 'html.parser')
class_extr = soup.find_all("span", class_="myclass")
</code>```

This works, but it finds all instances of myclass, and i only want those before the following text shows in the soup:

```<code><h4 class="cat-title" id="55">
 Title text N1
 <small>
  Title text N2.
 </small>
</h4>
</code>```

The thing that makes this block unique are the Title text N lines, especially the Title text N2. line. There are many cat-title tags before, so I can't use that as a stopping condition.

The code surrounding this block looks like this:

```<code>...
<div class="myc">
<a class="bbb" href="linkhere_893">
<span class="myclass">Text893</span>
<img data-lazy="https://link893.jpg"/>
</a>
</div>
<div class="myc">
<a class="bbb" href="linkhere_96">
<span class="myclass">Text96</span>
<img data-lazy="https://link96.jpg"/>
</a>
</div>
</div><!-- This closes a list that starts above -->
<h4 class="cat-title" id="55">Title text N1 <small> Title text N2.</small></h4>
<div class="list" id="55">
<div class="myc">
<a class="bbb" href="linkhere_34">
<span class="myclass">Text34</span>
<img data-lazy="https://link34.jpg"/>
</a>
</div>
<div class="myc">
...
</code>```

continuing both above and below.

How can I do this?

答:
Try using find_all_previous():

```<code>import requests
from bs4 import BeautifulSoup

page = requests.get("https://mysite")
soup = BeautifulSoup(page.content, 'html.parser')
stop_at = soup.find("h4", class_="cat-title", id='55') # finds your stop tag
class_extr = stop_at.find_all_previous("span", class_="myclass")
</code>```

This will stop at the first
 tag in the event that there are multiple.

Reference: Beautiful Soup Documentation

Body:
I'm trying to extract a class tag from an HTML file, but only if it is located before a given stopping point. What I have is:

import requests
from bs4 import BeautifulSoup

page = requests.get("https://mysite")
soup = BeautifulSoup(page.content, 'html.parser')
class_extr = soup.find_all("span", class_="myclass")

This works, but it finds all instances of myclass, and i only want those before the following text shows in the soup:

 Title text N1

  Title text N2.

The thing that makes this block unique are the Title text N lines, especially the Title text N2. line. There are many cat-title tags before, so I can't use that as a stopping condition.

The code surrounding this block looks like this:

...

Text893

Text96

Title text N1  Title text N2.

Text34

...

continuing both above and below.

How can I do this?

Body:
Try using find_all_previous():

import requests
from bs4 import BeautifulSoup

page = requests.get("https://mysite")
soup = BeautifulSoup(page.content, 'html.parser')
stop_at = soup.find("h4", class_="cat-title", id='55') # finds your stop tag
class_extr = stop_at.find_all_previous("span", class_="myclass")

This will stop at the first <h4 class='cat-title', id=55> tag in the event that there are multiple.

Reference: Beautiful Soup Documentation


问:
Parsing and Solving a Formula in Java SE 8

Disclaimer: Not Homework

I've written very basic calculator parsers in Java using tokenizers, but I have recently started writing a problem to help me understand chemistry. As I began writing more and more formulas, it became increasingly apparent that the complexity required to solve for each equation is almost more tedious than mastery of the equations themselves. Take the equation PV = nRT, how could I write a parser that would allow me to input all know variables and solve if it was solvable? I can do the logic behind solvability, but here are a few requirements:

must be able to solve for any unknown variable.

parsing should be capable for formulas of any size (ex: I want to implement more than one formula, such as π = MRT and formulas of increasing complexity, and only want to have to define them once.)

Once again this is purely for my enjoyment and to be used as a learning tool. Any help would be appreciated, as searching Google and StackOverflow for this problem have given me either vague or inapplicable answers.

答:
As you have posted no code I will speak my thoughts.

I used to have an hp48G calculator which had a library with many formulas covering different areas.

Instead of parsing a single line, you had to choose through menus which was the formula to apply, then the calculator would ask for each parameter separately, and apply it to the formula to provide the result.

If you follow this approach, and helped with java's interfaces I think you can do something like you are asking.


问:
How do i tell the browser to use cache manifest if the browser doesn't support service workers?
How do i tell the browser to use cache manifest if the browser doesn't support service workers?

I have an Angular 4 app that needs to run offline. Service workers do the job brilliantly but it isn't supported by Safari which is a required browser that it needs to run on.

I need to generate a cache manifest file if service workers is not supported by the browser then for the browser to use the cache manifest file once the browser goes offline

current code (typescript):

```<code>if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('../../service-worker.js').then(function(registration) {
    //TODO: Implement Logging
  }).catch(function(err) {
    //TODO: Implement Logging
  });
} else {
  //Not currently supported on Internet explorer, Safari, IE Mobile and Safari Mobile. Use old Application Caching instead.
  console.log("Not Supported");
  //Use cache manifest
}
</code>```

答:
The appCache manifest is supported by iOS. This is how we made sites work offline for the past decade.
If a page references an appCache manifest and a service worker, browsers that support service workers ignore appCache.

Also I think you are confusing web manifest with appCache manifest. They are two distinct things. appCache manages how to cache files for offline. A web manifest file provides meta data to the browser so it knows how to brand and rendering your site once it is added to the hone screen.

FWIW I have been building offline/mobile first web apps that rival native apps on iOS using appCache and localStorage/IndexedDB since about 2010. So you can absolutely do it :)

This is a presentation I gave at Velocity a few years ago https://youtu.be/GKxkzu0pHUc It might help you out.

Body:
How do i tell the browser to use cache manifest if the browser doesn't support service workers?

I have an Angular 4 app that needs to run offline. Service workers do the job brilliantly but it isn't supported by Safari which is a required browser that it needs to run on.

I need to generate a cache manifest file if service workers is not supported by the browser then for the browser to use the cache manifest file once the browser goes offline

current code (typescript):

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('../../service-worker.js').then(function(registration) {
    //TODO: Implement Logging
  }).catch(function(err) {
    //TODO: Implement Logging
  });
} else {
  //Not currently supported on Internet explorer, Safari, IE Mobile and Safari Mobile. Use old Application Caching instead.
  console.log("Not Supported");
  //Use cache manifest
}


问:
Regular Expression to accept only 0,1,(,),|,&
I am trying to create a regular expression that contains only below 6 characters in a string

0,1,(,),|,&

I came up with this regular expression

^[0-1\|()\&]$

But it seems to fail even when valid string is given as input. As below

```<code>const inputStr = "(0&(1&(1|0))";
const validateStr = new RegExp("^[0-1\|\(\)\&]$");
const isValid = validateStr.test(inputStr);
</code>```

Above need to be returned true, but the output of isValid is false. Please let me know where I am doing wrong.

答:
You need to add a plus after your character set to search the whole string!

const inputStr = "(0&(1&(1|0))";
const validateStr = new RegExp(/^[0-1()|&]+$/);
const isValid = validateStr.test(inputStr);
console.log(isValid);```

Body:
I am trying to create a regular expression that contains only below 6 characters in a string

0,1,(,),|,&

I came up with this regular expression

^[0-1\|()\&]$

But it seems to fail even when valid string is given as input. As below

const inputStr = "(0&(1&(1|0))";
const validateStr = new RegExp("^[0-1\|\(\)\&]$");
const isValid = validateStr.test(inputStr);

Above need to be returned true, but the output of isValid is false. Please let me know where I am doing wrong.


问:
File handling operetions in C
Can anyone point me to a reference or a beginner's tutorial for file handling in C.</p>

答:
You open a file with fopen:

```<code>FILE *file=fopen("filename", "r"); // opens a file for reading
if(file) {
    // success
}else{
    // error
}
</code>```

If you replace r with w, then it will be opened for writing. If you include b in the mode string, it will be opened as binary instead of text, which is the default. (in text mode it does some conversions such as line endings and such) If you use r+, it will open it for both reading and writing. If you use w+, it will truncate the file and open it for reading and writing. You can also use a to append to the file.

To read from a file, use fread or fgets:

```<code>char buffer[256];
if(fgets(buffer, sizeof(buffer), file)) { // reads a line from the file
    // success
}else{
    // error
}
if(fread(buffer, sizeof(buffer), 1, file)==1) { // reads 256 bytes from the file
    // success
}else{
    // error
}
</code>```

To write to a file, use fwrite or fputs:

```<code>if(fputs("Hello, world!", file)==0) { // writes a line to the file
    // success
}else{
    // error
}
// ---OR---
const char *data="Hello, world!";
if(fwrite(data, sizeof(data), 1, file)==1) { // writes some data to the file
    // success
}else{
    // error
}
</code>```

Once you're done with a file, you close it with fclose:

```<code>if(fclose(file)==0) {
    // success
}else{
    // error
}
</code>```

Title: File handling operetions in C

Body:
You open a file with fopen:

FILE *file=fopen("filename", "r"); // opens a file for reading
if(file) {
    // success
}else{
    // error
}

If you replace r with w, then it will be opened for writing. If you include b in the mode string, it will be opened as binary instead of text, which is the default. (in text mode it does some conversions such as line endings and such) If you use r+, it will open it for both reading and writing. If you use w+, it will truncate the file and open it for reading and writing. You can also use a to append to the file.

To read from a file, use fread or fgets:

char buffer[256];
if(fgets(buffer, sizeof(buffer), file)) { // reads a line from the file
    // success
}else{
    // error
}
if(fread(buffer, sizeof(buffer), 1, file)==1) { // reads 256 bytes from the file
    // success
}else{
    // error
}

To write to a file, use fwrite or fputs:

if(fputs("Hello, world!", file)==0) { // writes a line to the file
    // success
}else{
    // error
}
// ---OR---
const char *data="Hello, world!";
if(fwrite(data, sizeof(data), 1, file)==1) { // writes some data to the file
    // success
}else{
    // error
}

Once you're done with a file, you close it with fclose:

if(fclose(file)==0) {
    // success
}else{
    // error
}


问:
Installing opencv on Windows 10 with python 3.6 and anaconda 3.6
How to install opencv with python 3.6 and anaconda 3.6?

I tried conda install -c https://conda.binstar.org/menpo opencv3

but i get the following error:

```<code>UnsatisfiableError: The following specifications were found to be in conflict:
  - opencv3 -> python 2.7*
  - python 3.6*
Use "conda info <package>" to see the dependencies for each package.
</code>```

I am using Windows 10 64-bit, with python 3.6, and anaconda 3.6 installed.

Is it even available for python3.6 at the moment or should i rollback my python version to 3.5.*?

答:
Using:

conda install -c conda-forge opencv

worked for me

Body:
How to install opencv with python 3.6 and anaconda 3.6?

I tried conda install -c https://conda.binstar.org/menpo opencv3

but i get the following error:

UnsatisfiableError: The following specifications were found to be in conflict:
  - opencv3 -> python 2.7*
  - python 3.6*
Use "conda info <package>" to see the dependencies for each package.

I am using Windows 10 64-bit, with python 3.6, and anaconda 3.6 installed.

Is it even available for python3.6 at the moment or should i rollback my python version to 3.5.*?


问:
Use sed or awk to remove lines not adjacent to pattern in bash

I need to delete any line that is not surrounding a ">" symbol.

Here is some sample data:

```<code>sample1.fasta
>R00003
ATCATACTACTACG
sample2.fasta
sample3.fasta
sample4.fasta
>R00003
ATACTACGTA
sample7.fasta
>R00003
ATGCATCAT
sample8.fasta
>R00003
AATCATCGACCT
sample9.fasta
sample10.fasta
>R00003
AGCATCTCAGTC
</code>```

I tried using awk to help reveal the issue:

```<code>awk '{/fasta/?f++:f=0} f==2' R3.fasta
</code>```

This returns:

```<code>sample3.fasta
sample10.fasta
</code>```

This is diagnostic in that it shows where duplicates are present. However, I want to remove the lines that are not flanking the ">" symbol on either side. This does not remove them and only displays the second.

The result I expect is:

```<code>sample1.fasta
>R00003
ATCATACTACTACG
sample4.fasta
>R00003
ATACTACGTA
sample7.fasta
>R00003
ATGCATCAT
sample8.fasta
>R00003
AATCATCGACCT
sample10.fasta
>R0003
AGCATCTCAGTC
</code>```

Where the lines not flaking the ">" symbol have been removed

答:
Seems like the plain grep will suffice for this:

```<code>grep '^>' -C1 file | grep -v ^--$
</code>```

First print one line above and one line below each line starting with > (use context -C1), then just filter out the -- lines that grep inserts to separate each context.

But if you prefer awk:

```<code>awk '/^>/{print a ORS $0; getline; print} {a=$0}' file
</code>```

Keep the previous line in a, and when a line starts with >, print the previous line (in a), the current line, and the next line (which we get with getline).

Body:
I need to delete any line that is not surrounding a ">" symbol.

Here is some sample data:

sample1.fasta
>R00003
ATCATACTACTACG
sample2.fasta
sample3.fasta
sample4.fasta
>R00003
ATACTACGTA
sample7.fasta
>R00003
ATGCATCAT
sample8.fasta
>R00003
AATCATCGACCT
sample9.fasta
sample10.fasta
>R00003
AGCATCTCAGTC

I tried using awk to help reveal the issue:

awk '{/fasta/?f++:f=0} f==2' R3.fasta

This returns:

sample3.fasta
sample10.fasta

This is diagnostic in that it shows where duplicates are present. However, I want to remove the lines that are not flanking the ">" symbol on either side. This does not remove them and only displays the second.

The result I expect is:

sample1.fasta
>R00003
ATCATACTACTACG
sample4.fasta
>R00003
ATACTACGTA
sample7.fasta
>R00003
ATGCATCAT
sample8.fasta
>R00003
AATCATCGACCT
sample10.fasta
>R0003
AGCATCTCAGTC

Where the lines not flaking the ">" symbol have been removed

Body:
Seems like the plain grep will suffice for this:

grep '^>' -C1 file | grep -v ^--$

First print one line above and one line below each line starting with > (use context -C1), then just filter out the -- lines that grep inserts to separate each context.

But if you prefer awk:

awk '/^>/{print a ORS $0; getline; print} {a=$0}' file

Keep the previous line in a, and when a line starts with >, print the previous line (in a), the current line, and the next line (which we get with getline).


问:
Linux script for which needs to input password automatically and runs background (No expect and send)
I am writing a script which is intended to run every day. Script also consists of a command where I need to input my password lets say abcd every time it execute. Is there any way that I can input password automatically when it ask for "Password:"
Thanks</p>

答:
Actually it depends on the structure of your script. 2 alternatives on my mind;

Most of the (commonly-used) CLI executables has its own parameter set to provide password / user / credentials. Let me show MySQL for example;

```<code>shell> mysql --host=localhost --user=myname --password=password mydb
</code>```

If commands you're using are not appropriate to do that; you can consider using "expect" as follows;

```<code>set password 123
spawn ssh "root@192.168.1.1"
expect "Password:"
send "$password\r";
interact
</code>```

See that link for more details.

Body:
Actually it depends on the structure of your script. 2 alternatives on my mind;

Most of the (commonly-used) CLI executables has its own parameter set to provide password / user / credentials. Let me show MySQL for example;

shell> mysql --host=localhost --user=myname --password=password mydb

If commands you're using are not appropriate to do that; you can consider using "expect" as follows;

set password 123
spawn ssh "root@192.168.1.1"
expect "Password:"
send "$password\r";
interact

See that link for more details.


问:
Google Sign-In button causing null object reference
I'm trying to implement a Google Sign In button and getting a null object reference error when I call signInButton.setSize(). I initialize the button with findViewById(). I do it in promptSignIn() which is a couple stack levels higher than onCreate(). I tried initializing in onCreate() as other answers suggest, and I get the same error.

YourOrdersActivity.java

```<code>package com.example.mattf.yankeetoyboxv1;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.tasks.Task;

/**
 * Created by mattf on 12/8/2017.
 */

public class SignInActivity extends BaseActivity{

    private GoogleSignInClient mGoogleSignInClient;
    private SignInButton signInButton;
    private static int RC_SIGN_IN=100;
    private static final String TAG="SignInActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        isUserSignedIn();
    }

    @Override
    protected void onStart() {
        super.onStart();

        isUserSignedIn();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode,resultCode,data);

        //Result return from launching the Intent from GoogleSignInClient.getSignInIntent(...);
        if (requestCode == RC_SIGN_IN) {
            // The Task returned from this call is always completed
            // no need to attach a listener
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            handleSignInResult(task);
        }
    }

    private void isUserSignedIn() {
        GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);

        if (account==null){
            promptSignIn();
        }
        else updateUI(account);
    }

    private void promptSignIn() {
        // Configure sign-in to request the user's ID, email address, and basic profile
        // ID and basic profile are included in DEFAULT_SIGN_IN
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();

        // Build a GoogleSignInClient with the options specified by gso
        mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

        // Set the dimensions of the sign-in button
        signInButton = findViewById(R.id.sign_in_button);
        signInButton.setSize(SignInButton.SIZE_STANDARD);
        signInButton.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                signIn();
            }
        });
    }

    private void signIn() {
        Intent signInIntent = mGoogleSignInClient.getSignInIntent();
        startActivityForResult(signInIntent,RC_SIGN_IN);
    }

    private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
        try {
            GoogleSignInAccount account = completedTask.getResult();

            // Signed in successfully, show authenticated UI
            updateUI(account);

        } catch (Exception e) {
            Log.w(TAG, "signInResult:failed code=" + e.getMessage());
        }
    }

    protected void updateUI(GoogleSignInAccount account) {
        if (signInButton != null) signInButton.setVisibility(View.GONE);
    }
}
</code>```

The button is in this XML file which is linked to the YourOrdersActivity.java activity.

your_orders_activity.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.mattf.yankeetoyboxv1.YourOrdersActivity">

    <com.google.android.gms.common.SignInButton
        android:id="@+id/sign_in_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>
</code>```

LogCat

```<code>12-08 20:31:51.624 12373-12373/com.example.mattf.yankeetoyboxv1 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.mattf.yankeetoyboxv1, PID: 12373
                                                                                java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mattf.yankeetoyboxv1/com.example.mattf.yankeetoyboxv1.YourOrdersActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.common.SignInButton.setSize(int)' on a null object reference
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
                                                                                at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:106)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6494)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
                                                                                Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.common.SignInButton.setSize(int)' on a null object reference
                                                                                at com.example.mattf.yankeetoyboxv1.SignInActivity.promptSignIn(SignInActivity.java:72)
                                                                                at com.example.mattf.yankeetoyboxv1.SignInActivity.isUserSignedIn(SignInActivity.java:57)
                                                                                at com.example.mattf.yankeetoyboxv1.SignInActivity.onCreate(SignInActivity.java:30)
                                                                                at android.app.Activity.performCreate(Activity.java:7000)
                                                                                at android.app.Activity.performCreate(Activity.java:6991)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
                                                                                at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:106)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6494)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
</code>```

答:
You are not calling setContentView(R.layout.your_orders_activity) in onCreate method

Your onCreate should be like this:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_orders_activity);
    isUserSignedIn();
}
</code>```

Body:
I'm trying to implement a Google Sign In button and getting a null object reference error when I call signInButton.setSize(). I initialize the button with findViewById(). I do it in promptSignIn() which is a couple stack levels higher than onCreate(). I tried initializing in onCreate() as other answers suggest, and I get the same error.

YourOrdersActivity.java

package com.example.mattf.yankeetoyboxv1;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.tasks.Task;

/**
 * Created by mattf on 12/8/2017.
 */

public class SignInActivity extends BaseActivity{

    private GoogleSignInClient mGoogleSignInClient;
    private SignInButton signInButton;
    private static int RC_SIGN_IN=100;
    private static final String TAG="SignInActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        isUserSignedIn();
    }

    @Override
    protected void onStart() {
        super.onStart();

        isUserSignedIn();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode,resultCode,data);

        //Result return from launching the Intent from GoogleSignInClient.getSignInIntent(...);
        if (requestCode == RC_SIGN_IN) {
            // The Task returned from this call is always completed
            // no need to attach a listener
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            handleSignInResult(task);
        }
    }

    private void isUserSignedIn() {
        GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);

        if (account==null){
            promptSignIn();
        }
        else updateUI(account);
    }

    private void promptSignIn() {
        // Configure sign-in to request the user's ID, email address, and basic profile
        // ID and basic profile are included in DEFAULT_SIGN_IN
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();

        // Build a GoogleSignInClient with the options specified by gso
        mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

        // Set the dimensions of the sign-in button
        signInButton = findViewById(R.id.sign_in_button);
        signInButton.setSize(SignInButton.SIZE_STANDARD);
        signInButton.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                signIn();
            }
        });
    }

    private void signIn() {
        Intent signInIntent = mGoogleSignInClient.getSignInIntent();
        startActivityForResult(signInIntent,RC_SIGN_IN);
    }

    private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
        try {
            GoogleSignInAccount account = completedTask.getResult();

            // Signed in successfully, show authenticated UI
            updateUI(account);

        } catch (Exception e) {
            Log.w(TAG, "signInResult:failed code=" + e.getMessage());
        }
    }

    protected void updateUI(GoogleSignInAccount account) {
        if (signInButton != null) signInButton.setVisibility(View.GONE);
    }
}

The button is in this XML file which is linked to the YourOrdersActivity.java activity.

your_orders_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.mattf.yankeetoyboxv1.YourOrdersActivity">

    <com.google.android.gms.common.SignInButton
        android:id="@+id/sign_in_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

LogCat

12-08 20:31:51.624 12373-12373/com.example.mattf.yankeetoyboxv1 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.mattf.yankeetoyboxv1, PID: 12373
                                                                                java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mattf.yankeetoyboxv1/com.example.mattf.yankeetoyboxv1.YourOrdersActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.common.SignInButton.setSize(int)' on a null object reference
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
                                                                                at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:106)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6494)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
                                                                                Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.common.SignInButton.setSize(int)' on a null object reference
                                                                                at com.example.mattf.yankeetoyboxv1.SignInActivity.promptSignIn(SignInActivity.java:72)
                                                                                at com.example.mattf.yankeetoyboxv1.SignInActivity.isUserSignedIn(SignInActivity.java:57)
                                                                                at com.example.mattf.yankeetoyboxv1.SignInActivity.onCreate(SignInActivity.java:30)
                                                                                at android.app.Activity.performCreate(Activity.java:7000)
                                                                                at android.app.Activity.performCreate(Activity.java:6991)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
                                                                                at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:106)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6494)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

Body:
You are not calling setContentView(R.layout.your_orders_activity) in onCreate method

Your onCreate should be like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_orders_activity);
    isUserSignedIn();
}