问:
Android - AuthUI - firebase doesn't work when login by facebook
Welcome everybody,
A have an application in android studio,
I use the firebase, but when the user login
by AuthUI to login by (facebook or google)

```<code>    try {
        startActivityForResult(
                AuthUI.getInstance()
                        .createSignInIntentBuilder()
                        .setAvailableProviders(
                                Arrays.asList(new AuthUI.IdpConfig.Builder(AuthUI.EMAIL_PROVIDER).build(),
                                        new AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER).build(),
                                        new AuthUI.IdpConfig.Builder(AuthUI.FACEBOOK_PROVIDER).build()
                                ))
                        .build(),
                RC_SIGN_IN);
    } catch (Exception e) {
        Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
    }
</code>```

and the user success login then
the firebase doesn't work.
When a user logout,

```<code>    AuthUI.getInstance()
            .signOut(this)
            .addOnCompleteListener(new OnCompleteListener<Void>() {
                public void onComplete(@NonNull Task<Void> task) {
                    // user is now signed out
                    // finish();
                }
            });
</code>```

the firebase start working normally

答:
I use this for my google sign in and out. works great! You will of course have to adapt for your resources. If this does not fix the problem, then you may have library dependency issue. let me know

public class MainActivity extends AppCompatActivity implements
        GoogleApiClient.OnConnectionFailedListener,
        View.OnClickListener {

```<code>private static final String TAG = "GoogleActivity";
private static final int RC_SIGN_IN = 9001;

// [START declare_auth]
private FirebaseAuth mAuth;
// [END declare_auth]

private GoogleApiClient mGoogleApiClient;

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

    // Views

    // Button listeners
    findViewById(R.id.sign_in_button).setOnClickListener(this);
    findViewById(R.id.sign_out_button).setOnClickListener(this);
    findViewById(R.id.buttonGoChat).setOnClickListener(this);

    // [START config_signin]
    // Configure Google Sign In
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id))
            .requestEmail()
            .build();
    // [END config_signin]

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();

    // [START initialize_auth]
    mAuth = FirebaseAuth.getInstance();
    // [END initialize_auth]
}

// [START on_start_check_user]
@Override
public void onStart() {
    super.onStart();
    // Check if user is signed in (non-null) and update UI accordingly.
    FirebaseUser currentUser = mAuth.getCurrentUser();
    updateUI(currentUser);
}
// [END on_start_check_user]

// [START onactivityresult]
@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);
        if (result.isSuccess()) {
            // Google Sign In was successful, authenticate with Firebase
            GoogleSignInAccount account = result.getSignInAccount();
            firebaseAuthWithGoogle(account);
        } else {
            // Google Sign In failed, update UI appropriately
            // [START_EXCLUDE]
            updateUI(null);
            // [END_EXCLUDE]
        }
    }
}
// [END onactivityresult]

// [START auth_with_google]
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());

    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
    mAuth.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 = mAuth.getCurrentUser();
                        updateUI(user);
                    } else {
                        // If sign in fails, display a message to the user.
                        Log.w(TAG, "signInWithCredential:failure", task.getException());
                        Toast.makeText(MainActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                        updateUI(null);
                    }

                }
            });
}
// [END auth_with_google]

// [START signin]
private void signIn() {
    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
    startActivityForResult(signInIntent, RC_SIGN_IN);
}
// [END signin]

private void signOut() {
    // Firebase sign out
    mAuth.signOut();

    // Google sign out
    Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
            new ResultCallback<Status>() {
                @Override
                public void onResult(@NonNull Status status) {
                    updateUI(null);
                }
            });
}

private void updateUI(FirebaseUser user) {

    if (user != null) {

        findViewById(R.id.buttonGoChat).setVisibility(View.VISIBLE);
        findViewById(R.id.sign_in_button).setVisibility(View.GONE);
        findViewById(R.id.sign_out_button).setVisibility(View.VISIBLE);
    } else {

        findViewById(R.id.buttonGoChat).setVisibility(View.GONE);
        findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
        findViewById(R.id.sign_out_button).setVisibility(View.GONE);
    }
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    // An unresolvable error has occurred and Google APIs (including Sign-In) will not
    // be available.
    Log.d(TAG, "onConnectionFailed:" + connectionResult);
    Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show();
}

@Override
public void onClick(View v) {
    Intent go = new Intent();
    int i = v.getId();
    if (i == R.id.sign_in_button) {
        signIn();
    } else if (i == R.id.sign_out_button) {
        signOut();
    } else if (i == R.id.buttonGoChat){
        go.setClass(getApplicationContext(),ChatActivity.class);
        startActivity(go);
    }
}
</code>```

}

Body:
Welcome everybody,
A have an application in android studio,
I use the firebase, but when the user login
by AuthUI to login by (facebook or google)

    try {
        startActivityForResult(
                AuthUI.getInstance()
                        .createSignInIntentBuilder()
                        .setAvailableProviders(
                                Arrays.asList(new AuthUI.IdpConfig.Builder(AuthUI.EMAIL_PROVIDER).build(),
                                        new AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER).build(),
                                        new AuthUI.IdpConfig.Builder(AuthUI.FACEBOOK_PROVIDER).build()
                                ))
                        .build(),
                RC_SIGN_IN);
    } catch (Exception e) {
        Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
    }

and the user success login then
the firebase doesn't work.
When a user logout,

    AuthUI.getInstance()
            .signOut(this)
            .addOnCompleteListener(new OnCompleteListener<Void>() {
                public void onComplete(@NonNull Task<Void> task) {
                    // user is now signed out
                    // finish();
                }
            });

the firebase start working normally

Body:
I use this for my google sign in and out. works great! You will of course have to adapt for your resources. If this does not fix the problem, then you may have library dependency issue. let me know

public class MainActivity extends AppCompatActivity implements
        GoogleApiClient.OnConnectionFailedListener,
        View.OnClickListener {

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

// [START declare_auth]
private FirebaseAuth mAuth;
// [END declare_auth]

private GoogleApiClient mGoogleApiClient;

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

    // Views

    // Button listeners
    findViewById(R.id.sign_in_button).setOnClickListener(this);
    findViewById(R.id.sign_out_button).setOnClickListener(this);
    findViewById(R.id.buttonGoChat).setOnClickListener(this);

    // [START config_signin]
    // Configure Google Sign In
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id))
            .requestEmail()
            .build();
    // [END config_signin]

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();

    // [START initialize_auth]
    mAuth = FirebaseAuth.getInstance();
    // [END initialize_auth]
}

// [START on_start_check_user]
@Override
public void onStart() {
    super.onStart();
    // Check if user is signed in (non-null) and update UI accordingly.
    FirebaseUser currentUser = mAuth.getCurrentUser();
    updateUI(currentUser);
}
// [END on_start_check_user]

// [START onactivityresult]
@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);
        if (result.isSuccess()) {
            // Google Sign In was successful, authenticate with Firebase
            GoogleSignInAccount account = result.getSignInAccount();
            firebaseAuthWithGoogle(account);
        } else {
            // Google Sign In failed, update UI appropriately
            // [START_EXCLUDE]
            updateUI(null);
            // [END_EXCLUDE]
        }
    }
}
// [END onactivityresult]

// [START auth_with_google]
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());

    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
    mAuth.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 = mAuth.getCurrentUser();
                        updateUI(user);
                    } else {
                        // If sign in fails, display a message to the user.
                        Log.w(TAG, "signInWithCredential:failure", task.getException());
                        Toast.makeText(MainActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                        updateUI(null);
                    }

                }
            });
}
// [END auth_with_google]

// [START signin]
private void signIn() {
    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
    startActivityForResult(signInIntent, RC_SIGN_IN);
}
// [END signin]

private void signOut() {
    // Firebase sign out
    mAuth.signOut();

    // Google sign out
    Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
            new ResultCallback<Status>() {
                @Override
                public void onResult(@NonNull Status status) {
                    updateUI(null);
                }
            });
}

private void updateUI(FirebaseUser user) {

    if (user != null) {

        findViewById(R.id.buttonGoChat).setVisibility(View.VISIBLE);
        findViewById(R.id.sign_in_button).setVisibility(View.GONE);
        findViewById(R.id.sign_out_button).setVisibility(View.VISIBLE);
    } else {

        findViewById(R.id.buttonGoChat).setVisibility(View.GONE);
        findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
        findViewById(R.id.sign_out_button).setVisibility(View.GONE);
    }
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    // An unresolvable error has occurred and Google APIs (including Sign-In) will not
    // be available.
    Log.d(TAG, "onConnectionFailed:" + connectionResult);
    Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show();
}

@Override
public void onClick(View v) {
    Intent go = new Intent();
    int i = v.getId();
    if (i == R.id.sign_in_button) {
        signIn();
    } else if (i == R.id.sign_out_button) {
        signOut();
    } else if (i == R.id.buttonGoChat){
        go.setClass(getApplicationContext(),ChatActivity.class);
        startActivity(go);
    }
}

}


来源: stackexchange

问:
How do you manage your gists on GitHub?
I love GitHub and their gist service, and that's why I'm keeping a lot of code snippets and even development notes as a gist on my GitHub account. It also makes it easy to share them with my colleagues.

The problem is that it doesn't scale!! The GitHub features for gist are primitive, and I have lots of gists there which make it really difficult to find some of my old gists. There's no search, no tagging, or anything.

Do you know any application that can handle this mess? I would like an application that could

Search my gists

List my gists by source type and date

Let me edit or copy them

Let me tag or at least edit description

I would love to see something like this, and I'm willing to pay even some bucks for it.

So how do you manage you gists on GitHub? Do you know any software?

There's one called drift written in MacRuby, but I couldn't compile it, and it hasn't been updated for a while.

答:
If your snippets are Ruby snippets, I'd suggest boson. I use it to maintain my repository of 450+ ruby commands (snippets). I search my commands by name, description, usage, alias and other fields as well as sort by them.

Since my commands reside in local files, I can easily export to gists or install gists as boson commands. I can do all of the things you want to do except list by date and tag. Listing by date is trivial (timestamp of the file) and tags is something I'd like to add to boson as a plugin one day.

ContentLicense: CC BY-SA 3.0

Title: How do you manage your gists on GitHub?


问:
When scale the data, why the train dataset use 'fit' and 'transform', but the test dataset only use 'transform'?
When scale the data, why the train dataset use 'fit' and 'transform', but the test dataset only use 'transform'?

```<code>SAMPLE_COUNT = 5000
TEST_COUNT = 20000
seed(0)
sample = list()
test_sample = list()
for index, line in enumerate(open('covtype.data','rb')):
    if index < SAMPLE_COUNT:
        sample.append(line)
    else:
        r = randint(0,index)
        if r < SAMPLE_COUNT:
            sample[r] = line
        else:
            k = randint(0,index)
            if k < TEST_COUNT:
                if len(test_sample) < TEST_COUNT:
                    test_sample.append(line)
                else:
                    test_sample[k] = line
from sklearn.preprocessing import StandardScaler
for n, line in enumerate(sample):
sample[n] = map(float, line.strip().split(','))
y = np.array(sample)[:,-1]
scaling = StandardScaler()

X = scaling.fit_transform(np.array(sample)[:,:-1]) ##here use fit and transform

for n,line in enumerate(test_sample):
test_sample[n] = map(float,line.strip().split(','))
yt = np.array(test_sample)[:,-1]

Xt = scaling.transform(np.array(test_sample)[:,:-1])##why here only use transform
</code>```

