问:
Can I force the Android Back button to go two steps back in the Activity stack?
I know that I can override the onKeyDown method, but I want Back to do it's thing, just twice!

答:
|*| Going back one screen or end activity :

```<code>finish();
</code>```

|*| Going back more than one screen :

You can go back to which ever screen you need using intent and use flags to prevent going back to same screen :

```<code>Intent gotoScreenVar = new Intent(goFromScreenCls.this, goToScreenCls.class);

gotoScreenVar.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);

startActivity(gotoScreenVar);
</code>```

Body:
|*| Going back one screen or end activity :

finish();

|*| Going back more than one screen :

You can go back to which ever screen you need using intent and use flags to prevent going back to same screen :

Intent gotoScreenVar = new Intent(goFromScreenCls.this, goToScreenCls.class);

gotoScreenVar.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);

startActivity(gotoScreenVar);


来源: stackexchange

问:
Image animation with mouse y movement
So i make websites as a hobby nothing professional,
but i found a really well made website and i thought it had some things i never saw being used before like 3 images in one div ( which i searched up and found out how to do it ).

But what i could not simply google was how he made each image move seperately on mouse y movement, i do not know if this is doable with just css or would i need to use javascript as well? ( note: i hardly know any javascript ).

Here is the website: https://buy.cosmicpvp.com/
what i was referring to is the top portion of the website.

答:
This is called the Parallax effect.

Looks like the website in question used this jQuery plugin for it.
To answer your question, you most certainly need JavaScript.

ContentLicense: CC BY-SA 3.0

Title: Image animation with mouse y movement


问:
SQLAlchemy ManyToOne Relationship issue
I want to connect two models.

Model #1 is called "Groups". It is connected to several "Teams" via starter_id, main_id, dessert_id. I want to have a field called "teams" which contains a list of all connected teams.

```<code>class Group(db.Model):
    __tablename__ = 'groups'
    id = db.Column(db.Integer, primary_key=True)
    starter_id = db.Column(db.Integer, db.ForeignKey('teams.id'))
    main_id = db.Column(db.Integer, db.ForeignKey('teams.id'))
    dessert_id = db.Column(db.Integer, db.ForeignKey('teams.id'))

    #Relationships
    teams = db.relationship('Team', back_populates="group", foreign_keys= \
    [starter_1_id, starter_2_id, starter_3_id, main_1_id, main_2_id, main_3_id, \
    dessert_1_id, dessert_2_id, dessert_3_id])

class Team(db.Model):
    __tablename__ = 'teams'
    id = db.Column(db.Integer, primary_key=True)
    group_id = db.Column(db.Integer, db.ForeignKey('groups.id'))

    # Relationships
    group = db.relationship("Group", back_populates="teams", foreign_keys=[group_id])
</code>```

I get this error:

```<code>sqlalchemy.exc.AmbiguousForeignKeysError: Could not determine join condition
between parent/child tables on relationship Group.teams - there are multiple
foreign key paths linking the tables.  Specify the 'foreign_keys' argument,
providing a list of those columns which should be counted as containing a
foreign key reference to the parent table.
</code>```

I obviously don't know how to fix that error ;)

答:
The "a team belongs to a group" relationship (Team.group) and its inverse, "a group has many teams" (Group.teams), is given by the foreign key Team.group_id, so you need to write:

```<code>teams = db.relationship('Team', back_populates="group", foreign_keys=lambda: Team.group_id)
</code>```

Title: SQLAlchemy ManyToOne Relationship issue

Body:
I want to connect two models.

Model #1 is called "Groups". It is connected to several "Teams" via starter_id, main_id, dessert_id. I want to have a field called "teams" which contains a list of all connected teams.

class Group(db.Model):
    __tablename__ = 'groups'
    id = db.Column(db.Integer, primary_key=True)
    starter_id = db.Column(db.Integer, db.ForeignKey('teams.id'))
    main_id = db.Column(db.Integer, db.ForeignKey('teams.id'))
    dessert_id = db.Column(db.Integer, db.ForeignKey('teams.id'))

    #Relationships
    teams = db.relationship('Team', back_populates="group", foreign_keys= \
    [starter_1_id, starter_2_id, starter_3_id, main_1_id, main_2_id, main_3_id, \
    dessert_1_id, dessert_2_id, dessert_3_id])

class Team(db.Model):
    __tablename__ = 'teams'
    id = db.Column(db.Integer, primary_key=True)
    group_id = db.Column(db.Integer, db.ForeignKey('groups.id'))

    # Relationships
    group = db.relationship("Group", back_populates="teams", foreign_keys=[group_id])

I get this error:

sqlalchemy.exc.AmbiguousForeignKeysError: Could not determine join condition
between parent/child tables on relationship Group.teams - there are multiple
foreign key paths linking the tables.  Specify the 'foreign_keys' argument,
providing a list of those columns which should be counted as containing a
foreign key reference to the parent table.

I obviously don't know how to fix that error ;)

Body:
The "a team belongs to a group" relationship (Team.group) and its inverse, "a group has many teams" (Group.teams), is given by the foreign key Team.group_id, so you need to write:

teams = db.relationship('Team', back_populates="group", foreign_keys=lambda: Team.group_id)


问:
Oracle SQL with Join and count
I would like to join two tables, A and B, with a count function.

Table A has the followings:

```<code>SQL> select a.book_id, count(a.book_id)
   from
   a
   group by a.book_id ;

BOOK_ID COUNT(A.BOOK_ID)
--------- ----------------
    1                2
    2                2
    3                2
    4                2
    5                2
    6                3
</code>```

and table B has the followings:

```<code> SQL> select b.book_id, count(b.book_id)
from
b
group by b.book_id ;

 BOOK_ID COUNT(B.BOOK_ID)
--------- ----------------
     6                2
</code>```

So I would like to have a query which gives me the following result:

```<code> BOOK_ID COUNT(A.BOOK_ID)    COUNT(B.BOOK_ID)
--------- ----------------   ----------------
    1                2                   0
    2                2                   0
    3                2                   0
    4                2                   0
    5                2                   0
    6                3                   2
</code>```

I tried this :

```<code>  SQL> select b.book_id, count(b.book_id),a.book_id, count(a.book_id)
  from
  b , a
  where
  b.book_id(+) = a.book_id
 group by b.book_id, a.book_id ;
</code>```

but the results were like this :

```<code>   BOOK_ID COUNT(B.BOOK_ID)   BOOK_ID COUNT(A.BOOK_ID)
 --------- ---------------- --------- ----------------
                     0         1                2
                     0         2                2
                     0         3                2
                     0         4                2
                     0         5                2
    6                6         6                6
</code>```

答:
Another way to do it:

```<code>WITH total_list AS (
    SELECT a.Book_id, 'a' AS a_cnt, NULL AS b_cnt FROM a
    UNION ALL
    SELECT b.Book_id, NULL, 'b')
SELECT Book_id, COUNT(a_cnt) AS a_total, COUNT(b_cnt) AS b_total
GROUP BY Book_id
ORDER BY Book_id
</code>```

What this does is it uses a subquery to union together both of your book tables and attaches a flag to it to signify if it belonged to table a or table b. From there, I just selected from the subquery.

Title: Oracle SQL with Join and count

Body:
I would like to join two tables, A and B, with a count function.

Table A has the followings:

SQL> select a.book_id, count(a.book_id)
   from
   a
   group by a.book_id ;

BOOK_ID COUNT(A.BOOK_ID)
--------- ----------------
    1                2
    2                2
    3                2
    4                2
    5                2
    6                3

and table B has the followings:

 SQL> select b.book_id, count(b.book_id)
from
b
group by b.book_id ;

 BOOK_ID COUNT(B.BOOK_ID)
--------- ----------------
     6                2

So I would like to have a query which gives me the following result:

 BOOK_ID COUNT(A.BOOK_ID)    COUNT(B.BOOK_ID)
--------- ----------------   ----------------
    1                2                   0
    2                2                   0
    3                2                   0
    4                2                   0
    5                2                   0
    6                3                   2

I tried this :

  SQL> select b.book_id, count(b.book_id),a.book_id, count(a.book_id)
  from
  b , a
  where
  b.book_id(+) = a.book_id
 group by b.book_id, a.book_id ;

but the results were like this :

   BOOK_ID COUNT(B.BOOK_ID)   BOOK_ID COUNT(A.BOOK_ID)
 --------- ---------------- --------- ----------------
                     0         1                2
                     0         2                2
                     0         3                2
                     0         4                2
                     0         5                2
    6                6         6                6

Body:
Another way to do it:

WITH total_list AS (
    SELECT a.Book_id, 'a' AS a_cnt, NULL AS b_cnt FROM a
    UNION ALL
    SELECT b.Book_id, NULL, 'b')
SELECT Book_id, COUNT(a_cnt) AS a_total, COUNT(b_cnt) AS b_total
GROUP BY Book_id
ORDER BY Book_id

What this does is it uses a subquery to union together both of your book tables and attaches a flag to it to signify if it belonged to table a or table b. From there, I just selected from the subquery.


问:
mongod won't start on CentOS aws instance
I am trying to start a mongod instance using

```<code>sudo service mongod start
</code>```

But it simply fails with output:Starting mongod:                                           [FAILED]

Any suggestions? I am kinda new to this so maybe this is a really stupid question but I tried everything people suggested and nothing worked

答: Ended up making another instance since something was probably wrong with the AWS instance. Any way, this question is irrelevant anymore and probably won't have an answer</p>

Body:
I am trying to start a mongod instance using

sudo service mongod start

But it simply fails with output:Starting mongod:                                           [FAILED]

Any suggestions? I am kinda new to this so maybe this is a really stupid question but I tried everything people suggested and nothing worked


问:
Converting Observable to object B
I am using Angular 2 with RxJs. I get the following compilation exception,