As the annotation says, why Xt only use transform but no fit?

答:
fit() is used to compute the parameter needed for transformation and transform() is for scaling the data to convert into standard format for the model.

fit_tranform() is combination of two which is doing above work in efficiently.

Since fit_transform() is already computing and transforming the training data only transformation for testing data is left,since parameter needed for transformation is already computed and stored only transformation() of testing data is left therefor only transform() is used instead of fit_transform().

Body:
When scale the data, why the train dataset use 'fit' and 'transform', but the test dataset only use 'transform'?

SAMPLE_COUNT = 5000
TEST_COUNT = 20000
seed(0)
sample = list()
test_sample = list()
for index, line in enumerate(open('covtype.data','rb')):
    if index < SAMPLE_COUNT:
        sample.append(line)
    else:
        r = randint(0,index)
        if r < SAMPLE_COUNT:
            sample[r] = line
        else:
            k = randint(0,index)
            if k < TEST_COUNT:
                if len(test_sample) < TEST_COUNT:
                    test_sample.append(line)
                else:
                    test_sample[k] = line
from sklearn.preprocessing import StandardScaler
for n, line in enumerate(sample):
sample[n] = map(float, line.strip().split(','))
y = np.array(sample)[:,-1]
scaling = StandardScaler()

X = scaling.fit_transform(np.array(sample)[:,:-1]) ##here use fit and transform

for n,line in enumerate(test_sample):
test_sample[n] = map(float,line.strip().split(','))
yt = np.array(test_sample)[:,-1]

Xt = scaling.transform(np.array(test_sample)[:,:-1])##why here only use transform

As the annotation says, why Xt only use transform but no fit?


问:
How to get the id of the td based if the text value matches exactly
How to get the id of the td based if the text value matches exactly?

    George
    George2
    George3
    Georg

```

I want the id of "Georg" td4 to get returned?

答:
```<code>$('#tid1 tr').each(function() {
   $(this).children('td').each(function(j){
        var data =  $(this).html().trim();
        if(data==="Georg"){
           alert("Id of td which contain text 'George' " +$(this).attr('id'));
        }
    });
});
</code>```

Body:
How to get the id of the td based if the text value matches exactly?

    George
    George2
    George3
    Georg

I want the id of "Georg" td4 to get returned?


问:
Exporting MySQL data to Excel gives errors
While exporting data to excel, using PHP, it gets exported, but i keep getting these error messages:

"The file format and extension of 'database.xls' don't match. The file could be corrupted or unsafe. Unless you trust its source don't open it. Do you want to open it anyway?"

"Excel has detected that 'database.xls' is a SYLK file, but cannot load it. Either the file has errors or it is not a SYLK file format. Clic OK to try to open in a different format."

After clicking OK a few times, it does open, but I'd like to know if there's an easy way to fix this.

This is the code (used John Peter's code):

```<code><?php
    //db connection data
    //create MySQL connection
    $sql = "Select * from $DB_TBLName";
    $Connect = @mysql_connect($DB_Server, $DB_Username, $DB_Password) or die("Couldn't connect to       MySQL:<br>" . mysql_error() . "<br>" . mysql_errno());
    //select database
    $Db = @mysql_select_db($DB_DBName, $Connect) or die("Couldn't select database:<br>" .     mysql_error(). "<br>" . mysql_errno());
    //execute query
    $result = @mysql_query($sql,$Connect) or die("Couldn't execute query:<br>" . mysql_error(). "    <br>" . mysql_errno());
    $file_ending = "xls";
    //header info for browser
    header("Content-Type: application/xls");
    header("Content-Disposition: attachment; filename=$filename.xls");
    header("Pragma: no-cache");
    header("Expires: 0");
    /*******Start of Formatting for Excel*******/
    //define separator (defines columns in excel & tabs in word)
    $sep = "\t"; //tabbed character
    //start of printing column names as names of MySQL fields
    for ($i = 0; $i < mysql_num_fields($result); $i++) {
        echo mysql_field_name($result,$i) . "\t";
    }
    print("\n");
    //end of printing column names
    //start while loop to get data
    while($row = mysql_fetch_row($result))
    {
        $schema_insert = "";
        for($j=0; $j<mysql_num_fields($result);$j++)
        {
            if(!isset($row[$j]))
                $schema_insert .= "NULL".$sep;
            elseif ($row[$j] != "")
                $schema_insert .= "$row[$j]".$sep;
            else
                $schema_insert .= "".$sep;
        }
        $schema_insert = str_replace($sep."$", "", $schema_insert);
        $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
        $schema_insert .= "\t";
        print(trim($schema_insert));
        print "\n";
    }
?>
</code>```

答:
These errors are not related to the programming language used to create the file. Both these errors are caused by a single bug in MS Excel.

MSDN:

When you try to open a text or comma separated variable (CSV) file, you receive the following error message:

```<code>SYLK: File format is not valid
</code>```

This problem occurs when you open a text or CSV file and the first two characters of the file are the letters ID (uppercase).

For complete details, refer https://support.microsoft.com/en-in/help/215591/-sylk-file-format-is-not-valid-error-message-when-you-open-a-file-in-e

Body:
While exporting data to excel, using PHP, it gets exported, but i keep getting these error messages:

"The file format and extension of 'database.xls' don't match. The file could be corrupted or unsafe. Unless you trust its source don't open it. Do you want to open it anyway?"

"Excel has detected that 'database.xls' is a SYLK file, but cannot load it. Either the file has errors or it is not a SYLK file format. Clic OK to try to open in a different format."

After clicking OK a few times, it does open, but I'd like to know if there's an easy way to fix this.

This is the code (used John Peter's code):

<?php
    //db connection data
    //create MySQL connection
    $sql = "Select * from $DB_TBLName";
    $Connect = @mysql_connect($DB_Server, $DB_Username, $DB_Password) or die("Couldn't connect to       MySQL:
" . mysql_error() . "
" . mysql_errno());
    //select database
    $Db = @mysql_select_db($DB_DBName, $Connect) or die("Couldn't select database:
" .     mysql_error(). "
" . mysql_errno());
    //execute query
    $result = @mysql_query($sql,$Connect) or die("Couldn't execute query:
" . mysql_error(). "
" . mysql_errno());
    $file_ending = "xls";
    //header info for browser
    header("Content-Type: application/xls");
    header("Content-Disposition: attachment; filename=$filename.xls");
    header("Pragma: no-cache");
    header("Expires: 0");
    /*******Start of Formatting for Excel*******/
    //define separator (defines columns in excel & tabs in word)
    $sep = "\t"; //tabbed character
    //start of printing column names as names of MySQL fields
    for ($i = 0; $i < mysql_num_fields($result); $i++) {
        echo mysql_field_name($result,$i) . "\t";
    }
    print("\n");
    //end of printing column names
    //start while loop to get data
    while($row = mysql_fetch_row($result))
    {
        $schema_insert = "";
        for($j=0; $j<mysql_num_fields($result);$j++)
        {
            if(!isset($row[$j]))
                $schema_insert .= "NULL".$sep;
            elseif ($row[$j] != "")
                $schema_insert .= "$row[$j]".$sep;
            else
                $schema_insert .= "".$sep;
        }
        $schema_insert = str_replace($sep."$", "", $schema_insert);
        $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
        $schema_insert .= "\t";
        print(trim($schema_insert));
        print "\n";
    }
?>

Body:
These errors are not related to the programming language used to create the file. Both these errors are caused by a single bug in MS Excel.

MSDN:

When you try to open a text or comma separated variable (CSV) file, you receive the following error message:

SYLK: File format is not valid

This problem occurs when you open a text or CSV file and the first two characters of the file are the letters ID (uppercase).

For complete details, refer https://support.microsoft.com/en-in/help/215591/-sylk-file-format-is-not-valid-error-message-when-you-open-a-file-in-e


问:
Different Java file name than the class name in Eclipse IDE
I am at the beginner level in JAVA and finding difficulty in understanding this scenario.

I have read that, the name of the class should match the name of the file that holds the program. In the attached image, i have two classes and the name of the class file is different than that of classes having the program.

When compiled in cmd it shows error as expected, but why the Eclipse compiler not giving any error here ?

Eclipse Image

答: In java, It doesn't need to match the name of the class and the name of the file that holds the program. When the class is public, then it should be same name for the class name and the source file name.</p>


问:
Open world assumption and SPARQL in triple stores
I would like to know if SPARQL, by default, adopts the open world assumption or if this depends on the triple stores that execute the SPARQL queries.

And what are the implications of this assumption in queries.

Best regards.

答: SPARQL follows the Closed World Assumption and assumes RDF data to be  complete. This does not affect positive queries, but SPARQL queries with negation make only sense under closed world semantics.</p>


问:
What does assignment to *this do (*this = val)?
I was browsing Qt sources, and noticed this

```<code>QUuid &operator=(const GUID &guid)
{
    *this = QUuid(guid);
    return *this;
}
</code>```

I've never seen assignment to "this" before. What does assignment to "this" do?

答:
'this' is simply a pointer to the object on which the current method is invoked. Changing the value  behind 'this' (by dereferencing the pointer using '*this' and assigning another object) modifies the caller's object to become another one.

In your example, a caller of 'operator=' might do the following:

```<code>GUID guid = guid(...) ;
QUuid uid = guid ;
</code>```

According to the definition of 'operator=' this action copy-converts 'guid' into a new object of type 'QUuid'.

ContentLicense: CC BY-SA 2.5

Body:
I was browsing Qt sources, and noticed this

QUuid &operator=(const GUID &guid)
{
    *this = QUuid(guid);
    return *this;
}

I've never seen assignment to "this" before. What does assignment to "this" do?

Body:
'this' is simply a pointer to the object on which the current method is invoked. Changing the value  behind 'this' (by dereferencing the pointer using '*this' and assigning another object) modifies the caller's object to become another one.

In your example, a caller of 'operator=' might do the following:

GUID guid = guid(...) ;
QUuid uid = guid ;

According to the definition of 'operator=' this action copy-converts 'guid' into a new object of type 'QUuid'.


问:
How to align  value to center vertically?
I need to align td cell value to center, both horizontally and vertically.  has a rowspan attribute.

The output right now is like:

```<code>A  |  B  |  C  |  D
1  |  2  |  3  |  4
1  |  2  |  3  |
1  |  2  |  3  |
</code>```

Desired:

```<code>A  |  B  |  C  |  D
1  |  2  |  3  |
1  |  2  |  3  |  4
1  |  2  |  3  |
1  |  2  |  3  |
</code>```

答:
Try :</p>

```<code><td style="vertical-align : middle;text-align:center;">
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to align <td rowspan ="value"> value to center vertically?

Body:
I need to align td cell value to center, both horizontally and vertically.  has a rowspan attribute.

The output right now is like:

A  |  B  |  C  |  D
1  |  2  |  3  |  4
1  |  2  |  3  |
1  |  2  |  3  |

Desired:

A  |  B  |  C  |  D
1  |  2  |  3  |
1  |  2  |  3  |  4
1  |  2  |  3  |
1  |  2  |  3  |

Body:
Try :

<td style="vertical-align : middle;text-align:center;">


问:
Integrating GIT repository with Jenkins
When I am trying to give the Git URL in Jenkins source code management, I am getting this error:

```<code>Failed to connect to repository : Error performing command: git.exe ls-remote -h https://github.com/shivnathr/DevOPS1 HEAD
</code>```

How can I avoid it?

答: When you configure this in Jenkins, it gives this error. But if you ignore this error, does it then work for the build? Have you configured git tools in Jenkins? I am not sure if having git in the path for the user running Jenkins will work (it might), but if you configure a git tool, it should use the first tool in the list to find git. BUT, if the first tool is set to auto-install, then this problem can occur. Make sure the first git tool is just pointing to an installation on the machine. I believe this is a bug. I found this on one of my installations, but I have yet to open an issue for it. </p>

Title: Integrating GIT repository with Jenkins

Body:
When I am trying to give the Git URL in Jenkins source code management, I am getting this error:

Failed to connect to repository : Error performing command: git.exe ls-remote -h https://github.com/shivnathr/DevOPS1 HEAD

How can I avoid it?


问:
creating a dictionary with two lists when a key should have two values in python
hi I have two lists,

```<code>list1
['PO', 'NA', 'PO']

list2
['Post Office', 'Not Available', 'Post area']
</code>```

Iam trying to get a dictionary using this two lists
I tried, my_dict=dict(zip(list1,list2))
it gives,

```<code> {'NA': 'Not Available', 'PO': 'Post area'}
</code>```

but my expected output is,

```<code> {'NA': 'Not Available', 'PO': ['Post area','Post Office']}
</code>```

pls help

答:
This may not be exactly what you want because it gives you lists for single abbreviations, but it gives an output very similar to what you're looking for.
I hope it helps.

```<code>list1 = ['PO', 'NA', 'PO']
list2 = ['Post Office', 'Not Available', 'Post area']

my_dict = {}

for abbrev,value in zip(list1,list2):
    if abbrev in my_dict.keys():
        my_dict[abbrev] += [value]
    else:
        my_dict[abbrev] = [value]
</code>```

edit: For the sake of completeness, the code below will NOT create lists for single items and will function ok with large lists of items with many multiple matches.

```<code>list1 = ['PO', 'NA', 'PO']
list2 = ['Post Office', 'Not Available', 'Post area']

my_dict = {}

for abbrev,value in zip(list1,list2):
    if abbrev in my_dict.keys():
        if isinstance(my_dict[abbrev],str):
            my_dict[abbrev] = [my_dict[abbrev]]
        my_dict[abbrev] += [value]
    else:
        my_dict[abbrev] = value

print(my_dict)
</code>```

Body:
hi I have two lists,

list1
['PO', 'NA', 'PO']

list2
['Post Office', 'Not Available', 'Post area']

Iam trying to get a dictionary using this two lists
I tried, my_dict=dict(zip(list1,list2))
it gives,

 {'NA': 'Not Available', 'PO': 'Post area'}

but my expected output is,

 {'NA': 'Not Available', 'PO': ['Post area','Post Office']}

pls help

Body:
This may not be exactly what you want because it gives you lists for single abbreviations, but it gives an output very similar to what you're looking for.
I hope it helps.

list1 = ['PO', 'NA', 'PO']
list2 = ['Post Office', 'Not Available', 'Post area']

my_dict = {}

for abbrev,value in zip(list1,list2):
    if abbrev in my_dict.keys():
        my_dict[abbrev] += [value]
    else:
        my_dict[abbrev] = [value]

edit: For the sake of completeness, the code below will NOT create lists for single items and will function ok with large lists of items with many multiple matches.

list1 = ['PO', 'NA', 'PO']
list2 = ['Post Office', 'Not Available', 'Post area']

my_dict = {}

for abbrev,value in zip(list1,list2):
    if abbrev in my_dict.keys():
        if isinstance(my_dict[abbrev],str):
            my_dict[abbrev] = [my_dict[abbrev]]
        my_dict[abbrev] += [value]
    else:
        my_dict[abbrev] = value

print(my_dict)


问:
How to convert [0,3,4] into 100110 that is 6 digit string format in SQL Server 2012?
How to convert [0,3,4] into 100110 that is 6 digit string  format in SQL Server  2012 ?

Example

```<code>string  [2,4,5]
</code>```

should be converted into

```<code>string 001011
</code>```

I have to make 6 digit string , and the digit or position in the string 000000 should be convert to 1 suppose in above string [2,4,5] means 2nd ,4th and 5th index of 000000 should be converted to 1. Final string should be 001011

答:
You could try PARSENAME() function starts from SQL Server 2012

```<code>DECLARE @DATA1 VARCHAR(6) = '000000'

SELECT      A.DATA [Original String],
            STUFF(STUFF(STUFF(@DATA1, [First]+1, 1, '1'), [Second]+1 , 1, '1'), [Third]+1, 1, '1') [Converted String] FROM
(
    SELECT DATA, PARSENAME(REPLACE(REPLACE(REPLACE(DATA, '[', ''), ']',''), ',', '.'),3) [First], PARSENAME(REPLACE(REPLACE(REPLACE(DATA, '[', ''), ']',''), ',', '.'),2) [Second], PARSENAME(REPLACE(REPLACE(REPLACE(DATA, '[', ''), ']',''), ',', '.'),1) [Third] FROM <table_name>
) A
</code>```

Result :

```<code> Original String    Converted String
 [0, 3, 4]          100110
 [1, 3, 4]          010110
</code>```

You could learn Parsename() function.. https://learn.microsoft.com/en-us/sql/t-sql/functions/parsename-transact-sql

Body:
How to convert [0,3,4] into 100110 that is 6 digit string  format in SQL Server  2012 ?

Example

string  [2,4,5]

should be converted into

string 001011

I have to make 6 digit string , and the digit or position in the string 000000 should be convert to 1 suppose in above string [2,4,5] means 2nd ,4th and 5th index of 000000 should be converted to 1. Final string should be 001011

Body:
You could try PARSENAME() function starts from SQL Server 2012

DECLARE @DATA1 VARCHAR(6) = '000000'

SELECT      A.DATA [Original String],
            STUFF(STUFF(STUFF(@DATA1, [First]+1, 1, '1'), [Second]+1 , 1, '1'), [Third]+1, 1, '1') [Converted String] FROM
(
    SELECT DATA, PARSENAME(REPLACE(REPLACE(REPLACE(DATA, '[', ''), ']',''), ',', '.'),3) [First], PARSENAME(REPLACE(REPLACE(REPLACE(DATA, '[', ''), ']',''), ',', '.'),2) [Second], PARSENAME(REPLACE(REPLACE(REPLACE(DATA, '[', ''), ']',''), ',', '.'),1) [Third] FROM <table_name>
) A

Result :

 Original String    Converted String
 [0, 3, 4]          100110
 [1, 3, 4]          010110

You could learn Parsename() function.. https://learn.microsoft.com/en-us/sql/t-sql/functions/parsename-transact-sql


答:
Try add a extend function below</p>

```<code> <script>
    $(document).ready(function(){
    alert($("tr").find("td:textEquals('Georg')").attr('id'));
    });

 $.expr[':'].textEquals = function(el, i, m) {
    var searchText = m[3];
    var match = $(el).text().trim().match("^" + searchText + "$")
    return match && match.length > 0;
}
    </script>
</code>```

Title: How to get the id of the td based if the text value matches exactly

Body:
Try add a extend function below

 <script>
    $(document).ready(function(){
    alert($("tr").find("td:textEquals('Georg')").attr('id'));
    });

 $.expr[':'].textEquals = function(el, i, m) {
    var searchText = m[3];
    var match = $(el).text().trim().match("^" + searchText + "$")
    return match && match.length > 0;
}
    </script>


问:
I have a list of numbers where the 1st digit is appended to a new list, then last, then 2nd, then 2nd last and so on
Following is my code:

```<code>def alt_ele():
    mylist=list(input("Enter the elements: "))
    newlist=[int(i) for i in mylist]
    final_list=[]
    try:
        for x in range(len(newlist)):
            final_list.append(newlist.pop(0))
            final_list.append(newlist.pop())
            print(final_list)
    except IndexError:
        pass
</code>```

Now the Input I am giving is:

I/N: Enter the elements: 12345

My desired output is [1,5,2,4,3]

But the output I am actually getting is:

```<code>[1,5]
[1,5,2,4]
</code>```

Can anyone please help me figure out where am I going wrong? I tried but, I cannot figure it out by myself
Thanks in advance.

答:
You are currently printing the list in every iteration of the loop. Be careful with the indentation.

It should be:

```<code>for x in range(len(newlist)):
    final_list.append(newlist.pop(0))
    final_list.append(newlist.pop())
print(final_list)
</code>```

Body:
Following is my code:

def alt_ele():
    mylist=list(input("Enter the elements: "))
    newlist=[int(i) for i in mylist]
    final_list=[]
    try:
        for x in range(len(newlist)):
            final_list.append(newlist.pop(0))
            final_list.append(newlist.pop())
            print(final_list)
    except IndexError:
        pass

Now the Input I am giving is:

I/N: Enter the elements: 12345

My desired output is [1,5,2,4,3]

But the output I am actually getting is:

[1,5]
[1,5,2,4]

Can anyone please help me figure out where am I going wrong? I tried but, I cannot figure it out by myself
Thanks in advance.

Body:
You are currently printing the list in every iteration of the loop. Be careful with the indentation.

It should be:

for x in range(len(newlist)):
    final_list.append(newlist.pop(0))
    final_list.append(newlist.pop())
print(final_list)


问:
How do I use a HL7 FHIR custom tag?
Idea:
I would like to store the change action on each version of my FHIR Patient resource. For example, when it is created, the action is 'Created'. By similar token, if the subsequent actions on the same resource are 'updated', 'deleted' and 'restored from deleted', the action of each version of the same resource will be 'Updated', 'Deleted' and 'Restored'.

Implementation:
We are thinking to put the 'Action' into a customer defined resource.meta.tag. An example is shown below.

```<code>"tag" : [
        {
            "system" : "hxxp://mydomain/fhir/custom_tag/SystemActionStatus",
            "code" : "Updated"
        }
    ]
</code>```

Questions:

Is this the right usage and approach to use meta.tag for the system action idea? If not, what should I use?

Does FHIR allow custom meta.tag?

I tried to implement the above, but we got error when testing with a testing tool. Do I need to provide the code definition under hxxp://mydomain/fhir/custom_tag/SystemActionStatus such that a system can access the custom tag to find the definition of each code (created, updated, deleted and restored)?

Any suggestions or links are high appreciated.

答:
No, I think there are better approaches.

If you need to communicate this data to other systems the FHIR way,
you can use the AuditEvent resource to capture this data.