```<code>[ts]
Type 'Observable<Observable<B>>' is not assignable to type
'Observable<B>'.
  Type 'Observable<B>' is not assignable to type 'B'.
    Property 'id' is missing in type 'Observable<B>'.
</code>```

Below is the code in question. I can't really change the method signature for 'getB' since I am overriding it. The base method does not need the 2nd API call to fill children, hence overriding.

```<code>export interface A {
   b: B;
}

export class B {
   cList: C[];
}

export interface C {
   name: string;
   type: string;
}

getB(): Observable<B> {
   let entries = <A[]> []; // get A[] via an server call
   // in this case entries will have only one element in the array
   return this.loadBChilds(entries[0])
     .map(e => e.b);
}

loadBChilds(a: A): Observable<A> {
   // API call to fetch childs
   // set childs to a.b.List
   return this.rest.get('someapi')
     .map(res => {
       res.record.map(r => this.setData(r));
       return a;
     });
}
</code>```

Any idea how to achieve this?

TIA

答:
Managed to solve this. The fix was to collapse the first array being received from the first API via a flatMap and then use that for subsequent API call.</p>

```<code>getB(): Observable<B> {
   return this.rest.get('firstapi')
     .flatMap(res => {
         let entries = res.record
              .map(record => this.getEntry(record));
         return this.loadBChilds(entries[0])
          .map(e => e.b);
     });
}
</code>```

Title: Converting Observable<B> to object B

Body:
I am using Angular 2 with RxJs. I get the following compilation exception,

[ts]
Type 'Observable<Observable>' is not assignable to type
'Observable'.
  Type 'Observable' is not assignable to type 'B'.
    Property 'id' is missing in type 'Observable'.

Below is the code in question. I can't really change the method signature for 'getB' since I am overriding it. The base method does not need the 2nd API call to fill children, hence overriding.

export interface A {
   b: B;
}

export class B {
   cList: C[];
}

export interface C {
   name: string;
   type: string;
}

getB(): Observable {
   let entries =  []; // get A[] via an server call
   // in this case entries will have only one element in the array
   return this.loadBChilds(entries[0])
     .map(e => e.b);
}

loadBChilds(a: A): Observable {
   // API call to fetch childs
   // set childs to a.b.List
   return this.rest.get('someapi')
     .map(res => {
       res.record.map(r => this.setData(r));
       return a;
     });
}

Any idea how to achieve this?

TIA

Body:
Managed to solve this. The fix was to collapse the first array being received from the first API via a flatMap and then use that for subsequent API call.

getB(): Observable<B> {
   return this.rest.get('firstapi')
     .flatMap(res => {
         let entries = res.record
              .map(record => this.getEntry(record));
         return this.loadBChilds(entries[0])
          .map(e => e.b);
     });
}


问:
Loop function until there is no specified needle in the haystack
I'm trying to build a function, that will check if the needle is in haystack, if it is then the function should loop until there is none.

So far I've built a function for random number generation. What that function does is it will create a random string then hash it with sha512. The function then extracts all the numbers from a string and multiplies it by 2.

It leaves me with a long line of numbers, then I'll use mt_rand to specify start and end point for strpos. After that I just return the number that was created randomly.

```<code>function randomNumber($suurus, $max){
mb_internal_encoding("UTF-8");
$possible="aábcdeéfghiíjklmnoóöópqrstuúüűvwxyzAÁBCDEÉFGHIÍJKLMNOÓÖŐPQRSTUÚVWXYZ";
$char = mb_substr($possible,rand(0, mb_strlen($possible) - 1),1);
$str = openssl_digest($char, 'sha512');
$str = preg_replace('/[^1-9.]+/', '', $str);
$str = $str*2;
$strLen = strlen($str)-5;
$strStart =  mt_rand(1, $strLen);
$strEnd = mt_rand(1, $suurus);
$str = substr($str, $strStart, $strEnd);
while($str > $max){
  $str = $str / 2;
}
return round($str);
</code>```

The thing is that this number can't repeat, I need it to be unique at all times for my app.

I actually accomplished what I wanted with if else statements, but that means I have to write a long script of repeated if statements until I get the results I want. I really don't think this is the smartest way to do things.

```<code>if(!isset($voitjad)){
                      $voitjad[$vCounter][] = array(
                        'nimi' => $voitja,
                        'auhind' => $keyCode['v'.$vCount.''],
                        'rn' => $rN,
                        'siin' => 1,
                        'id' => $voitjaID
                      );
                    }else{
                      if(!exist($rN, $voitjad)){
                        $voitjad[$vCounter][] = array(
                          'nimi' => $voitja,
                          'auhind' => $keyCode['v'.$vCount.''],
                          'rn' => $rN,
                          'siin' => 1,
                          'id' => $voitjaID
                        );
                        }else{
                          $rN = randomNumber($atLength, $atCount);
                          $voitja = $attendcheckfb['attending'][$rN]['name'];
                          $voitjaID = $attendcheckfb['attending'][$rN]['id'];
                          if(!exist($rN, $voitjad)){
                            $voitjad[$vCounter][] = array(
                              'nimi' => $voitja,
                              'auhind' => $keyCode['v'.$vCount.''],
                              'rn' => $rN,
                              'siin' => 2,
                              'id' => $voitjaID
                            );
                          }else{ and so on....
</code>```

I also tried with do-while loop, but I couldn't really get it working, I'm not sure what exactly I'm doing wrong here. If you can educate me, shoot me with information.

```<code> $nimed = array_values($nimed);
                      $voitja = $nimed[$rN]['name'];
                      $voitjaID = $nimed[$rN]['id'];
                      $voitjad[$vCounter][] = array(
                        'nimi' => $voitja,
                        'auhind' => $keyCode['v'.$vCount.''],
                        'rn' => $rN,
                        'siin' => 1,
                        'id' => $voitjaID
                      );
                      $oitjaCount++;
                      $rN = randomNumber($nimedLength, $nimedCount);
                    } while(!exist($rN, $voitjad));
</code>```

If there's a way for me to get better randomly generated numbers, then please tell me, I'm open for suggestions. Meanwhile I need help with this needle, haystack thing.

答:
You can either do it with a loop:

```<code>function get_unique_hashcode() {
    global $hash_array;
    do {
        $hashcode = make_random_hashcode();
    } while (in_array($hashcode, $hash_array));
    $hash_array[] = $hashcode;
    return $hashcode;
}
</code>```

Or you can do it with recursion:

```<code>function get_unique_hashcode() {
    global $hash_array;
    $hashcode = make_random_hashcode();
    if (in_array($hashcode, $hash_array)) {
        return get_unique_hashcode();
    } else {
        $hash_array[] = $hashcode;
        return $hashcode;
    }
}
</code>```

This is just a general structure, you may need to adjust it for your detailed needs.

Body:
I'm trying to build a function, that will check if the needle is in haystack, if it is then the function should loop until there is none.

So far I've built a function for random number generation. What that function does is it will create a random string then hash it with sha512. The function then extracts all the numbers from a string and multiplies it by 2.

It leaves me with a long line of numbers, then I'll use mt_rand to specify start and end point for strpos. After that I just return the number that was created randomly.

function randomNumber($suurus, $max){
mb_internal_encoding("UTF-8");
$possible="aábcdeéfghiíjklmnoóöópqrstuúüűvwxyzAÁBCDEÉFGHIÍJKLMNOÓÖŐPQRSTUÚVWXYZ";
$char = mb_substr($possible,rand(0, mb_strlen($possible) - 1),1);
$str = openssl_digest($char, 'sha512');
$str = preg_replace('/[^1-9.]+/', '', $str);
$str = $str*2;
$strLen = strlen($str)-5;
$strStart =  mt_rand(1, $strLen);
$strEnd = mt_rand(1, $suurus);
$str = substr($str, $strStart, $strEnd);
while($str > $max){
  $str = $str / 2;
}
return round($str);

The thing is that this number can't repeat, I need it to be unique at all times for my app.

I actually accomplished what I wanted with if else statements, but that means I have to write a long script of repeated if statements until I get the results I want. I really don't think this is the smartest way to do things.

if(!isset($voitjad)){
                      $voitjad[$vCounter][] = array(
                        'nimi' => $voitja,
                        'auhind' => $keyCode['v'.$vCount.''],
                        'rn' => $rN,
                        'siin' => 1,
                        'id' => $voitjaID
                      );
                    }else{
                      if(!exist($rN, $voitjad)){
                        $voitjad[$vCounter][] = array(
                          'nimi' => $voitja,
                          'auhind' => $keyCode['v'.$vCount.''],
                          'rn' => $rN,
                          'siin' => 1,
                          'id' => $voitjaID
                        );
                        }else{
                          $rN = randomNumber($atLength, $atCount);
                          $voitja = $attendcheckfb['attending'][$rN]['name'];
                          $voitjaID = $attendcheckfb['attending'][$rN]['id'];
                          if(!exist($rN, $voitjad)){
                            $voitjad[$vCounter][] = array(
                              'nimi' => $voitja,
                              'auhind' => $keyCode['v'.$vCount.''],
                              'rn' => $rN,
                              'siin' => 2,
                              'id' => $voitjaID
                            );
                          }else{ and so on....

I also tried with do-while loop, but I couldn't really get it working, I'm not sure what exactly I'm doing wrong here. If you can educate me, shoot me with information.

 $nimed = array_values($nimed);
                      $voitja = $nimed[$rN]['name'];
                      $voitjaID = $nimed[$rN]['id'];
                      $voitjad[$vCounter][] = array(
                        'nimi' => $voitja,
                        'auhind' => $keyCode['v'.$vCount.''],
                        'rn' => $rN,
                        'siin' => 1,
                        'id' => $voitjaID
                      );
                      $oitjaCount++;
                      $rN = randomNumber($nimedLength, $nimedCount);
                    } while(!exist($rN, $voitjad));

If there's a way for me to get better randomly generated numbers, then please tell me, I'm open for suggestions. Meanwhile I need help with this needle, haystack thing.

Body:
You can either do it with a loop:

function get_unique_hashcode() {
    global $hash_array;
    do {
        $hashcode = make_random_hashcode();
    } while (in_array($hashcode, $hash_array));
    $hash_array[] = $hashcode;
    return $hashcode;
}

Or you can do it with recursion:

function get_unique_hashcode() {
    global $hash_array;
    $hashcode = make_random_hashcode();
    if (in_array($hashcode, $hash_array)) {
        return get_unique_hashcode();
    } else {
        $hash_array[] = $hashcode;
        return $hashcode;
    }
}

This is just a general structure, you may need to adjust it for your detailed needs.


问:
C++: difference between 0. and 0.0?
I am well aware of the difference between 0 and 0.0 (int and double).

But is there any difference between 0. and 0.0 ( please note the . )?

Thanks a lot in advance,

Axel

答:
Just having the . as part of the number identifies it as a floating point type.

This:

```<code> cout << (5 / 2) << endl;
 cout << (5. / 2) << endl;
 cout << (5.0 / 2) << endl;
</code>```

Prints this:

```<code> 2
 2.5
 2.5
</code>```

You can see that the first line uses integer division (because both values are integers), whereas 5. and 5.0 both get identified as floating point types, and so they trigger "normal division."

ContentLicense: CC BY-SA 2.5

Title: C++: difference between 0. and 0.0?

Body:
Just having the . as part of the number identifies it as a floating point type.

This:

 cout << (5 / 2) << endl;
 cout << (5. / 2) << endl;
 cout << (5.0 / 2) << endl;

Prints this:

 2
 2.5
 2.5

You can see that the first line uses integer division (because both values are integers), whereas 5. and 5.0 both get identified as floating point types, and so they trigger "normal division."


问:
Indexing documents - do I have to run the refresh index service to maintain the indices?
I am using ElasticSearch in Moqui. DataDocument and Feed documents are set, everything is working. Except for the situation when I restart the server. I need to run the org.moqui.search.SearchServices.index#DataFeedDocuments service. Does this means that the indices are stored in-memory? And I have to restore them by running the service?

I also set up the Real-time Service Push [DTFDTP_RT_PUSH] service for MantleProduct. Does this service only take care of refreshing when individual entities are modified?

答:
Yes, a real-time push DataFeed is just for that purpose, ie to generate a new 'document' (JSON document, though internally nested Map and List objects) based on the DataDocument definitions associated with the DataFeed and call the service on the DataFeed with them. The indexing service then takes those and indexes them in ElasticSearch. Other services can be used for different things such as sending notifications.

The index documents are persisted in ElasticSearch unless you delete its files. If something in the way you are restarting the server deletes the ElasticSearch files then you'll have to use the Data Document Index screen in the System app to tell it to re-index all documents based on database records.


问:
Count number of elements in a text or list using Spark
I know there are different ways to count number of elements in a text or list. But I am trying to understand why this one does not work. I am trying to write an equivalent code to

```<code>A_RDD=sc.parallelize(['a', 1.2, []])

acc = sc.accumulator(0)
acc.value
A_RDD.foreach(lambda _: acc.add(1))
acc.value
</code>```

Where the result is 3.
To do so I defined the following function called my_count(_), but I don't know how to get the result. A_RDD.foreach(my_count)  does not do anything. I didn't receive any error either. What did I do wrong?

```<code>counter = 0   #function that counts elements
def my_count(_):
    global counter
    counter += 1

A_RDD.foreach(my_count)
</code>```

答:
The A_RDD.foreach(my_count) operation doesnt run on your local Python Virtual machine. It runs in your remote executor node. So the drives ships your  my_count method to each of the executor nodes along with variable counter since the method refers the variable. So each executor nodes gets its own definition of counter variable which is updated by the foreach method while the counter variable defined in your driver application is not incremented.

One easy but risky solution would be to collect the RDD on your driver and then compute the count like below. This is risky because the entire RDD content is downloaded to the memory of the driver which may cause MemoryError.

```<code>>>> len(A_RDD.collect())
3
</code>```

Body:
I know there are different ways to count number of elements in a text or list. But I am trying to understand why this one does not work. I am trying to write an equivalent code to

A_RDD=sc.parallelize(['a', 1.2, []])

acc = sc.accumulator(0)
acc.value
A_RDD.foreach(lambda _: acc.add(1))
acc.value

Where the result is 3.
To do so I defined the following function called my_count(_), but I don't know how to get the result. A_RDD.foreach(my_count)  does not do anything. I didn't receive any error either. What did I do wrong?

counter = 0   #function that counts elements
def my_count(_):
    global counter
    counter += 1

A_RDD.foreach(my_count)

Body:
The A_RDD.foreach(my_count) operation doesnt run on your local Python Virtual machine. It runs in your remote executor node. So the drives ships your  my_count method to each of the executor nodes along with variable counter since the method refers the variable. So each executor nodes gets its own definition of counter variable which is updated by the foreach method while the counter variable defined in your driver application is not incremented.

One easy but risky solution would be to collect the RDD on your driver and then compute the count like below. This is risky because the entire RDD content is downloaded to the memory of the driver which may cause MemoryError.

>>> len(A_RDD.collect())
3


问:
Android login activity only shows Google sign-in upon launch
The first time opening a newly installed version of my app shows a custom login/register field and a Google sign-in button beneath the custom option. After logging in, I am brought to the MainActivity without an issue, however, when I try to re-launch the app, it always prompts me with the Google sign-in that I cannot get past without either logging in with a Google account or uninstalling and reinstalling the app.

LoginActivity.java

```<code>public class LoginActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener, OnClickListener {

private static final String TAG = "LoginActivity";
private static final int RC_SIGN_IN = 9001;

    // Id to identity READ_CONTACTS permission request.
private static final int REQUEST_READ_CONTACTS = 0;

// UI references.
private EditText mEmailView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;

private Button mEmailSignInButton;
private Button mEmailRegisterButton;
private SignInButton googleSignInButton;

// Firebase Auth
private FirebaseAuth fbAuth;
private FirebaseUser fbu;

// Firebase DB
private FirebaseDatabase database;
private DatabaseReference myUsers;

// Google
private GoogleApiClient mGoogleApiClient;
private GoogleSignInOptions gso;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    // Set up the login form.
    mEmailView = (EditText) findViewById(R.id.email_edittext);
    mPasswordView = (EditText) findViewById(R.id.password_edittext);

    googleSignInButton= (SignInButton) findViewById(R.id.google_sign_in_button);
    googleSignInButton.setSize(SignInButton.SIZE_STANDARD);
    googleSignInButton.setOnClickListener(this);

    mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
            if (id == R.id.login || id == EditorInfo.IME_NULL) {
                attemptEmailLogin();
                return true;
            }
            return false;
        }
    });

    mEmailRegisterButton = (Button) findViewById(R.id.register_button);
    mEmailRegisterButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            attemptEmailRegister();
        }
    });

    mEmailSignInButton = (Button) findViewById(R.id.sign_in_button);
    mEmailSignInButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            attemptEmailLogin();
        }
    });

    mLoginFormView = findViewById(R.id.login_form);
    mProgressView = findViewById(R.id.login_progress);

    // Google sign in
    gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id))
            .requestEmail()
            .build();
    buildGoogleApiClient();

    // Initialize FirebaseAuth instance
    fbAuth = FirebaseAuth.getInstance();
    fbu = fbAuth.getCurrentUser();
    if (fbu != null) {
        Intent signInIntent = Auth
                .GoogleSignInApi
                .getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent, RC_SIGN_IN);
        finish();
    } else {
        Log.d(TAG, "No user is logged in");
    }

    // FireBase DB
    database = FirebaseDatabase.getInstance();
    myUsers = database.getReference("users");
}

@Override
protected void onStart() {
    super.onStart();
    fbu = fbAuth.getCurrentUser();
    if (fbu != null) {
        Intent signInIntent = Auth
                .GoogleSignInApi
                .getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent, RC_SIGN_IN);
        finish();
    } else {
        Log.d(TAG, "No user is logged in");
    }
}

protected synchronized void buildGoogleApiClient() {
    Log.i(TAG, "Building GoogleApiClient");
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity (AppCompatActivity) */, this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();
    mGoogleApiClient.connect();
}

private void attemptEmailRegister() {

    // Reset errors.
    mEmailView.setError(null);
    mPasswordView.setError(null);

    // Store values at the time of the login attempt.
    String email = mEmailView.getText().toString();
    String password = mPasswordView.getText().toString();

    boolean cancel = false;
    View focusView = null;

    // Check for a valid password, if the user entered one.
    if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
        mPasswordView.setError(getString(R.string.error_invalid_password));
        focusView = mPasswordView;
        cancel = true;
    }

    // Check for a valid email address.
    if (TextUtils.isEmpty(email)) {
        mEmailView.setError(getString(R.string.error_field_required));
        focusView = mEmailView;
        cancel = true;
    } else if (!isEmailValid(email)) {
        mEmailView.setError(getString(R.string.error_invalid_email));
        focusView = mEmailView;
        cancel = true;
    }

    if (cancel) {
        // There was an error; don't attempt register and focus the first
        // form field with an error.
        focusView.requestFocus();
    } else {
        // perform the user register attempt.
        showProgress(true);
        fbAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            // Register success
                            Log.d(TAG, "createUserWithEmail:success");
                            FirebaseUser user = fbAuth.getCurrentUser();
                            onAuthSuccess(user);
                        } else {
                            // If register fails, display a message to the user.
                            Log.w(TAG, "createUserWithEmail:failure", task.getException());
                            Toast.makeText(LoginActivity.this, "Registration authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                            Intent startMainActivity = new Intent(LoginActivity.this, LoginActivity.class);
                            startActivity(startMainActivity);
                            finish();
                        }
                    }
                });
    }

}

private void attemptEmailLogin(){

    // Reset errors.
    mEmailView.setError(null);
    mPasswordView.setError(null);

    // Store values at the time of the login attempt.
    String email = mEmailView.getText().toString();
    String password = mPasswordView.getText().toString();

    boolean cancel = false;
    View focusView = null;

    // Check for a valid password, if the user entered one.
    if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
        mPasswordView.setError(getString(R.string.error_invalid_password));
        focusView = mPasswordView;
        cancel = true;
    }

    // Check for a valid email address.
    if (TextUtils.isEmpty(email)) {
        mEmailView.setError(getString(R.string.error_field_required));
        focusView = mEmailView;
        cancel = true;
    } else if (!isEmailValid(email)) {
        mEmailView.setError(getString(R.string.error_invalid_email));
        focusView = mEmailView;
        cancel = true;
    }

    if (cancel) {
        // There was an error; don't attempt register and focus the first
        // form field with an error.
        focusView.requestFocus();
    } else {
        // perform the user register attempt.
        showProgress(true);
        fbAuth.signInWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            // Sign in success
                            Log.d(TAG, "signInWithEmail:success");
                            FirebaseUser user = fbAuth.getCurrentUser();
                            Intent startMainActivity = new Intent(LoginActivity.this, MainActivity.class);
                            startActivity(startMainActivity);
                        } else {
                            // If sign in fails, display a message to the user.
                            Log.w(TAG, "signInWithEmail:failure", task.getException());
                            Toast.makeText(LoginActivity.this, "Login authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                            Intent startMainActivity = new Intent(LoginActivity.this, LoginActivity.class);
                            startActivity(startMainActivity);
                        }

                    }
                });
    }

}

private void onAuthSuccess(FirebaseUser user) {
    String username = usernameFromEmail(user.getEmail());
    String[] names = firstAndLastNameFromDisplayName(user.getDisplayName());

    // Write new user
    writeNewUser(user.getUid(), names, username, user.getEmail());

    // Go to MainActivity
    Intent startMainActivity = new Intent(LoginActivity.this, MainActivity.class);
    startActivity(startMainActivity);
    finish();
}
private String usernameFromEmail(String email) {
    if (email.contains("@")) {
        return email.split("@")[0];
    } else {
        return email;
    }
}
private String[] firstAndLastNameFromDisplayName(String fullName) {
    if (fullName != null) {
        if (fullName.contains(" ")) {
            return new String[]{fullName.split(" ")[0], fullName.split(" ")[1]};
        } else {
            return new String[]{fullName, "emptyLastName"};
        }
    } else {
        return new String[]{"defaultfirst","defaultlast"};
    }
}
private void writeNewUser(String userId, String[] names, String username, String email) {
    User user = new User(username,names[0],names[1], email);
    myUsers.child("users").child(userId).setValue(user);
}

private boolean isEmailValid(String email) {
    return email.contains("@");
}

private boolean isPasswordValid(String password) {
    return (password.length() > 4) && !password.contains("\\");
}

/**
 * Shows the progress UI and hides the login form.
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
    // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
    // for very easy animations. If available, use these APIs to fade-in
    // the progress spinner.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
        int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

        mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        mLoginFormView.animate().setDuration(shortAnimTime).alpha(
                show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            }
        });

        mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
        mProgressView.animate().setDuration(shortAnimTime).alpha(
                show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            }
        });
    } else {
        // The ViewPropertyAnimator APIs are not available, so simply show
        // and hide the relevant UI components.
        mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
        mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
    }
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    Log.e(TAG, "onConnectionFailed called");
}

@Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.google_sign_in_button:
            Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
            startActivityForResult(signInIntent, RC_SIGN_IN);
            break;
    }
}

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

    // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
    if (requestCode == RC_SIGN_IN) {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        handleSignInResult(result);
    }
}

private void handleSignInResult(GoogleSignInResult result) {
    Log.d(TAG, "handleSignInResult:" + result.isSuccess());
    if (result.isSuccess()) {
        // Signed in successfully, show authenticated UI.
        GoogleSignInAccount account = result.getSignInAccount();
        firebaseAuthWithGoogle(account);
        Log.d(TAG, "google handleSignInResult: success!");
        Intent startMainActivity = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(startMainActivity);
    } else {
        // Signed out, show unauthenticated
        Toast.makeText(LoginActivity.this, "HandleSignInResult malfunction. Try again.",
                Toast.LENGTH_SHORT).show();
        Intent startMainActivity = new Intent(LoginActivity.this, LoginActivity.class);
        startActivity(startMainActivity);
    }
}

private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());

    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
    fbAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        // Sign in success, update UI with the signed-in user's information
                        Log.d(TAG, "signInWithCredential:success");
                        FirebaseUser user = fbAuth.getCurrentUser();
                    } else {
                        // If sign in fails, display a message to the user.
                        Log.w(TAG, "signInWithCredential:failure", task.getException());
                        Toast.makeText(LoginActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                        Intent startMainActivity = new Intent(LoginActivity.this, LoginActivity.class);
                        startActivity(startMainActivity);
                    }

                }
            });
}
}
</code>```

答:
In the onCreate and onStart you've fbAuth.getCurrentUser(). It is null when the user hasn't logged in otherwise it returns user details.

Your logic is in reverse asking for a sign in if the user has already logged in.

```<code>if (fbu != null) {
    Intent signInIntent = Auth
            .GoogleSignInApi
            .getSignInIntent(mGoogleApiClient);
    startActivityForResult(signInIntent, RC_SIGN_IN);
    finish();
} else {
    Log.d(TAG, "No user is logged in");
}
</code>```

This should be in reverse

```<code>if (fbu == null) {
    Log.d(TAG, "No user is logged in");
    // Initiate Google sign in
    Intent signInIntent = Auth
            .GoogleSignInApi
            .getSignInIntent(mGoogleApiClient);
    startActivityForResult(signInIntent, RC_SIGN_IN);
} else {
    Log.d(TAG, "User is already logged in");
    // Open Main Activity
    Intent startMainActivity = new Intent(LoginActivity.this, MainActivity.class);
    startActivity(startMainActivity);
    // Close the current activity
    finish();
}
</code>```

Body:
The first time opening a newly installed version of my app shows a custom login/register field and a Google sign-in button beneath the custom option. After logging in, I am brought to the MainActivity without an issue, however, when I try to re-launch the app, it always prompts me with the Google sign-in that I cannot get past without either logging in with a Google account or uninstalling and reinstalling the app.

LoginActivity.java

public class LoginActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener, OnClickListener {

private static final String TAG = "LoginActivity";
private static final int RC_SIGN_IN = 9001;

    // Id to identity READ_CONTACTS permission request.
private static final int REQUEST_READ_CONTACTS = 0;

// UI references.
private EditText mEmailView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;

private Button mEmailSignInButton;
private Button mEmailRegisterButton;
private SignInButton googleSignInButton;

// Firebase Auth
private FirebaseAuth fbAuth;
private FirebaseUser fbu;

// Firebase DB
private FirebaseDatabase database;
private DatabaseReference myUsers;

// Google
private GoogleApiClient mGoogleApiClient;
private GoogleSignInOptions gso;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    // Set up the login form.
    mEmailView = (EditText) findViewById(R.id.email_edittext);
    mPasswordView = (EditText) findViewById(R.id.password_edittext);

    googleSignInButton= (SignInButton) findViewById(R.id.google_sign_in_button);
    googleSignInButton.setSize(SignInButton.SIZE_STANDARD);
    googleSignInButton.setOnClickListener(this);

    mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
            if (id == R.id.login || id == EditorInfo.IME_NULL) {
                attemptEmailLogin();
                return true;
            }
            return false;
        }
    });

    mEmailRegisterButton = (Button) findViewById(R.id.register_button);
    mEmailRegisterButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            attemptEmailRegister();
        }
    });

    mEmailSignInButton = (Button) findViewById(R.id.sign_in_button);
    mEmailSignInButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            attemptEmailLogin();
        }
    });

    mLoginFormView = findViewById(R.id.login_form);
    mProgressView = findViewById(R.id.login_progress);

    // Google sign in
    gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id))
            .requestEmail()
            .build();
    buildGoogleApiClient();

    // Initialize FirebaseAuth instance
    fbAuth = FirebaseAuth.getInstance();
    fbu = fbAuth.getCurrentUser();
    if (fbu != null) {
        Intent signInIntent = Auth
                .GoogleSignInApi
                .getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent, RC_SIGN_IN);
        finish();
    } else {
        Log.d(TAG, "No user is logged in");
    }

    // FireBase DB
    database = FirebaseDatabase.getInstance();
    myUsers = database.getReference("users");
}