If it's just for internal storage, you could use an extra database table,
and store it outside of the resources.

Yes

No, you don't have to do that. Check the error from server you sent this to, to see why you couldn't put the tag on the resource.

Title: How do I use a HL7 FHIR custom tag?

Body:
Idea:
I would like to store the change action on each version of my FHIR Patient resource. For example, when it is created, the action is 'Created'. By similar token, if the subsequent actions on the same resource are 'updated', 'deleted' and 'restored from deleted', the action of each version of the same resource will be 'Updated', 'Deleted' and 'Restored'.

Implementation:
We are thinking to put the 'Action' into a customer defined resource.meta.tag. An example is shown below.

"tag" : [
        {
            "system" : "hxxp://mydomain/fhir/custom_tag/SystemActionStatus",
            "code" : "Updated"
        }
    ]

Questions:

Is this the right usage and approach to use meta.tag for the system action idea? If not, what should I use?

Does FHIR allow custom meta.tag?

I tried to implement the above, but we got error when testing with a testing tool. Do I need to provide the code definition under hxxp://mydomain/fhir/custom_tag/SystemActionStatus such that a system can access the custom tag to find the definition of each code (created, updated, deleted and restored)?

Any suggestions or links are high appreciated.


问:
Azure AD B2B in Azure Government
Is there any way to use Azure AD B2B in Azure Government?

Previously, when I clicked on "New user" and typed in a user from a different tenant (e.g. someguest@someothercompany.com) and it would tell me the users would be added as a guest but unlike Azure AD B2B in Azure commercial, it wouldn't send an email notification.

Now there's a separate "New guest user" button that's grayed out in Azure Government. Are there any conditions under which this button would show enabled? Or is there any other way to add a user from a different Azure AD tenant to my Azure AD Gov tenant?

答: Azure AD B2B is not yet supported in Azure Government. Support this ask by voting for it in the Azure Government feedback forum: Azure AD B2B in Azure Government

Title: Azure AD B2B in Azure Government


问:
How I can install AsteriskNOW on Amazon EC2?
I have a question about asterisk, I know that I can install asterisk on EC2, but my questions is:

Its possible install AsteriskNOW on Amazon EC2? if not, why? and where its the best possible server or solution for install this

thanks

答:
can you not just download the ISO directly?

```<code>ubuntu@ip-172-31-14-19:~/iso$
ubuntu@ip-172-31-14-19:~/iso$ wget -v https://downloads.asterisk.org/pub/telephony/asterisk-now/AsteriskNow-1013-current-64.iso
--2017-11-17 05:52:53--  https://downloads.asterisk.org/pub/telephony/asterisk-now/AsteriskNow-1013-current-64.iso
Resolving downloads.asterisk.org (downloads.asterisk.org)... 76.164.171.238, 2001:470:e0d4::ee
Connecting to downloads.asterisk.org (downloads.asterisk.org)|76.164.171.238|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 1343909888 (1.3G) [application/x-iso9660-image]
Saving to: ‘AsteriskNow-1013-current-64.iso’

AsteriskNow-1013-curr 100%[======================>]   1.25G  1.79MB/s    in 9m 54s

2017-11-17 06:02:48 (2.16 MB/s) - ‘AsteriskNow-1013-current-64.iso’ saved [1343909888/1343909888]

ubuntu@ip-172-31-14-19:~/iso$
</code>```

https://downloads.asterisk.org/pub/telephony/asterisk-now/

Body:
can you not just download the ISO directly?

ubuntu@ip-172-31-14-19:~/iso$
ubuntu@ip-172-31-14-19:~/iso$ wget -v https://downloads.asterisk.org/pub/telephony/asterisk-now/AsteriskNow-1013-current-64.iso
--2017-11-17 05:52:53--  https://downloads.asterisk.org/pub/telephony/asterisk-now/AsteriskNow-1013-current-64.iso
Resolving downloads.asterisk.org (downloads.asterisk.org)... 76.164.171.238, 2001:470:e0d4::ee
Connecting to downloads.asterisk.org (downloads.asterisk.org)|76.164.171.238|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 1343909888 (1.3G) [application/x-iso9660-image]
Saving to: ‘AsteriskNow-1013-current-64.iso’

AsteriskNow-1013-curr 100%[======================>]   1.25G  1.79MB/s    in 9m 54s

2017-11-17 06:02:48 (2.16 MB/s) - ‘AsteriskNow-1013-current-64.iso’ saved [1343909888/1343909888]

ubuntu@ip-172-31-14-19:~/iso$

https://downloads.asterisk.org/pub/telephony/asterisk-now/


问:
How "WPM" calculate in typing speed apps?
I'm working on typing speed app and I need to know what's the Formula of calculating WPM (Words Per Minute)

Edit:
indeed i know:

```<code>wpm = correct_characters_in_60_seconds / 5
</code>```

but i have no idea what should i do with decimal numbers like 22.6 or 19.7 and...

for example if user typed 158 keystrokes in 60 seconds so, 158/5 = 31.6
so do the result should be 32 WPM or 31 WPM? How?
thanks.

答:
Words per minute(WPM) should be rounded off to the closest decimal value.

In your case 158/5 = 31.6 should be reported as 32 and not 31.

However if the the value was 156/5 = 31.2 then it should be rounded off to 31 to approximate the closest decimal value and hence averaging the overall error.

if WPM<=x.5 then WPM = x else WPM = x+1

Body:
I'm working on typing speed app and I need to know what's the Formula of calculating WPM (Words Per Minute)

Edit:
indeed i know:

wpm = correct_characters_in_60_seconds / 5

but i have no idea what should i do with decimal numbers like 22.6 or 19.7 and...

for example if user typed 158 keystrokes in 60 seconds so, 158/5 = 31.6
so do the result should be 32 WPM or 31 WPM? How?
thanks.


问:
How can I insert a line break into a <Text> component in React Native?
I want to insert a new line (like \r\n,
) in a Text component in React Native.

If I have:

```<code><text>
<br />
Hi~<br />
this is a test message.<br />
</text>
</code>```

Then React Native renders Hi~ this is a test message.

Is it possible render text to add a new line like so:

```<code>Hi~
this is a test message.
</code>```

答:
You can use <code>{'\n'}</code> as line breaks.

    Hi~ {'\n'} this is a test message.
    </p>

Body:
I want to insert a new line (like \r\n,
) in a Text component in React Native.

If I have:

<text>

Hi~

this is a test message.

</text>

Then React Native renders Hi~ this is a test message.

Is it possible render text to add a new line like so:

Hi~
this is a test message.

Body:
You can use {'\n'} as line breaks.

    Hi~ {'\n'} this is a test message.


问:
IF condition not working in UPDATE query
In this code when I want to update the status from Pending to Accepted that time If statement not working.
In database I keep Pending by default. Problem is that when I'm going to update the status the STATUS will update but the code inside the If condition can't work.
please help me out from this problem.
Thanks in advance.

 <?php