@Override
protected void onStart() {
    super.onStart();
    fbu = fbAuth.getCurrentUser();
    if (fbu != null) {
        Intent signInIntent = Auth
                .GoogleSignInApi
                .getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent, RC_SIGN_IN);
        finish();
    } else {
        Log.d(TAG, "No user is logged in");
    }
}

protected synchronized void buildGoogleApiClient() {
    Log.i(TAG, "Building GoogleApiClient");
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity (AppCompatActivity) */, this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();
    mGoogleApiClient.connect();
}

private void attemptEmailRegister() {

    // Reset errors.
    mEmailView.setError(null);
    mPasswordView.setError(null);

    // Store values at the time of the login attempt.
    String email = mEmailView.getText().toString();
    String password = mPasswordView.getText().toString();

    boolean cancel = false;
    View focusView = null;

    // Check for a valid password, if the user entered one.
    if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
        mPasswordView.setError(getString(R.string.error_invalid_password));
        focusView = mPasswordView;
        cancel = true;
    }

    // Check for a valid email address.
    if (TextUtils.isEmpty(email)) {
        mEmailView.setError(getString(R.string.error_field_required));
        focusView = mEmailView;
        cancel = true;
    } else if (!isEmailValid(email)) {
        mEmailView.setError(getString(R.string.error_invalid_email));
        focusView = mEmailView;
        cancel = true;
    }

    if (cancel) {
        // There was an error; don't attempt register and focus the first
        // form field with an error.
        focusView.requestFocus();
    } else {
        // perform the user register attempt.
        showProgress(true);
        fbAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            // Register success
                            Log.d(TAG, "createUserWithEmail:success");
                            FirebaseUser user = fbAuth.getCurrentUser();
                            onAuthSuccess(user);
                        } else {
                            // If register fails, display a message to the user.
                            Log.w(TAG, "createUserWithEmail:failure", task.getException());
                            Toast.makeText(LoginActivity.this, "Registration authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                            Intent startMainActivity = new Intent(LoginActivity.this, LoginActivity.class);
                            startActivity(startMainActivity);
                            finish();
                        }
                    }
                });
    }

}