include("connect.php");//conection
if(isset($_REQUEST['leave_id']))
{
$id=$_REQUEST['leave_id'];
}
else
{
$id=NULL;
}
$result = mysqli_query($con,"SELECT TAKEN_LEAVES,BALANCE_LEAVE,STATUS
                              FROM xxxemi_person_leave_t
                              WHERE leave_id= $id");
$res = mysqli_fetch_array($result);
if (!$result)
  {
  die("Error: Data not found..");
  }

 $taken_leave = $res['TAKEN_LEAVES'];
 $balance_leave = $res['BALANCE_LEAVE'];
 $status = $res['STATUS'];

    if(isset($_POST['save']))
          {
    if ($status=='ACCEPTED')
    {
   $status = $_POST['USTATUS'];
   $updated_balance_leave = $_POST['UBALANCE_LEAVE'];

   $updated_balance_leave = $balance_leave - $taken_leave;

   mysqli_query($con,"UPDATE xxxemi_person_leave_t
                      SET STATUS ='$status', BALANCE_LEAVE ='$updated_balance_leave'
        WHERE leave_id = '$id' ");

        echo "";

     }

      else
    {
     $status = $_POST['USTATUS'];

   mysqli_query($con,"UPDATE xxxemi_person_leave_t
                      SET STATUS ='$status'
        WHERE leave_id = '$id' ");

        echo "";

     }
  }

    mysqli_close($con);
?>
/**************PHP CODE *******/
   <form method="post">
             <input type="hidden" name="id" value=<?php echo $_GET['leave_id'];?>>

             <input type="hidden" name="UBALANCE_LEAVE" value="<?php echo $updated_balance_leave;?>">

              <input type="checkbox"  name="USTATUS" value="ACCEPTED" />

              <input type="checkbox" name="USTATUS" value="REJECTED" />

              <input type="submit" name="save" value="Update">
            </form>
/************* HTML CODE**********/```

答:
It seems that ,you are using $statu = $res['STATUS']; // STATUS
$statu for STATUS, but in if condition you are checking for $status

Change This

```<code>if ($status=='ACCEPTED')
</code>```

To

```<code> if($_POST['USTATUS']=='ACCEPTED')
</code>```

AND  type="checkbox" TO  type="radio"

Body:
It seems that ,you are using $statu = $res['STATUS']; // STATUS
$statu for STATUS, but in if condition you are checking for $status

Change This

if ($status=='ACCEPTED')

To

 if($_POST['USTATUS']=='ACCEPTED')

AND  type="checkbox" TO  type="radio"


问:
Assert that a method was called in a Python unit test
Suppose I have the following code in a Python unit test:

```<code>aw = aps.Request("nv1")
aw2 = aps.Request("nv2", aw)
</code>```

Is there an easy way to assert that a particular method (in my case aw.Clear()) was called during the second line of the test? e.g. is there something like this:

```<code>#pseudocode:
assertMethodIsCalled(aw.Clear, lambda: aps.Request("nv2", aw))
</code>```

答:
I use Mock (which is now unittest.mock on py3.3+) for this:

```<code>from mock import patch
from PyQt4 import Qt

@patch.object(Qt.QMessageBox, 'aboutQt')
def testShowAboutQt(self, mock):
    self.win.actionAboutQt.trigger()
    self.assertTrue(mock.called)
</code>```

For your case, it could look like this:

```<code>import mock
from mock import patch

def testClearWasCalled(self):
   aw = aps.Request("nv1")
   with patch.object(aw, 'Clear') as mock:
       aw2 = aps.Request("nv2", aw)

   mock.assert_called_with(42) # or mock.assert_called_once_with(42)
</code>```

Mock supports quite a few useful features, including ways to patch an object or module, as well as checking that the right thing was called, etc etc.

Caveat emptor! (Buyer beware!)

If you mistype assert_called_with (to assert_called_once or assert_called_wiht) your test may still run, as Mock will think this is a mocked function and happily go along, unless you use autospec=true. For more info read assert_called_once: Threat or Menace.

Body:
Suppose I have the following code in a Python unit test:

aw = aps.Request("nv1")
aw2 = aps.Request("nv2", aw)

Is there an easy way to assert that a particular method (in my case aw.Clear()) was called during the second line of the test? e.g. is there something like this:

#pseudocode:
assertMethodIsCalled(aw.Clear, lambda: aps.Request("nv2", aw))

Body:
I use Mock (which is now unittest.mock on py3.3+) for this:

from mock import patch
from PyQt4 import Qt

@patch.object(Qt.QMessageBox, 'aboutQt')
def testShowAboutQt(self, mock):
    self.win.actionAboutQt.trigger()
    self.assertTrue(mock.called)

For your case, it could look like this:

import mock
from mock import patch

def testClearWasCalled(self):
   aw = aps.Request("nv1")
   with patch.object(aw, 'Clear') as mock:
       aw2 = aps.Request("nv2", aw)

   mock.assert_called_with(42) # or mock.assert_called_once_with(42)

Mock supports quite a few useful features, including ways to patch an object or module, as well as checking that the right thing was called, etc etc.

Caveat emptor! (Buyer beware!)

If you mistype assert_called_with (to assert_called_once or assert_called_wiht) your test may still run, as Mock will think this is a mocked function and happily go along, unless you use autospec=true. For more info read assert_called_once: Threat or Menace.


问:
Why does adding a semicolon make this code work?
```<code>process.on('exit', function () {
    console.log("Exiting normally")
})

process.on('uncaughtException', function (err) {
    console.log("Caught - " + err)
})

[1,2,3,4,5].forEach(function(element) {
    console.log("Loop " + element)
})
</code>```

This breaks with:

Caught - TypeError: Cannot read property 'forEach' of undefined

Exiting normally

Whereas when I add a semi-colon, it works:

```<code>process.on('exit', function () {
    console.log("Exiting normally")
})

process.on('uncaughtException', function (err) {
    console.log("Caught - " + err)
}); // Added semi colon here

[1,2,3,4,5].forEach(function(element) {
    console.log("Loop " + element)
})
</code>```

Does this mean that I should be using semi-colons after every statement just to be safe?

答:
Suppose you have a function returnArray() that returns, you guessed it, an array.

lets say you make this call:

```<code>#do stuff
returnArray();
[n].blah
#do other stuff
#this returns an array. say [1,2,3,4,5];
#and in the next line it does [n].blah
</code>```

now lets say you make the same call without the semicolon

```<code>#do stuff
returnArray()
[n].blah
#do stuff
#this effectively does [1,2,3,4,5][n]
#which is the nth index element of the returned array.
</code>```

this is similar to getting the n'th index of the returned array, which is typically not what you were trying to do.

Body:
process.on('exit', function () {
    console.log("Exiting normally")
})

process.on('uncaughtException', function (err) {
    console.log("Caught - " + err)
})

[1,2,3,4,5].forEach(function(element) {
    console.log("Loop " + element)
})

This breaks with:

Caught - TypeError: Cannot read property 'forEach' of undefined

Exiting normally

Whereas when I add a semi-colon, it works:

process.on('exit', function () {
    console.log("Exiting normally")
})

process.on('uncaughtException', function (err) {
    console.log("Caught - " + err)
}); // Added semi colon here

[1,2,3,4,5].forEach(function(element) {
    console.log("Loop " + element)
})

Does this mean that I should be using semi-colons after every statement just to be safe?

Body:
Suppose you have a function returnArray() that returns, you guessed it, an array.

lets say you make this call:

#do stuff
returnArray();
[n].blah
#do other stuff
#this returns an array. say [1,2,3,4,5];
#and in the next line it does [n].blah

now lets say you make the same call without the semicolon

#do stuff
returnArray()
[n].blah
#do stuff
#this effectively does [1,2,3,4,5][n]
#which is the nth index element of the returned array.

this is similar to getting the n'th index of the returned array, which is typically not what you were trying to do.


问:
how to change WordPress URL on all pages?
how to change WordPress URL on all pages? suppose we have a xyz.com. Now I want something like xyz.com/test when customer visiting to xyz.com. and for all newly created pages must be something like xyz.com/test/Newpage.</p>

答:
If you want to change the Wordpress URL for all pages then you can follow below step,

Login to WordPress

Open the existing page or create a new page

Enter a Title if necessary

Save the page, this will automatically create a URL

Look directly under the title field, you will see Permalink: followed    by the URL

Click the Edit button behind the link

Type in the new URL and click OK

Save the page or post


问:
Access an item of the loop out of the loop
So i have a couple of item that iterate through from database using Jquery and for each of them I output a button to select that specific item and when I click on that row's button I want to POST the details to the controller in MVC.

```<code>$.each(data, function (i, val) {
    var item = $('<div></div>');
    item.append('<h2><a>' +val.Name+ '</a></h2>');
    item.append('<a id="button">SELECT</a>');
    tab.append(item);
});
</code>```

And I have this function for the button:

```<code>$('#myId').on('click', 'a#button', function () {
    alert('Name'+val.Name+'');
    var item = { Name: val.Name };
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: "{item:" + JSON.stringify(item) + "}",
        url: "/Person/GetData"
    });
});
</code>```

If I add the function inside the loop it will iterate as many times as there are items in there. So how can I deal with this in order to send post the name after I press SELECT button?

答:
Use DOM traversal method to get the desired element to extract text to be passed to $.ajax()

As Identifiers in HTML must be unique use CSS class selector to target them

```<code>$.each(data, function (i, val) {
    var item = $('<div></div>');
    item.append('<h2><a>' + val.Name + '</a></h2>');
    item.append('<a class="button">SELECT</a>');
    tab.append(item);
});
</code>```

In the event handler, use .prev() to target the sibling
 element

```<code>$('#myId').on('click', 'a.button', function () {
    var item = {
        Name: $(this).prev('h2').find('a').text()
    };
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: {
            item: item
        },
        url: '@Url.Action("GetData", "Person")' //Note: this will not work in separate JS file
    });
});
</code>```

Body:
So i have a couple of item that iterate through from database using Jquery and for each of them I output a button to select that specific item and when I click on that row's button I want to POST the details to the controller in MVC.

$.each(data, function (i, val) {
    var item = $('

');
    item.append('
' +val.Name+ '
');
    item.append('SELECT');
    tab.append(item);
});

And I have this function for the button:

$('#myId').on('click', 'a#button', function () {
    alert('Name'+val.Name+'');
    var item = { Name: val.Name };
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: "{item:" + JSON.stringify(item) + "}",
        url: "/Person/GetData"
    });
});

If I add the function inside the loop it will iterate as many times as there are items in there. So how can I deal with this in order to send post the name after I press SELECT button?

Body:
Use DOM traversal method to get the desired element to extract text to be passed to $.ajax()

As Identifiers in HTML must be unique use CSS class selector to target them

$.each(data, function (i, val) {
    var item = $('<div></div>');
    item.append('<h2><a>' + val.Name + '</a></h2>');
    item.append('<a class="button">SELECT</a>');
    tab.append(item);
});

In the event handler, use .prev() to target the sibling <H2> element

$('#myId').on('click', 'a.button', function () {
    var item = {
        Name: $(this).prev('h2').find('a').text()
    };
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: {
            item: item
        },
        url: '@Url.Action("GetData", "Person")' //Note: this will not work in separate JS file
    });
});


问:
test for the file related function in python
I am rather new to software testing. I wonder how to write a unit test for file related functions in python. e.g., if I have a file copy function as follows. </p>

```<code>def copy_file (self):
    if not os.path.isdir(dest_path):
        os.makedirs(dest_path)
    try:
        shutil.copy2(src_path, dest_path)
    except IOError as e:
        print e
</code>```

<p>What should I do about testing above function? what should I assert (directory, file content, exceptions)? </p>

答: I think, you can get some clue from test_shutil itself and see how it is testing the copy functionality. Namely it is moving files and testing if it exists using another module.  The difference in behavior of standard shutil.copy to your wrapper is in dealing with destination if it not already exists. In shutil.copy2, if the destination not already exists, then a file is created which is move from the source, in your case, it is not file, but a destination directory is created and you move your source into that. So write tests there destination does not exists and ensure that after your wrapper runs, the destination is still a directory and and it contains the file that shutil moved. </p>

Body:
I am rather new to software testing. I wonder how to write a unit test for file related functions in python. e.g., if I have a file copy function as follows.

def copy_file (self):
    if not os.path.isdir(dest_path):
        os.makedirs(dest_path)
    try:
        shutil.copy2(src_path, dest_path)
    except IOError as e:
        print e

What should I do about testing above function? what should I assert (directory, file content, exceptions)?


答:
Move the click to the bottom of the page outside any loop,

change the id to a class item.append('SELECT'); for your click event to select the proper value

```<code>$('#myId').on('click', 'a.button', function () {
    var val = $(this).prev('h2 a').text();//get the val.Name value
    var item = { Name: val};//create a object
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: item,//jquery will take care of the encoding
        url: "/Person/GetData"
    });
});
</code>```

Title: Access an item of the loop out of the loop

Body:
Move the click to the bottom of the page outside any loop,

change the id to a class item.append('<a class="button">SELECT</a>'); for your click event to select the proper value

$('#myId').on('click', 'a.button', function () {
    var val = $(this).prev('h2 a').text();//get the val.Name value
    var item = { Name: val};//create a object
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: item,//jquery will take care of the encoding
        url: "/Person/GetData"
    });
});


问:
How to print leading spaces before char array in C?
```<code>#include <stdio.h>
int main() {

char a[30];
char b[30];
scanf("%[^\n]s",a);
scanf(" %[^\n]s",b);
printf("%s \n",a);
printf("%s",b);
return 0;
}
</code>```

Input :

```<code>    hai
        hello
</code>```

Output :

```<code>    hai
hello
</code>```

But I am expecting

```<code>    hai
        hello
</code>```

How to print leading spaces before hello?

答:
You may try fgets:

```<code>#include <stdio.h>
int main() {
  char a[30];
  char b[30];
  fgets(a, 30, stdin);
  fgets(b, 30, stdin);
  printf("%s \n",a);
  printf("%s",b);
  return 0;
}
</code>```

Body:
#include <stdio.h>
int main() {

char a[30];
char b[30];
scanf("%[^\n]s",a);
scanf(" %[^\n]s",b);
printf("%s \n",a);
printf("%s",b);
return 0;
}

Input :

    hai
        hello

Output :

    hai
hello

But I am expecting

    hai
        hello

How to print leading spaces before hello?

Body:
You may try fgets:

#include <stdio.h>
int main() {
  char a[30];
  char b[30];
  fgets(a, 30, stdin);
  fgets(b, 30, stdin);
  printf("%s \n",a);
  printf("%s",b);
  return 0;
}


问:
Interleaving tf.data.Datasets
I'm trying to use tf.data.Dataset to interleave two datasets but having problems doing so. Given this simple example:

```<code>ds0 = tf.data.Dataset()
ds0 = ds0.range(0, 10, 2)
ds1 = tf.data.Dataset()
ds1 = ds1.range(1, 10, 2)
dataset = ...
iter = dataset.make_one_shot_iterator()
val = iter.get_next()
</code>```

What is ... to produce an output like 0, 1, 2, 3...9?

It would seem like dataset.interleave() would be relevant but I haven't been able to formulate the statement in a way that doesn't generate an error.

答:
MattScarpino is on the right track in his comment. You can use Dataset.zip() along with Dataset.flat_map() to flatten a multi-element dataset:

```<code>ds0 = tf.data.Dataset.range(0, 10, 2)
ds1 = tf.data.Dataset.range(1, 10, 2)