private void attemptEmailLogin(){

    // Reset errors.
    mEmailView.setError(null);
    mPasswordView.setError(null);

    // Store values at the time of the login attempt.
    String email = mEmailView.getText().toString();
    String password = mPasswordView.getText().toString();

    boolean cancel = false;
    View focusView = null;

    // Check for a valid password, if the user entered one.
    if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
        mPasswordView.setError(getString(R.string.error_invalid_password));
        focusView = mPasswordView;
        cancel = true;
    }

    // Check for a valid email address.
    if (TextUtils.isEmpty(email)) {
        mEmailView.setError(getString(R.string.error_field_required));
        focusView = mEmailView;
        cancel = true;
    } else if (!isEmailValid(email)) {
        mEmailView.setError(getString(R.string.error_invalid_email));
        focusView = mEmailView;
        cancel = true;
    }

    if (cancel) {
        // There was an error; don't attempt register and focus the first
        // form field with an error.
        focusView.requestFocus();
    } else {
        // perform the user register attempt.
        showProgress(true);
        fbAuth.signInWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            // Sign in success
                            Log.d(TAG, "signInWithEmail:success");
                            FirebaseUser user = fbAuth.getCurrentUser();
                            Intent startMainActivity = new Intent(LoginActivity.this, MainActivity.class);
                            startActivity(startMainActivity);
                        } else {
                            // If sign in fails, display a message to the user.
                            Log.w(TAG, "signInWithEmail:failure", task.getException());
                            Toast.makeText(LoginActivity.this, "Login authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                            Intent startMainActivity = new Intent(LoginActivity.this, LoginActivity.class);
                            startActivity(startMainActivity);
                        }

                    }
                });
    }

}

private void onAuthSuccess(FirebaseUser user) {
    String username = usernameFromEmail(user.getEmail());
    String[] names = firstAndLastNameFromDisplayName(user.getDisplayName());

    // Write new user
    writeNewUser(user.getUid(), names, username, user.getEmail());

    // Go to MainActivity
    Intent startMainActivity = new Intent(LoginActivity.this, MainActivity.class);
    startActivity(startMainActivity);
    finish();
}
private String usernameFromEmail(String email) {
    if (email.contains("@")) {
        return email.split("@")[0];
    } else {
        return email;
    }
}
private String[] firstAndLastNameFromDisplayName(String fullName) {
    if (fullName != null) {
        if (fullName.contains(" ")) {
            return new String[]{fullName.split(" ")[0], fullName.split(" ")[1]};
        } else {
            return new String[]{fullName, "emptyLastName"};
        }
    } else {
        return new String[]{"defaultfirst","defaultlast"};
    }
}
private void writeNewUser(String userId, String[] names, String username, String email) {
    User user = new User(username,names[0],names[1], email);
    myUsers.child("users").child(userId).setValue(user);
}

private boolean isEmailValid(String email) {
    return email.contains("@");
}

private boolean isPasswordValid(String password) {
    return (password.length() > 4) && !password.contains("\\");
}