# Zip combines an element from each input into a single element, and flat_map
# enables you to map the combined element into two elements, then flattens the
# result.
dataset = tf.data.Dataset.zip((ds0, ds1)).flat_map(
    lambda x0, x1: tf.data.Dataset.from_tensors(x0).concatenate(
        tf.data.Dataset.from_tensors(x1)))

iter = dataset.make_one_shot_iterator()
val = iter.get_next()
</code>```

Having said this, your intuition about using Dataset.interleave() is pretty sensible. We're investigating ways that you can do this more easily.

PS. As an alternative, you can use Dataset.interleave() to solve the problem if you change how ds0 and ds1 are defined:

```<code>dataset = tf.data.Dataset.range(2).interleave(
    lambda x: tf.data.Dataset.range(x, 10, 2), cycle_length=2, block_length=1)
</code>```

Title: Interleaving tf.data.Datasets

Body:
I'm trying to use tf.data.Dataset to interleave two datasets but having problems doing so. Given this simple example:

ds0 = tf.data.Dataset()
ds0 = ds0.range(0, 10, 2)
ds1 = tf.data.Dataset()
ds1 = ds1.range(1, 10, 2)
dataset = ...
iter = dataset.make_one_shot_iterator()
val = iter.get_next()

What is ... to produce an output like 0, 1, 2, 3...9?

It would seem like dataset.interleave() would be relevant but I haven't been able to formulate the statement in a way that doesn't generate an error.

Body:
MattScarpino is on the right track in his comment. You can use Dataset.zip() along with Dataset.flat_map() to flatten a multi-element dataset:

ds0 = tf.data.Dataset.range(0, 10, 2)
ds1 = tf.data.Dataset.range(1, 10, 2)

# Zip combines an element from each input into a single element, and flat_map
# enables you to map the combined element into two elements, then flattens the
# result.
dataset = tf.data.Dataset.zip((ds0, ds1)).flat_map(
    lambda x0, x1: tf.data.Dataset.from_tensors(x0).concatenate(
        tf.data.Dataset.from_tensors(x1)))

iter = dataset.make_one_shot_iterator()
val = iter.get_next()

Having said this, your intuition about using Dataset.interleave() is pretty sensible. We're investigating ways that you can do this more easily.

PS. As an alternative, you can use Dataset.interleave() to solve the problem if you change how ds0 and ds1 are defined:

dataset = tf.data.Dataset.range(2).interleave(
    lambda x: tf.data.Dataset.range(x, 10, 2), cycle_length=2, block_length=1)


答:
The print statement needs to be after the try/except clause:

```<code>def alt_ele():
    mylist=list(input("Enter the elements: "))
    newlist=[int(i) for i in mylist]
    final_list=[]
    try:
        for x in range(len(newlist)):
            final_list.append(newlist.pop(0))
            final_list.append(newlist.pop())
    except IndexError:
        pass
    print(final_list)
</code>```

With this, we get the desired output.

I don't think this is the best solution, so here's one way of avoiding the try/except clause:

```<code>def alt_ele():
    mylist=list(input("Enter the elements: "))
    newlist=[int(i) for i in mylist]
    final_list=[]
    switch = False
    while newlist:
        final_list.append(newlist.pop(-switch))
        switch = not switch
    print(final_list)
</code>```

Title: I have a list of numbers where the 1st digit is appended to a new list, then last, then 2nd, then 2nd last and so on

Body:
Following is my code:

def alt_ele():
    mylist=list(input("Enter the elements: "))
    newlist=[int(i) for i in mylist]
    final_list=[]
    try:
        for x in range(len(newlist)):
            final_list.append(newlist.pop(0))
            final_list.append(newlist.pop())
            print(final_list)
    except IndexError:
        pass

Now the Input I am giving is:

I/N: Enter the elements: 12345

My desired output is [1,5,2,4,3]

But the output I am actually getting is:

[1,5]
[1,5,2,4]

Can anyone please help me figure out where am I going wrong? I tried but, I cannot figure it out by myself
Thanks in advance.

Body:
The print statement needs to be after the try/except clause:

def alt_ele():
    mylist=list(input("Enter the elements: "))
    newlist=[int(i) for i in mylist]
    final_list=[]
    try:
        for x in range(len(newlist)):
            final_list.append(newlist.pop(0))
            final_list.append(newlist.pop())
    except IndexError:
        pass
    print(final_list)

With this, we get the desired output.

I don't think this is the best solution, so here's one way of avoiding the try/except clause:

def alt_ele():
    mylist=list(input("Enter the elements: "))
    newlist=[int(i) for i in mylist]
    final_list=[]
    switch = False
    while newlist:
        final_list.append(newlist.pop(-switch))
        switch = not switch
    print(final_list)


问:
img class="rounded-circle" is not creating a rounded circle in asp.net
I am using bootstrap in asp.net mcv application. I want the images to be rounded. therefore used the "img class="rounded-circle". The code is below.

index.html

```<code>@{
ViewBag.Title = "Home Page";
 }

<h1 class="my-4">
  About Us
  <small>It's Nice to Meet You!</small>
</h1>

<div class="row">
  <div class="col-lg-12">
    <h2 class="my-4 text-center">Our Services</h2>
  </div>

  <div class="col-lg-4 col-sm-6 text-center mb-4">
    <a href="Application/Search">
        <img class="rounded-circle img-fluid d-block mx-auto" src="~/Images/search.png" alt="">
    </a>
    <h3>Search App</h3>
    <p>What does this team member to? Keep it short! This is also a great spot for social links!</p>
   </div>

   <div class="col-lg-4 col-sm-6 text-center mb-4">
    <a href="Application/TTS">
        <img class="rounded-circle img-fluid d-block mx-auto" src="~/Images/text-to-speech.png" alt="">
    </a>
        <h3>Text-to-Speech</h3>
        <p>What does this team member to? Keep it short! This is also a great spot for social links!</p>
  </div>

  <div class="col-lg-4 col-sm-6 text-center mb-4">
    <a href="Application/SpeechRecognition">
        <img class="rounded-circle img-fluid d-block mx-auto" src="~/Images/speech-recognition.jpg" alt="">
    </a>
        <h3>Speech Recognition</h3>
        <p>What does this team member to? Keep it short! This is also a great spot for social links!</p>
  </div>

  <div class="col-lg-4 col-sm-6 text-center mb-4">
    <a href="Application/VAvatar">
        <img class="rounded-circle img-fluid d-block mx-auto" src="~/Images/virtual-avatar.jpg" alt="">
    </a>
        <h3> Virtual Avatar</h3>
        <p>What does this team member to? Keep it short! This is also a great spot for social links!</p>
  </div>

  <div class="col-lg-4 col-sm-6 text-center mb-4">
    <a href="Application/VAvatar">
        <img class="rounded-circle img-fluid d-block mx-auto" src="~/Images/text-to-speech.png" alt="">
    </a>
        <h3>John Smith</h3>
        <p>What does this team member to? Keep it short! This is also a great spot for social links!</p>
  </div>

  <div class="col-lg-4 col-sm-6 text-center mb-4">
    <a href="Application/VAvatar">
        <img class="rounded-circle img-fluid d-block mx-auto" src="~/Images/text-to-speech.png" alt="">
    </a>
        <h3>John Smith</h3>
        <p>What does this team member to? Keep it short! This is also a great spot for social links!</p>
  </div>
</code>```

This is how it looks like

The above code should give a rounded image. But it is still square. Why is this?

答: For Bootstrap, you should add img-circle and not rounded-circle. See the sample here Give it a try.

Body:
I am using bootstrap in asp.net mcv application. I want the images to be rounded. therefore used the "img class="rounded-circle". The code is below.

index.html

@{
ViewBag.Title = "Home Page";
 }

  About Us
  It's Nice to Meet You!

Our Services

Search App

What does this team member to? Keep it short! This is also a great spot for social links!

Text-to-Speech

What does this team member to? Keep it short! This is also a great spot for social links!

Speech Recognition

What does this team member to? Keep it short! This is also a great spot for social links!

 Virtual Avatar

What does this team member to? Keep it short! This is also a great spot for social links!

John Smith

What does this team member to? Keep it short! This is also a great spot for social links!

John Smith

What does this team member to? Keep it short! This is also a great spot for social links!

This is how it looks like

The above code should give a rounded image. But it is still square. Why is this?


问:
Share auto-incremented primary key between two tables
Hi I want to have two tables each have an INT "id" column which will auto-increment but I don't want either "id" columns to ever share the same number. What is this called and what's the best way to do it? Sequence? Iterator? Index? Incrementor?

Motivation: we're migrating from one schema to a another and have a web-page that reads both tables and shows the (int) ID, but I can't have the same ID used for both tables.

I'm using SQL Server 9.0.3068.

Thanks!

答:
If you really need to do this with an int and you have an auto incrementing number, the way i have done this before is to change the id field auto increment function to the sequence of the other table. I am not too sure in ms sql or my sql but in pgsql that means that in the sql you would have this field

```<code> id integer NOT NULL DEFAULT nextval('table_two_seq'::regclass),
</code>```

where table_two_sequence is the sequence function for the other table. Then test it out by inserting some data. I am really sorry if this wont work in ms sql i try to steer clear of it tbh. Failing that the GUID is the best way as has been mentioned by others. Or when inserting in the code that you use you could put an algorithm in that but it could get messy.

Alternatively, think about having the data in one table as this would be a way around it. if you need to you could have a view simulating two tables. Just a thought.

Hope i have helped

Body:
If you really need to do this with an int and you have an auto incrementing number, the way i have done this before is to change the id field auto increment function to the sequence of the other table. I am not too sure in ms sql or my sql but in pgsql that means that in the sql you would have this field

 id integer NOT NULL DEFAULT nextval('table_two_seq'::regclass),

where table_two_sequence is the sequence function for the other table. Then test it out by inserting some data. I am really sorry if this wont work in ms sql i try to steer clear of it tbh. Failing that the GUID is the best way as has been mentioned by others. Or when inserting in the code that you use you could put an algorithm in that but it could get messy.

Alternatively, think about having the data in one table as this would be a way around it. if you need to you could have a view simulating two tables. Just a thought.

Hope i have helped


问:
Preventing Page Breaks in a Table When Printing
I have a page that I'm trying to set up for printing. This page contains a large number of individual tables. The tables are of varying size but, in general, I can fit 2.5 to 3 tables on each page. I'd like to be able to prevent the tables from being broken by a page break. Any idea how I can accomplish that?

I tried this:

```<code>.reportTable {
    page-break-inside: avoid;
}
</code>```

Unfortunately, page-break-inside only seems to be supported in Opera (according to W3Schools - I verified that this doesn't work in Firefox 4.0.1).

I can do this to force a page break before after every single table:

```<code>.reportTable {
    page-break-after: always;
}
</code>```

This works to insert the page breaks and seems to be supported in all major browsers, but it leaves me with tons of wasted space on the printed documents (roughly half of each page is blank). I really only want a page break if the entire next table won't fit on this page.

I know that I have users utilizing Internet Explorer, Firefox, and Safari so I'd really like to support those as much as possible. Finding something that would also work in Chrome and Opera would be a very nice bonus.

Any ideas?

答:
to fix this just make
 #table{page-break-after:auto;}</p>

Body:
I have a page that I'm trying to set up for printing. This page contains a large number of individual tables. The tables are of varying size but, in general, I can fit 2.5 to 3 tables on each page. I'd like to be able to prevent the tables from being broken by a page break. Any idea how I can accomplish that?

I tried this:

.reportTable {
    page-break-inside: avoid;
}

Unfortunately, page-break-inside only seems to be supported in Opera (according to W3Schools - I verified that this doesn't work in Firefox 4.0.1).

I can do this to force a page break before after every single table:

.reportTable {
    page-break-after: always;
}

This works to insert the page breaks and seems to be supported in all major browsers, but it leaves me with tons of wasted space on the printed documents (roughly half of each page is blank). I really only want a page break if the entire next table won't fit on this page.

I know that I have users utilizing Internet Explorer, Firefox, and Safari so I'd really like to support those as much as possible. Finding something that would also work in Chrome and Opera would be a very nice bonus.

Any ideas?


问:
Show TableView Section Headers and Rows ios swift
I have an array with objects and i want to show Group Name in headers , but in the array some groups have same name, now i want to show single header for same group and create rows.
```<code>[
       {
         "primary_dark_color": "#0d6d9f",
         "Groups": "A",
         "primary_color": "#03a9f4"
       },
       {
         "primary_dark_color": "#0d6d9f",
         "Groups": "B",
         "primary_color": "#03a9f4"
        },
        {
         "primary_dark_color": "#0d6d9f",
         "Groups": "A",
         "primary_color": "#03a9f4"
        },
        {
         "primary_dark_color": "#0d6d9f",
         "Groups": "B",
         "primary_color": "#03a9f4"
       }]
</code>```

答:
To solve your problem you need to use predicate. Using predicate you can make group(array) of dictionary which contains same Groups

Try bellow code.

```<code>let array = [
    [
        "primary_dark_color": "#0d6d9f",
        "Groups": "A",
        "primary_color": "#03a9f4"
        ],
    [
        "primary_dark_color": "#0d6d9f",
        "Groups": "B",
        "primary_color": "#03a9f4"
        ],
    [
        "primary_dark_color": "#0d6d9f",
        "Groups": "A",
        "primary_color": "#03a9f4"
        ],
    [
        "primary_dark_color": "#0d6d9f",
        "Groups": "B",
        "primary_color": "#03a9f4"
        ]]

    var arrGroups = [String]()
    for dict in array {

        if !arrGroups.contains(dict["Groups"]!) {

            arrGroups.append(dict["Groups"]!)
        }
    }
    var arrTmp = [Array<Dictionary<String, String>>]()
    for i in 0..<arrGroups.count {

        var tmp:Array = array
        tmp = tmp.filter { ($0["Groups"]!).range(of: arrGroups[i], options: [.diacriticInsensitive, .caseInsensitive]) != nil }
        arrTmp.append(tmp)
    }
    print(arrTmp)
</code>```

Each array in arrTmp will have dictionary that contains same Groups

So your numberOfSections = arrTmp.count

And numberOfRowsInSection = arrTmp[section].count

arrTmp will have

```<code>[[["primary_color": "#03a9f4", "primary_dark_color": "#0d6d9f", "Groups": "A"], ["primary_color": "#03a9f4", "primary_dark_color": "#0d6d9f", "Groups": "A"]], [["primary_color": "#03a9f4", "primary_dark_color": "#0d6d9f", "Groups": "B"], ["primary_color": "#03a9f4", "primary_dark_color": "#0d6d9f", "Groups": "B"]]]
</code>```

Body:
I have an array with objects and i want to show Group Name in headers , but in the array some groups have same name, now i want to show single header for same group and create rows.

[
       {
         "primary_dark_color": "#0d6d9f",
         "Groups": "A",
         "primary_color": "#03a9f4"
       },
       {
         "primary_dark_color": "#0d6d9f",
         "Groups": "B",
         "primary_color": "#03a9f4"
        },
        {
         "primary_dark_color": "#0d6d9f",
         "Groups": "A",
         "primary_color": "#03a9f4"
        },
        {
         "primary_dark_color": "#0d6d9f",
         "Groups": "B",
         "primary_color": "#03a9f4"
       }]

Body:
To solve your problem you need to use predicate. Using predicate you can make group(array) of dictionary which contains same Groups

Try bellow code.

let array = [
    [
        "primary_dark_color": "#0d6d9f",
        "Groups": "A",
        "primary_color": "#03a9f4"
        ],
    [
        "primary_dark_color": "#0d6d9f",
        "Groups": "B",
        "primary_color": "#03a9f4"
        ],
    [
        "primary_dark_color": "#0d6d9f",
        "Groups": "A",
        "primary_color": "#03a9f4"
        ],
    [
        "primary_dark_color": "#0d6d9f",
        "Groups": "B",
        "primary_color": "#03a9f4"
        ]]

    var arrGroups = [String]()
    for dict in array {

        if !arrGroups.contains(dict["Groups"]!) {

            arrGroups.append(dict["Groups"]!)
        }
    }
    var arrTmp = [Array<Dictionary<String, String>>]()
    for i in 0..<arrGroups.count {

        var tmp:Array = array
        tmp = tmp.filter { ($0["Groups"]!).range(of: arrGroups[i], options: [.diacriticInsensitive, .caseInsensitive]) != nil }
        arrTmp.append(tmp)
    }
    print(arrTmp)

Each array in arrTmp will have dictionary that contains same Groups

So your numberOfSections = arrTmp.count

And numberOfRowsInSection = arrTmp[section].count

arrTmp will have

[[["primary_color": "#03a9f4", "primary_dark_color": "#0d6d9f", "Groups": "A"], ["primary_color": "#03a9f4", "primary_dark_color": "#0d6d9f", "Groups": "A"]], [["primary_color": "#03a9f4", "primary_dark_color": "#0d6d9f", "Groups": "B"], ["primary_color": "#03a9f4", "primary_dark_color": "#0d6d9f", "Groups": "B"]]]


答:
when you dont use semicolon javascript consider it in following way

```<code>process.on('',function (err) {..})[1,2,3,4,5].forEach(function(element) {
    console.log("Loop " + element)
})
</code>```

obliviously process.on() don't have any property like [1,2,3,4,5] which is why it was undefined

Title: Why does adding a semicolon make this code work?

Body:
process.on('exit', function () {
    console.log("Exiting normally")
})

process.on('uncaughtException', function (err) {
    console.log("Caught - " + err)
})

[1,2,3,4,5].forEach(function(element) {
    console.log("Loop " + element)
})

This breaks with:

Caught - TypeError: Cannot read property 'forEach' of undefined

Exiting normally

Whereas when I add a semi-colon, it works:

process.on('exit', function () {
    console.log("Exiting normally")
})

process.on('uncaughtException', function (err) {
    console.log("Caught - " + err)
}); // Added semi colon here

[1,2,3,4,5].forEach(function(element) {
    console.log("Loop " + element)
})

Does this mean that I should be using semi-colons after every statement just to be safe?

Body:
when you dont use semicolon javascript consider it in following way

process.on('',function (err) {..})[1,2,3,4,5].forEach(function(element) {
    console.log("Loop " + element)
})

obliviously process.on() don't have any property like [1,2,3,4,5] which is why it was undefined


问:
Program that reads multiple lines from a file and converts to a single line string
I'm trying to create a C program that takes a file path as a command line argument. My program then reads that file line by line, removing the endline character and adding it to a string so at the end the string is the input file but on only one line.

```<code>#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main(int argc, char **argv){

  FILE *input = fopen(argv[1], "r");
  char *line = NULL;
  char buffer[100];
  char temp[200];

  line = fgets(buffer, 100 *sizeof(char), input);

  while(line != NULL){
    line[strlen(line)-1] = '\0';
    strcat(temp, line);
    line = fgets(buffer, 100 *sizeof(char), input);
  }

  printf("%s\n", temp);
  fclose(input);
}
</code>```

I input a file with data:

```<code>This is Line 1
line 2
line 3
and this is line 4
</code>```

and expect the string to be
This is Line 1line 2line 3and this is line 4

but instead it is
and this is line 1

Any help is appreciated!

答:
You risk Undefined Behavior for (1) failing to validate input is actually a valid file stream opened for reading, and (2) failing to track the maximum number of characters stored in temp allowing more characters to be stored than you have room for (you would invoke undefined behavior by failing to check that the argument count is greater than 1, but as used in fopen the sentinel NULL at the end of the argument vector (argv) simply causes fopen to fail -- but since you fail to check that...).

Before looking at possible fixes, let's look at some general coding points. Don't use magic numbers in your code, e.g. 100, 200,

```<code>/* if use need constants, #define them or use an enum */
enum { BUFSZ = 100, TMPSZ = 200 };

int main (int argc, char **argv){

    char buffer[BUFSZ] = "",    /* read buffer */
        temp[TMPSZ] = "";       /* buffer for combined lines */
</code>```

By defining constants at the beginning of each source file, if you need to adjust them over time, you don't have to go picking through each declaration, loop variable, test clause, etc.. to make sure you have make all required changes.

Before using command line arguments, validate your argument count (argc):

```<code>    if (argc < 2 ) {   /* validate at least 1 argument given */
        fprintf (stderr, "error: insufficient input, usage: %s file\n", argv[0]);
        return 1;
    }
</code>```

Before reading from any file you open:

```<code>    if (!input) {   /* validate file open for reading */
        fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
        return 1;
    }
</code>```

When reading with fgets, unless you are discarding the first line, there is no need for a separate fgets before entering your while loop to read the file,

```<code>    while (fgets(buffer, BUFSZ, input)) {   /* read each line */
        ...
    }
</code>```

Validate whether the last character read in buffer is the '\n' characters:

```<code>        size_t len = strlen (buffer);       /* get length */
        if (len && buffer[len - 1] == '\n') /* check if last is '\n' */
            buffer[--len] = 0;              /* overwrite with nul-char */
</code>```

Now to the meat and potatoes of preventing Undefined Behavior. You only have TMPSZ characters available, and if you plan to use temp as a string, you must make sure you leave room for the nul-terminating character '\0' as the final character. ('\0' is equivalent to 0 (zero)). So check the length, the number of characters you have stored so far, and write at most one less than the number of characters remaining in temp,

```<code>        if (TMPSZ <= nchr + len + 1) {      /* room to fit in buffer? */
            strncat (temp, buffer, TMPSZ - nchr - 1); /* only what fits */
            nchr = TMPSZ - 1;          /* nchr is max (+1 for nul-char) */
            temp[nchr] = 0;            /* affirmatively nul-terminate */
            break;                          /* bail - all full */
        }
</code>```

If you didn't reach the end of temp in the test above, then buffer will fit in temp, so just copy it and update the total character count:

```<code>        strcat (temp, buffer);              /* copy buffer to temp */
        nchr += len;                        /* update nchr */
    }