/**
 * Shows the progress UI and hides the login form.
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
    // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
    // for very easy animations. If available, use these APIs to fade-in
    // the progress spinner.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
        int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

        mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        mLoginFormView.animate().setDuration(shortAnimTime).alpha(
                show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            }
        });

        mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
        mProgressView.animate().setDuration(shortAnimTime).alpha(
                show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            }
        });
    } else {
        // The ViewPropertyAnimator APIs are not available, so simply show
        // and hide the relevant UI components.
        mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
        mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
    }
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    Log.e(TAG, "onConnectionFailed called");
}

@Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.google_sign_in_button:
            Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
            startActivityForResult(signInIntent, RC_SIGN_IN);
            break;
    }
}

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

    // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
    if (requestCode == RC_SIGN_IN) {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        handleSignInResult(result);
    }
}

private void handleSignInResult(GoogleSignInResult result) {
    Log.d(TAG, "handleSignInResult:" + result.isSuccess());
    if (result.isSuccess()) {
        // Signed in successfully, show authenticated UI.
        GoogleSignInAccount account = result.getSignInAccount();
        firebaseAuthWithGoogle(account);
        Log.d(TAG, "google handleSignInResult: success!");
        Intent startMainActivity = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(startMainActivity);
    } else {
        // Signed out, show unauthenticated
        Toast.makeText(LoginActivity.this, "HandleSignInResult malfunction. Try again.",
                Toast.LENGTH_SHORT).show();
        Intent startMainActivity = new Intent(LoginActivity.this, LoginActivity.class);
        startActivity(startMainActivity);
    }
}

private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());

    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
    fbAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        // Sign in success, update UI with the signed-in user's information
                        Log.d(TAG, "signInWithCredential:success");
                        FirebaseUser user = fbAuth.getCurrentUser();
                    } else {
                        // If sign in fails, display a message to the user.
                        Log.w(TAG, "signInWithCredential:failure", task.getException());
                        Toast.makeText(LoginActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                        Intent startMainActivity = new Intent(LoginActivity.this, LoginActivity.class);
                        startActivity(startMainActivity);
                    }

                }
            });
}
}

Body:
In the onCreate and onStart you've fbAuth.getCurrentUser(). It is null when the user hasn't logged in otherwise it returns user details.

Your logic is in reverse asking for a sign in if the user has already logged in.

if (fbu != null) {
    Intent signInIntent = Auth
            .GoogleSignInApi
            .getSignInIntent(mGoogleApiClient);
    startActivityForResult(signInIntent, RC_SIGN_IN);
    finish();
} else {
    Log.d(TAG, "No user is logged in");
}

This should be in reverse

if (fbu == null) {
    Log.d(TAG, "No user is logged in");
    // Initiate Google sign in
    Intent signInIntent = Auth
            .GoogleSignInApi
            .getSignInIntent(mGoogleApiClient);
    startActivityForResult(signInIntent, RC_SIGN_IN);
} else {
    Log.d(TAG, "User is already logged in");
    // Open Main Activity
    Intent startMainActivity = new Intent(LoginActivity.this, MainActivity.class);
    startActivity(startMainActivity);
    // Close the current activity
    finish();
}


问:
Send message through Ring (Circular) Buffer between Threads (in C)
I need to send a message from Main thread to my Created Thread using WinAPI and Ring Buffer.

I defined structures and wrote functions for my Ring buffer.
Ring Buffer - it contains head, tail, size and pointer to the structure Descriptor which has length of Data and data itself. As I need to send 2 parameters to CreateThread function, I created the third structure ThreadParams to keep 2 parameters.

I want to leave this structures how they are now, not changeable.

```<code>typedef struct _Descriptor
{
    uint32_t dataLen;
    void * data;
} Descriptor;

typedef struct _ringBuffer
{
    Descriptor *bufferData;
    int head;
    int tail;
    int size;
} ringBuffer;

typedef struct _ThreadParams
{
    void * ptr1;
    void * ptr2;
} ThreadParams;
</code>```

There are my realisations of Ring Buffer functions:

```<code>void bufferFree(ringBuffer *buffer)
{
    free(buffer->bufferData);
}

void ringInitialization(ringBuffer *buffer, int size)
{
    buffer->size = size;
    buffer->head = 0;
    buffer->tail = 0;
    buffer->bufferData = (Descriptor*)malloc(sizeof(Descriptor) * size);
}

int pushBack(ringBuffer *buffer, void * data) // fill buffer
{
    buffer->bufferData[buffer->tail++] = *(Descriptor*)data;
    if (buffer->tail == buffer->size)
    {
        buffer->tail = 0;
    }
    return 0;
}

int popFront(ringBuffer *buffer)
{
    if (buffer->head != buffer->tail)
    {
        buffer->head++;
        if (buffer->head == buffer->size)
        {
            buffer->head = 0;
        }
    }
    return 0;
}
</code>```

My main: I checked that I can send a few bytes (the memory is shared between threads), now I need to send a big message (> BUFF_SIZE) though Ring Buffer what I'm trying to do in while() cycle. Here is the question: how should I do it? My thing doesn't work because I catch an exception in printf() function (memory acces violation).

```<code>#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#include <strsafe.h>
#include <stdint.h>

#define RING_SIZE 256
#define BUFFER_SIZE 1024

DWORD WINAPI HandleSendThread(LPVOID params);

uint8_t * getPointer(uint8_t *buffer, uint32_t index)
{
    uint8_t * ptr = ((uint8_t*)buffer) + index * BUFFER_SIZE;
    return ptr;
}

int main(int argc, char * argv[])
{
    //Descriptor * ringData = (Descriptor *)malloc(sizeof(Descriptor) * RING_SIZE);

    ringBuffer ring;
    ringInitialization(&ring, RING_SIZE);
    void * packetBuffer = malloc(BUFFER_SIZE * RING_SIZE);
    uint8_t * currentBuffer = getPointer(packetBuffer, 0);
    uint8_t * str = "Mr. and Mrs. Dursley, of number four, Privet Drive, were proud to say that they were perfectly normal, thank you very much. They were the last people you'd expect to be involved in anything strange or mysterious, because they just didn't hold with such nonsense. Mr.Dursley was the director of a firm called Grunnings, which made drills.He was a big, beefy man with hardly any neck, although he did have a very large mustache.Mrs.Dursley was thin and blonde and had nearly twice the usual amount of neck, which came in very useful as she spent so much of her time craning over garden fences, spying on the neighbors.The Dursleys had a small son called Dudley and in their opinion there was no finer boy anywhere.";

    strcpy(currentBuffer, str);
    ring.bufferData[0].data = currentBuffer;
    ring.bufferData[0].dataLen = strlen(str);

    int currentSize = 0;
    int ringSize = RING_SIZE;
    while(ring.bufferData[0].data != '\0')
    {
        for (int i = currentSize; i < ringSize; i + RING_SIZE)
        {
            pushBack(&ring, currentBuffer);
            printf("h = %s, tail = %s, dataBuffer = %s\n", (char*)ring.head, (char*)ring.tail, (char*)ring.bufferData[i].data);
        }
        currentSize = ringSize;
        ringSize = 2 * ringSize;
        popFront(&ring);
    }

    ThreadParams params = { &ring, packetBuffer };
    HANDLE MessageThread = 0;
    MessageThread = CreateThread(NULL, 0, HandleSendThread, &params, 0, NULL);
    if (MessageThread == NULL)
    {
        ExitProcess(MessageThread);
    }

    WaitForSingleObject(MessageThread, INFINITE);
    CloseHandle(MessageThread);
    system("pause");
    return 0;
}
</code>```

And my CreateThread function:

```<code>DWORD WINAPI HandleSendThread(LPVOID params)
{
    ringBuffer * ring = ((ThreadParams*)params)->ptr1;
    void * buffer = ((ThreadParams*)params)->ptr2;
    //ring->bufferData[0].dataLen = sizeof(buffer) + sizeof(ring->bufferData[0])*1024;

    printf("Shared memory check: ringBuffer data = \"%s\", \nlength = %d\n", (char*)ring->bufferData[0].data, ring->bufferData[0].dataLen);
    return 0;
}
</code>```

答:
Your most immediate problem is the inconsistency between the code in pushBack(), which expects data to point to a Descriptor, and the  code in your main function, which passes in a pointer to a string instead.

If you had declared pushBack() properly, i.e.,

```<code>void pushBack(ringBuffer *buffer, Descriptor * data)
{
    buffer->bufferData[buffer->tail++] = *data;
    if (buffer->tail == buffer->size)
    {
        buffer->tail = 0;
    }
}
</code>```

Then the compiler would have been able to warn you about the discrepancy.

You also have an infinite loop here:

```<code>for (int i = currentSize; i < ringSize; i + RING_SIZE)
</code>```

You probably meant

```<code>for (int i = currentSize; i < ringSize; i += RING_SIZE)
</code>```

... although it still doesn't look to me like it will do anything sensible.  Nor do I understand the purpose of the outer loop, which compares a pointer to a character.

Body:
I need to send a message from Main thread to my Created Thread using WinAPI and Ring Buffer.

I defined structures and wrote functions for my Ring buffer.
Ring Buffer - it contains head, tail, size and pointer to the structure Descriptor which has length of Data and data itself. As I need to send 2 parameters to CreateThread function, I created the third structure ThreadParams to keep 2 parameters.

I want to leave this structures how they are now, not changeable.

typedef struct _Descriptor
{
    uint32_t dataLen;
    void * data;
} Descriptor;

typedef struct _ringBuffer
{
    Descriptor *bufferData;
    int head;
    int tail;
    int size;
} ringBuffer;

typedef struct _ThreadParams
{
    void * ptr1;
    void * ptr2;
} ThreadParams;

There are my realisations of Ring Buffer functions:

void bufferFree(ringBuffer *buffer)
{
    free(buffer->bufferData);
}

void ringInitialization(ringBuffer *buffer, int size)
{
    buffer->size = size;
    buffer->head = 0;
    buffer->tail = 0;
    buffer->bufferData = (Descriptor*)malloc(sizeof(Descriptor) * size);
}

int pushBack(ringBuffer *buffer, void * data) // fill buffer
{
    buffer->bufferData[buffer->tail++] = *(Descriptor*)data;
    if (buffer->tail == buffer->size)
    {
        buffer->tail = 0;
    }
    return 0;
}

int popFront(ringBuffer *buffer)
{
    if (buffer->head != buffer->tail)
    {
        buffer->head++;
        if (buffer->head == buffer->size)
        {
            buffer->head = 0;
        }
    }
    return 0;
}

My main: I checked that I can send a few bytes (the memory is shared between threads), now I need to send a big message (> BUFF_SIZE) though Ring Buffer what I'm trying to do in while() cycle. Here is the question: how should I do it? My thing doesn't work because I catch an exception in printf() function (memory acces violation).

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#include <strsafe.h>
#include <stdint.h>

#define RING_SIZE 256
#define BUFFER_SIZE 1024

DWORD WINAPI HandleSendThread(LPVOID params);

uint8_t * getPointer(uint8_t *buffer, uint32_t index)
{
    uint8_t * ptr = ((uint8_t*)buffer) + index * BUFFER_SIZE;
    return ptr;
}

int main(int argc, char * argv[])
{
    //Descriptor * ringData = (Descriptor *)malloc(sizeof(Descriptor) * RING_SIZE);

    ringBuffer ring;
    ringInitialization(&ring, RING_SIZE);
    void * packetBuffer = malloc(BUFFER_SIZE * RING_SIZE);
    uint8_t * currentBuffer = getPointer(packetBuffer, 0);
    uint8_t * str = "Mr. and Mrs. Dursley, of number four, Privet Drive, were proud to say that they were perfectly normal, thank you very much. They were the last people you'd expect to be involved in anything strange or mysterious, because they just didn't hold with such nonsense. Mr.Dursley was the director of a firm called Grunnings, which made drills.He was a big, beefy man with hardly any neck, although he did have a very large mustache.Mrs.Dursley was thin and blonde and had nearly twice the usual amount of neck, which came in very useful as she spent so much of her time craning over garden fences, spying on the neighbors.The Dursleys had a small son called Dudley and in their opinion there was no finer boy anywhere.";

    strcpy(currentBuffer, str);
    ring.bufferData[0].data = currentBuffer;
    ring.bufferData[0].dataLen = strlen(str);

    int currentSize = 0;
    int ringSize = RING_SIZE;
    while(ring.bufferData[0].data != '\0')
    {
        for (int i = currentSize; i < ringSize; i + RING_SIZE)
        {
            pushBack(&ring, currentBuffer);
            printf("h = %s, tail = %s, dataBuffer = %s\n", (char*)ring.head, (char*)ring.tail, (char*)ring.bufferData[i].data);
        }
        currentSize = ringSize;
        ringSize = 2 * ringSize;
        popFront(&ring);
    }

    ThreadParams params = { &ring, packetBuffer };
    HANDLE MessageThread = 0;
    MessageThread = CreateThread(NULL, 0, HandleSendThread, &params, 0, NULL);
    if (MessageThread == NULL)
    {
        ExitProcess(MessageThread);
    }

    WaitForSingleObject(MessageThread, INFINITE);
    CloseHandle(MessageThread);
    system("pause");
    return 0;
}

And my CreateThread function:

DWORD WINAPI HandleSendThread(LPVOID params)
{
    ringBuffer * ring = ((ThreadParams*)params)->ptr1;
    void * buffer = ((ThreadParams*)params)->ptr2;
    //ring->bufferData[0].dataLen = sizeof(buffer) + sizeof(ring->bufferData[0])*1024;

    printf("Shared memory check: ringBuffer data = \"%s\", \nlength = %d\n", (char*)ring->bufferData[0].data, ring->bufferData[0].dataLen);
    return 0;
}

Body:
Your most immediate problem is the inconsistency between the code in pushBack(), which expects data to point to a Descriptor, and the  code in your main function, which passes in a pointer to a string instead.

If you had declared pushBack() properly, i.e.,

void pushBack(ringBuffer *buffer, Descriptor * data)
{
    buffer->bufferData[buffer->tail++] = *data;
    if (buffer->tail == buffer->size)
    {
        buffer->tail = 0;
    }
}

Then the compiler would have been able to warn you about the discrepancy.

You also have an infinite loop here:

for (int i = currentSize; i < ringSize; i + RING_SIZE)

You probably meant

for (int i = currentSize; i < ringSize; i += RING_SIZE)

... although it still doesn't look to me like it will do anything sensible.  Nor do I understand the purpose of the outer loop, which compares a pointer to a character.


问:
Python: how to add curves in an image
I have an image as follows:

The image is generated in Python. I want to further plot a curve on top of the image, which encloses the white region. I have already got the pixel indices for the region border. I know in Matlab, e.g., it can be simply done by :

```<code>hold on
plot(x,y,'r-') %x and y are the indices of boundary pixels.
</code>```

The resultant image should be like this:

How can I do that contour on top of the image in Python, not by cv2.drawContours? Anyone can help me with the problem?

答:
You can use the Pillow library for it. Without going into the whole solution, there's a good example in their tutorial on how to read an image an do some postscript drawing on top of it: https://pillow.readthedocs.io/en/4.1.x/handbook/tutorial.html#drawing-postscript

You pretty much only need to change the rectangle to a circle instead.

The cut down example is:

```<code>from PIL import Image
from PIL import PSDraw

im = Image.open("lena.ppm")
box = (1*72, 2*72, 7*72, 10*72) # in points

ps = PSDraw.PSDraw() # default is sys.stdout
ps.begin_document(title)

# draw the image (75 dpi)
ps.image(box, im, 75)
ps.rectangle(box)

ps.end_document()
</code>```

PS. I'm assuming that by "I have an image as follows:" you mean, you have an image file and want to process that, not that you're generating that graph in python already. If you're using something like matplotlib to generate it in the first place, you can add it there instead.

If you're already doing it in matplotlib, then the question is likely a duplicate of matplotlib: add circle to plot

Title: Python: how to add curves in an image

Body:
I have an image as follows:

The image is generated in Python. I want to further plot a curve on top of the image, which encloses the white region. I have already got the pixel indices for the region border. I know in Matlab, e.g., it can be simply done by :

hold on
plot(x,y,'r-') %x and y are the indices of boundary pixels.

The resultant image should be like this:

How can I do that contour on top of the image in Python, not by cv2.drawContours? Anyone can help me with the problem?

Body:
You can use the Pillow library for it. Without going into the whole solution, there's a good example in their tutorial on how to read an image an do some postscript drawing on top of it: https://pillow.readthedocs.io/en/4.1.x/handbook/tutorial.html#drawing-postscript

You pretty much only need to change the rectangle to a circle instead.

The cut down example is:

from PIL import Image
from PIL import PSDraw

im = Image.open("lena.ppm")
box = (1*72, 2*72, 7*72, 10*72) # in points

ps = PSDraw.PSDraw() # default is sys.stdout
ps.begin_document(title)

# draw the image (75 dpi)
ps.image(box, im, 75)
ps.rectangle(box)

ps.end_document()

PS. I'm assuming that by "I have an image as follows:" you mean, you have an image file and want to process that, not that you're generating that graph in python already. If you're using something like matplotlib to generate it in the first place, you can add it there instead.

If you're already doing it in matplotlib, then the question is likely a duplicate of matplotlib: add circle to plot


问:
Too many "&&"s in condition coding. The better codes?
The following code works as intended but seems inelegant.

```<code>.Where(x =>     x.Attributes().Contains(x.Attribute("Quick"))
            && !x.Attributes().Contains(x.Attribute("Brown"))
            && !x.Attributes().Contains(x.Attribute("Fox"))
            && !x.Attributes().Contains(x.Attribute("Jumps"))
            && !x.Attributes().Contains(x.Attribute("Lazy"))
            && !x.Attributes().Contains(x.Attribute("Dogs")))
</code>```

As you can see, I am checking whether

the XElement has exactly one attribute

this attribute has the specified name

[Edit] My intention is..I want to make sure that the element has only one attribute. I mean only "Quick" attribute in this case. I know the count style though, the count does not distinguish its name.[/Edit]

[Edit2]I want elements if only if it has sigle attribute, nothing else.[/Edit2]

[Edit3]"x" is an element for instance..

```<code><mySeg Quick="1" Brown="Two" Fox="None" Jumps="2016_En" Lazy="100" Dogs="Source">  //  I do not want this XElement
</code>```

or

```<code><mySeg Quick="2" Brown="Ten">  //  Nah.
</code>```

or

```<code><mySeg Quick="3">  // yes, this is one I'm looking for.
</code>```

[Edit3]

[Edit4]
I guess, I have to use this one. Actually, it is the one I used before this post. I was thingking one shot.

```<code>x.Attributes().Contains(x.Attribute("Quick")) && x.Attributes().Count() == 1 //thanks Ryan
</code>```

[Edit4]

答:
If you want to ensure that it contains one and only one of a list of attributes, and you can create the list of attributes you care about, you can intersect it with the object you're examining and see if the intersection is only one item:

```<code>var attributesICareAbout = new List<Attribute>
{
    AllAttributes.Attribute("Quick"),
    AllAttributes.Attribute("Brown"),
    AllAttributes.Attribute("Fox"),
    AllAttributes.Attribute("Jumps"),
    AllAttributes.Attribute("Lazy"),
    AllAttributes.Attribute("Dogs")
};

// To get all items that have only a single attribute from our list and no others:
.Where(x => x.Attributes().Intersect(attributesICareAbout).Count == 1);
</code>```

To get the items that have a specific attribute and no others:

```<code>// To get all the items who have only a single "Quick" attribute:
.Where(x => x.Attributes().Count(a => a == AllAttributes.Attribute("Quick")) == 1);
</code>```

Body:
The following code works as intended but seems inelegant.

.Where(x =>     x.Attributes().Contains(x.Attribute("Quick"))
            && !x.Attributes().Contains(x.Attribute("Brown"))
            && !x.Attributes().Contains(x.Attribute("Fox"))
            && !x.Attributes().Contains(x.Attribute("Jumps"))
            && !x.Attributes().Contains(x.Attribute("Lazy"))
            && !x.Attributes().Contains(x.Attribute("Dogs")))

As you can see, I am checking whether

the XElement has exactly one attribute

this attribute has the specified name

[Edit] My intention is..I want to make sure that the element has only one attribute. I mean only "Quick" attribute in this case. I know the count style though, the count does not distinguish its name.[/Edit]

[Edit2]I want elements if only if it has sigle attribute, nothing else.[/Edit2]

[Edit3]"x" is an element for instance..

<mySeg Quick="1" Brown="Two" Fox="None" Jumps="2016_En" Lazy="100" Dogs="Source">  //  I do not want this XElement

or

<mySeg Quick="2" Brown="Ten">  //  Nah.

or

<mySeg Quick="3">  // yes, this is one I'm looking for.

[Edit3]

[Edit4]
I guess, I have to use this one. Actually, it is the one I used before this post. I was thingking one shot.

x.Attributes().Contains(x.Attribute("Quick")) && x.Attributes().Count() == 1 //thanks Ryan

[Edit4]

Body:
If you want to ensure that it contains one and only one of a list of attributes, and you can create the list of attributes you care about, you can intersect it with the object you're examining and see if the intersection is only one item:

var attributesICareAbout = new List<Attribute>
{
    AllAttributes.Attribute("Quick"),
    AllAttributes.Attribute("Brown"),
    AllAttributes.Attribute("Fox"),
    AllAttributes.Attribute("Jumps"),
    AllAttributes.Attribute("Lazy"),
    AllAttributes.Attribute("Dogs")
};

// To get all items that have only a single attribute from our list and no others:
.Where(x => x.Attributes().Intersect(attributesICareAbout).Count == 1);

To get the items that have a specific attribute and no others:

// To get all the items who have only a single "Quick" attribute:
.Where(x => x.Attributes().Count(a => a == AllAttributes.Attribute("Quick")) == 1);


问:
Matching Latin Letters, including Serbo-Croatian characters
I am trying to write a regex (regular expression) in PHP to match all Latin letters, including those specific to Serbo-Croatian, such as "ćčđšž"

Here is my code:

```<code>public function alpha_space( $str )
{
    return ( ! preg_match( "/^([-a-z0-9_ ])+$/i", $str ) ) ? FALSE : TRUE;
}
</code>```

How should I modify this snippet so that the regex applies as well to Serbo-Croatian letters?

Thank you for any thoughts you wish to offer.

答:
These are members of the Unicode Latin Extended A block, which goes from 0x0100 to 0x017F. You can limit characters by code point by using the u flag:

```<code>$test = "ćčđšž";
$start = "100";
$finish = "17f";
$pattern = "/^[\x{{$start}}-\x{{$finish}}]*$/u";
$result = preg_match($pattern, $test);
var_dump($result);
</code>```

So extending this to your original pattern would look something like this:

```<code>$pattern = "/^[-a-z0-9_ \x{100}-\x{17f}]+$/ui";
</code>```

Body:
I am trying to write a regex (regular expression) in PHP to match all Latin letters, including those specific to Serbo-Croatian, such as "ćčđšž"

Here is my code:

public function alpha_space( $str )
{
    return ( ! preg_match( "/^([-a-z0-9_ ])+$/i", $str ) ) ? FALSE : TRUE;
}

How should I modify this snippet so that the regex applies as well to Serbo-Croatian letters?

Thank you for any thoughts you wish to offer.

Body:
These are members of the Unicode Latin Extended A block, which goes from 0x0100 to 0x017F. You can limit characters by code point by using the u flag:

$test = "ćčđšž";
$start = "100";
$finish = "17f";
$pattern = "/^[\x{{$start}}-\x{{$finish}}]*$/u";
$result = preg_match($pattern, $test);
var_dump($result);

So extending this to your original pattern would look something like this:

$pattern = "/^[-a-z0-9_ \x{100}-\x{17f}]+$/ui";


问:
matching two strings VBA
This one has really gotten me stumped but it seems like there is an easy soluition.

I have a code where I am matching two string to display Failed if they dont match and Done is if they do.

I first grab the text to append here

```<code>....
    Do While ie.getRowsInTables("tbl_business") ' table class name
    For Each tr In ie.tableRows
        For Each cell In tr.Cells
            If (InStr(cell.innerHTML, "SystemComments")) Then
                innerText = cell.innerText
            End If
        Next
    Next
    Exit Do
Loop
...
</code>```

This is where I set the text area:

```<code>...
tmpString = ie.SetPageID("SystemComments", innerText & vbCrLf & "eATO: " & eMASSFieldAppender.cbATO.text & vbCrLf & "PSO: " & eMASSFieldAppender.tbPSO.text & vbCrLf & "AMP: " & eMASSFieldAppender.tbAMP)
...
</code>```

This is where I try a conditional statment to spit out done or failed

```<code>...
If (ie.GetEditSipPage(emass_id) = True) Then
    tmpString = ie.GetPageID("SystemComments")

    If (tmpString = innerText & vbCrLf & "eATO: " & eMASSFieldAppender.cbATO.text & vbCrLf & "PSO: " & eMASSFieldAppender.tbPSO.text & vbCrLf & "AMP: " & eMASSFieldAppender.tbAMP) Then

        Worksheets(wrksht).Cells(readRow, 2).value = "Done"
    Else
        Worksheets(wrksht).Cells(readRow, 2).value = "FAILED TO UPDATE"
    End If
...
</code>```

Please note my code is fully functional but it is just not matching up those statements.

When I do a Debug.Print they appear to be the same exact statements.

What Am I missing?

答:
Depending on what you're writing to innerHTML, there's no guarantee it will read back out exactly the same as when you put it in.

For example, if you set innerHTML = "A{six spaces}B" it will read back out as "A{one space}B" because multiple spaces typically get collapsed to a single space in HTML.

Bottom line, innerHTML is not a good place to store random text if you need it to come back unchanged..

Title: matching two strings VBA

Body:
This one has really gotten me stumped but it seems like there is an easy soluition.

I have a code where I am matching two string to display Failed if they dont match and Done is if they do.

I first grab the text to append here

....
    Do While ie.getRowsInTables("tbl_business") ' table class name
    For Each tr In ie.tableRows
        For Each cell In tr.Cells
            If (InStr(cell.innerHTML, "SystemComments")) Then
                innerText = cell.innerText
            End If
        Next
    Next
    Exit Do
Loop
...

This is where I set the text area:

...
tmpString = ie.SetPageID("SystemComments", innerText & vbCrLf & "eATO: " & eMASSFieldAppender.cbATO.text & vbCrLf & "PSO: " & eMASSFieldAppender.tbPSO.text & vbCrLf & "AMP: " & eMASSFieldAppender.tbAMP)
...

This is where I try a conditional statment to spit out done or failed

...
If (ie.GetEditSipPage(emass_id) = True) Then
    tmpString = ie.GetPageID("SystemComments")

    If (tmpString = innerText & vbCrLf & "eATO: " & eMASSFieldAppender.cbATO.text & vbCrLf & "PSO: " & eMASSFieldAppender.tbPSO.text & vbCrLf & "AMP: " & eMASSFieldAppender.tbAMP) Then

        Worksheets(wrksht).Cells(readRow, 2).value = "Done"
    Else
        Worksheets(wrksht).Cells(readRow, 2).value = "FAILED TO UPDATE"
    End If
...

Please note my code is fully functional but it is just not matching up those statements.

When I do a Debug.Print they appear to be the same exact statements.

What Am I missing?


问:
How to get the Python interpreter to emit a NOP instruction?
Is there any way to get Python's interpreter to compile any Python code into a NOP instruction?

(I'm specifically talking about obtaining bytecode via compiling Python code, not generating it directly.)

答:
This appears to be impossible. NOP opcodes are only generated by the peephole optimizer, but the last step of peephole optimization removes all NOPs and retargets jumps for the new instruction indices.

In fact, barring bugs, this seems likely to have been impossible in every Python version ever released. In Python 2.3, there was no NOP opcode, and in Python 2.4, the peephole optimizer already removed all NOPs it generated.


问:
Why isn't my usort() output sorted?
I'm rewriting an old script that spits out the most popular content using usort.

For some reason, the output of my usort isn't actually sorted.

I'm using php 5.5 (please disregard the use of the depreciated mysql_ function, that is part of the reason I am rewriting this script).

```<code>    //store data in array
    $sort_array = array();
    while($row = mysql_fetch_assoc($result)) {
        //calculate age
        $age = (strtotime("now") - strtotime($row["DATE"]))/86400;//86400 converts seconds to days
        //calculate "effective views" via gaussian distribution shown below
        //y = e^(-(k * x)^2) where k is below
        $K = 0.1665109222315395512706329289790402095261177704528881;//solved for a half-life of 5 days
        $effective_views = round($row["VIEWS"] * exp(-pow( $K * $age, 2)));

        //store data
        $article = new stdClass;
        //$article->id = $row["ID"];
        $article->effective_views = $effective_views;
        //$article->title = $row["TITLE"];
        //$article->author = $row["AUTHOR"];
        $sort_array[] = $article;
    }

    //sort array based on effective views
    usort(
        $sort_array,
        function($a, $b) {
            return -strcmp($a->effective_views, $b->effective_views);
        }
    );
    echo "```";
    print_r($sort_array);
```

The output should be sorted on effective_views in descending order, however, it is not.

Here is an output dump:

http://pastebin.com/rV5YwWN7

Please inform me what I am doing wrong here.

答:
Strcmp - Binary safe string comparison

You can not use strcmp like that because it is not to compare numbers, if you want to compare numbers using strcmp you can use a little trick like this:

```<code>function cmp($a, $b)
{
    if ($a == $b) {
        return 0;
    }
    return ($a > $b) ? -1 : 1;
}

$a = array(3, 7, 733, 9, 73, 222, 5, 99, 1, 5, 0);
usort($a, "cmp");

foreach ($a as $key => $value) {
    echo "$key: $value\n";
}
</code>```

And if you want to use Comparison Operators:

```<code>function cmp2($a, $b) {
    if(strlen($a)!==strlen($b)){
    return -strcmp(strlen($a),strlen($b));
    }
    return -strcmp($a, $b);
}

$a = array(3, 7, 733, 9, 73, 222, 5, 99, 1, 5, 0);
usort($a, "cmp2");

foreach ($a as $key => $value) {
    echo "$key: $value\n";
}
</code>```

Example: http://sandbox.onlinephpfunctions.com/

Title: Why isn't my usort() output sorted?

Body:
I'm rewriting an old script that spits out the most popular content using usort.

For some reason, the output of my usort isn't actually sorted.

I'm using php 5.5 (please disregard the use of the depreciated mysql_ function, that is part of the reason I am rewriting this script).

    //store data in array
    $sort_array = array();
    while($row = mysql_fetch_assoc($result)) {
        //calculate age
        $age = (strtotime("now") - strtotime($row["DATE"]))/86400;//86400 converts seconds to days
        //calculate "effective views" via gaussian distribution shown below
        //y = e^(-(k * x)^2) where k is below
        $K = 0.1665109222315395512706329289790402095261177704528881;//solved for a half-life of 5 days
        $effective_views = round($row["VIEWS"] * exp(-pow( $K * $age, 2)));

        //store data
        $article = new stdClass;
        //$article->id = $row["ID"];
        $article->effective_views = $effective_views;
        //$article->title = $row["TITLE"];
        //$article->author = $row["AUTHOR"];
        $sort_array[] = $article;
    }

    //sort array based on effective views
    usort(
        $sort_array,
        function($a, $b) {
            return -strcmp($a->effective_views, $b->effective_views);
        }
    );
    echo "
";
    print_r($sort_array);

The output should be sorted on effective_views in descending order, however, it is not.

Here is an output dump:

http://pastebin.com/rV5YwWN7

Please inform me what I am doing wrong here.

Body:
Strcmp - Binary safe string comparison

You can not use strcmp like that because it is not to compare numbers, if you want to compare numbers using strcmp you can use a little trick like this:

function cmp($a, $b)
{
    if ($a == $b) {
        return 0;
    }
    return ($a > $b) ? -1 : 1;
}

$a = array(3, 7, 733, 9, 73, 222, 5, 99, 1, 5, 0);
usort($a, "cmp");

foreach ($a as $key => $value) {
    echo "$key: $value\n";
}

And if you want to use Comparison Operators:

function cmp2($a, $b) {
    if(strlen($a)!==strlen($b)){
    return -strcmp(strlen($a),strlen($b));
    }
    return -strcmp($a, $b);
}

$a = array(3, 7, 733, 9, 73, 222, 5, 99, 1, 5, 0);
usort($a, "cmp2");

foreach ($a as $key => $value) {
    echo "$key: $value\n";
}

Example: http://sandbox.onlinephpfunctions.com/


问:
Conditional statements with too many ifelse statements
I have the following data:

```<code>my.list<-list(a=c(55,17,18,18,18,21),
b=c(11,17,17,17,22,18,22),
c=c(55,17,22,22,22,22,22,21,30))

x<-c(1,1,1,1,2,2,3,3,3,3,3,3,3,3,3)

set.seed(1)

my.function <- function(x) {

ifelse(x == 1,sample(my.list$a,replace = T),
ifelse(x == 2,sample(my.list$b,replace = T),
ifelse(x == 3,sample(my.list$c,replace = T)

)))
}

p<-sapply(x, my.function)
</code>```

In the "real" dataset I have much more ifelse-statements than shown above and the code is too long.

Is there a smarter solution so I don't need to write so many ifelse-statements? Every ifelse-statement is related to a unique list as above with different lengths that I draw samples from.

答:
That double use of x confused me a bit. If I understand you correctly,

```<code>my.function <- function(x) {
   sample(my.list[[1]],size = 1,replace = T)
}
</code>```

should give you what you want.

Body:
I have the following data:

my.list<-list(a=c(55,17,18,18,18,21),
b=c(11,17,17,17,22,18,22),
c=c(55,17,22,22,22,22,22,21,30))

x<-c(1,1,1,1,2,2,3,3,3,3,3,3,3,3,3)

set.seed(1)

my.function <- function(x) {

ifelse(x == 1,sample(my.list$a,replace = T),
ifelse(x == 2,sample(my.list$b,replace = T),
ifelse(x == 3,sample(my.list$c,replace = T)

)))
}

p<-sapply(x, my.function)

In the "real" dataset I have much more ifelse-statements than shown above and the code is too long.

Is there a smarter solution so I don't need to write so many ifelse-statements? Every ifelse-statement is related to a unique list as above with different lengths that I draw samples from.

Body:
That double use of x confused me a bit. If I understand you correctly,

my.function <- function(x) {
   sample(my.list[[1]],size = 1,replace = T)
}

should give you what you want.