</code>```

That's it. Putting it altogether, you can read from the file given as the first argument (or from stdin by default if no argument is given) and combine all lines into a single line up to TMPSZ - 1 characters, e.g.

```<code>#include <stdio.h>
#include <string.h>

/* if use need constants, #define them or use an enum */
enum { BUFSZ = 100, TMPSZ = 200 };

int main (int argc, char **argv){

    char buffer[BUFSZ] = "",    /* read buffer */
        temp[TMPSZ] = "";       /* buffer for combined lines */
    size_t nchr = 0;            /* total character count */
    FILE *input = argc > 1 ? fopen (argv[1], "r") : stdin;

    if (!input) {   /* validate file open for reading */
        fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
        return 1;
    }

    while (fgets(buffer, BUFSZ, input)) {   /* read each line */
        size_t len = strlen (buffer);       /* get length */
        if (len && buffer[len - 1] == '\n') /* check if last is '\n' */
            buffer[--len] = 0;              /* overwrite with nul-char */

        if (TMPSZ <= nchr + len + 1) {      /* room to fit in buffer? */
            strncat (temp, buffer, TMPSZ - nchr - 1); /* only what fits */
            nchr = TMPSZ - 1;          /* nchr is max (+1 for nul-char) */
            temp[nchr] = 0;            /* affirmatively nul-terminate */
            break;                          /* bail - all full */
        }

        strcat (temp, buffer);              /* copy buffer to temp */
        nchr += len;                        /* update nchr */
    }
    if (input != stdin) fclose (input);     /* close file if not stdin */

    printf ("'%s'\n(%zu chars)\n", temp, nchr); /* output temp */

    return 0;
}
</code>```

Example Use/Output

```<code>$ ./bin/cmblines <dat/cmblines.txt
'This is Line 1line 2line 3and this is line 4'
(44 chars)
</code>```

Example with TMPSZ = 20

Let's perform a test. Let's set TMPSZ = 20 and verify our code properly protects against writing beyond the end of temp,

```<code>$ ./bin/cmblines <dat/cmblines.txt
'This is Line 1line '
(19 chars)
</code>```

Look things over and let me know if you have further questions.

Body:
I'm trying to create a C program that takes a file path as a command line argument. My program then reads that file line by line, removing the endline character and adding it to a string so at the end the string is the input file but on only one line.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main(int argc, char **argv){

  FILE *input = fopen(argv[1], "r");
  char *line = NULL;
  char buffer[100];
  char temp[200];

  line = fgets(buffer, 100 *sizeof(char), input);

  while(line != NULL){
    line[strlen(line)-1] = '\0';
    strcat(temp, line);
    line = fgets(buffer, 100 *sizeof(char), input);
  }

  printf("%s\n", temp);
  fclose(input);
}

I input a file with data:

This is Line 1
line 2
line 3
and this is line 4

and expect the string to be
This is Line 1line 2line 3and this is line 4

but instead it is
and this is line 1

Any help is appreciated!

Body:
You risk Undefined Behavior for (1) failing to validate input is actually a valid file stream opened for reading, and (2) failing to track the maximum number of characters stored in temp allowing more characters to be stored than you have room for (you would invoke undefined behavior by failing to check that the argument count is greater than 1, but as used in fopen the sentinel NULL at the end of the argument vector (argv) simply causes fopen to fail -- but since you fail to check that...).

Before looking at possible fixes, let's look at some general coding points. Don't use magic numbers in your code, e.g. 100, 200,

/* if use need constants, #define them or use an enum */
enum { BUFSZ = 100, TMPSZ = 200 };

int main (int argc, char **argv){

    char buffer[BUFSZ] = "",    /* read buffer */
        temp[TMPSZ] = "";       /* buffer for combined lines */

By defining constants at the beginning of each source file, if you need to adjust them over time, you don't have to go picking through each declaration, loop variable, test clause, etc.. to make sure you have make all required changes.

Before using command line arguments, validate your argument count (argc):

    if (argc < 2 ) {   /* validate at least 1 argument given */
        fprintf (stderr, "error: insufficient input, usage: %s file\n", argv[0]);
        return 1;
    }

Before reading from any file you open:

    if (!input) {   /* validate file open for reading */
        fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
        return 1;
    }

When reading with fgets, unless you are discarding the first line, there is no need for a separate fgets before entering your while loop to read the file,

    while (fgets(buffer, BUFSZ, input)) {   /* read each line */
        ...
    }

Validate whether the last character read in buffer is the '\n' characters:

        size_t len = strlen (buffer);       /* get length */
        if (len && buffer[len - 1] == '\n') /* check if last is '\n' */
            buffer[--len] = 0;              /* overwrite with nul-char */

Now to the meat and potatoes of preventing Undefined Behavior. You only have TMPSZ characters available, and if you plan to use temp as a string, you must make sure you leave room for the nul-terminating character '\0' as the final character. ('\0' is equivalent to 0 (zero)). So check the length, the number of characters you have stored so far, and write at most one less than the number of characters remaining in temp,

        if (TMPSZ <= nchr + len + 1) {      /* room to fit in buffer? */
            strncat (temp, buffer, TMPSZ - nchr - 1); /* only what fits */
            nchr = TMPSZ - 1;          /* nchr is max (+1 for nul-char) */
            temp[nchr] = 0;            /* affirmatively nul-terminate */
            break;                          /* bail - all full */
        }

If you didn't reach the end of temp in the test above, then buffer will fit in temp, so just copy it and update the total character count:

        strcat (temp, buffer);              /* copy buffer to temp */
        nchr += len;                        /* update nchr */
    }

That's it. Putting it altogether, you can read from the file given as the first argument (or from stdin by default if no argument is given) and combine all lines into a single line up to TMPSZ - 1 characters, e.g.

#include <stdio.h>
#include <string.h>

/* if use need constants, #define them or use an enum */
enum { BUFSZ = 100, TMPSZ = 200 };

int main (int argc, char **argv){

    char buffer[BUFSZ] = "",    /* read buffer */
        temp[TMPSZ] = "";       /* buffer for combined lines */
    size_t nchr = 0;            /* total character count */
    FILE *input = argc > 1 ? fopen (argv[1], "r") : stdin;

    if (!input) {   /* validate file open for reading */
        fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
        return 1;
    }

    while (fgets(buffer, BUFSZ, input)) {   /* read each line */
        size_t len = strlen (buffer);       /* get length */
        if (len && buffer[len - 1] == '\n') /* check if last is '\n' */
            buffer[--len] = 0;              /* overwrite with nul-char */

        if (TMPSZ <= nchr + len + 1) {      /* room to fit in buffer? */
            strncat (temp, buffer, TMPSZ - nchr - 1); /* only what fits */
            nchr = TMPSZ - 1;          /* nchr is max (+1 for nul-char) */
            temp[nchr] = 0;            /* affirmatively nul-terminate */
            break;                          /* bail - all full */
        }

        strcat (temp, buffer);              /* copy buffer to temp */
        nchr += len;                        /* update nchr */
    }
    if (input != stdin) fclose (input);     /* close file if not stdin */

    printf ("'%s'\n(%zu chars)\n", temp, nchr); /* output temp */

    return 0;
}

Example Use/Output

$ ./bin/cmblines <dat/cmblines.txt
'This is Line 1line 2line 3and this is line 4'
(44 chars)

Example with TMPSZ = 20

Let's perform a test. Let's set TMPSZ = 20 and verify our code properly protects against writing beyond the end of temp,

$ ./bin/cmblines <dat/cmblines.txt
'This is Line 1line '
(19 chars)

Look things over and let me know if you have further questions.


问:
How do i return date with MMDDYYYY format as a valid date value in sql server?
I am trying to validate the date field for the various combination. While trying to validate MMDDYYYY, the function does not return it as valid. also, it does not give proper input for MMDDYY, MMMDDYY, MMMDDYYYY.

```<code>SET DATEFORMAT mdy;

IF ISDATE('11202018') = 1
    PRINT 'Valida date field'
ELSE
    PRINT 'INVALID';
</code>```

The date in above example is a valid date field, still, it returns invalid. I doubt SQL server is considering the local date setting.

Can anyone share your thought?

答:
SQL Server works based on the DATEFORMAT,
Before going to check should separate the date filed by "/" or "-"

Refer the query, It will works both "MMM/DD/YYYY" and "mm/dd/yy"

```<code>IF ISDATE('11/20/2018') = 1
    PRINT 'VALID'
ELSE
    PRINT 'INVALID';
</code>```

Body:
I am trying to validate the date field for the various combination. While trying to validate MMDDYYYY, the function does not return it as valid. also, it does not give proper input for MMDDYY, MMMDDYY, MMMDDYYYY.

SET DATEFORMAT mdy;

IF ISDATE('11202018') = 1
    PRINT 'Valida date field'
ELSE
    PRINT 'INVALID';

The date in above example is a valid date field, still, it returns invalid. I doubt SQL server is considering the local date setting.

Can anyone share your thought?

Body:
SQL Server works based on the DATEFORMAT,
Before going to check should separate the date filed by "/" or "-"

Refer the query, It will works both "MMM/DD/YYYY" and "mm/dd/yy"

IF ISDATE('11/20/2018') = 1
    PRINT 'VALID'
ELSE
    PRINT 'INVALID';


问:
UINavigationBar Custom Title View not centered on iOS11
I just updated to Xcode 9 and run to an iOS11 simulator. My custom view for the navaagation bar title is shifted down.

This code was working before i updated; it was vertically centered before

```<code>companyCountryView = CompanyNameView(frame: CGRect(x: 0, y: 0, width: Utils.getScreenWidth() - 150, height: 35))
companyCountryView.companyLbl.text = ""
companyCountryView.countryLbl.text = ""
self.navigationItem.titleView = companyCountryView
</code>```

Even though I change values for y and height, no effect at all.
It seems the width value i used does not do any effect too.

答:
I have solved it! You need to override the intrinsicContentSize in your custom view class and put the size of the view there:</p>

```<code>class CustomView: UIView {
    override var intrinsicContentSize: CGSize {
        return CGSize(width: Utils.getScreenWidth() - 150.0, height: 35.0)
    }
}
</code>```

Body:
I just updated to Xcode 9 and run to an iOS11 simulator. My custom view for the navaagation bar title is shifted down.

This code was working before i updated; it was vertically centered before

companyCountryView = CompanyNameView(frame: CGRect(x: 0, y: 0, width: Utils.getScreenWidth() - 150, height: 35))
companyCountryView.companyLbl.text = ""
companyCountryView.countryLbl.text = ""
self.navigationItem.titleView = companyCountryView

Even though I change values for y and height, no effect at all.
It seems the width value i used does not do any effect too.

Body:
I have solved it! You need to override the intrinsicContentSize in your custom view class and put the size of the view there:

class CustomView: UIView {
    override var intrinsicContentSize: CGSize {
        return CGSize(width: Utils.getScreenWidth() - 150.0, height: 35.0)
    }
}