问:
Getting lots of controller calls with Xamarin Azure Pullasync
We are using xamarin forms to create an Azure backed mobile app. We are using offline data sync to allow offline data storage and processing. This is all hooked up as per the many walkthroughs on the web and all seems to be working fine.

One of our tables contains ~5000 rows which is causing us a few issues. When you do the initial sync with the app using the code;

```<code>this.listTable = client.GetSyncTable<Entities.List>();
await this.listTable.PullAsync("allLists", listTable.CreateQuery());
</code>```

the azure .NET service seems to get his thousands of times. I have debugged the services' GetAllList() method on azure - containing the code;

```<code>public IQueryable<List> GetAllList()
{
    return Query();
}
</code>```

and the breakpoint get’s hit a lot. I have checked out what Query() is returning and it looks to be returning the whole dataset (~5000 rows) as I would expect.

Does anybody know what I could be doing wrong to have it called so many times? It looks to be returning the whole dataset for maybe each row in the dataset - causing the sync to be very slow.

I stepped through the controller process when debugging and it doesn’t just look to be calling the GetAllList() method loads of times, it initialises the controller then calls the GetAllList method over and over again.

I’m sure I’ve set something up incorrectly and it’s a simple mistake as I can’t believe this is by design, but can’t for the life of me spot what I have done wrong :(

Any help would be very welcome!

Thanks,
Al.

答:
Turns out the pagesize for the requests is 50 by default. This results in loads of calls to the service to the number of rows I was calling taking loads of time.

I can up the MaxPageSize on the client and the PageSize on the service and it is significantly quicker.

Came across the suggestions here for reference - https://social.msdn.microsoft.com/Forums/sqlserver/en-US/ff5b6ba7-76c7-42fe-847d-9898256e3249/problem-syncing-large-table?forum=azuremobile

There are, of course things that need to be taken into account when upping this value - but at least it explains what was happening.

Body:
We are using xamarin forms to create an Azure backed mobile app. We are using offline data sync to allow offline data storage and processing. This is all hooked up as per the many walkthroughs on the web and all seems to be working fine.

One of our tables contains ~5000 rows which is causing us a few issues. When you do the initial sync with the app using the code;

this.listTable = client.GetSyncTable<Entities.List>();
await this.listTable.PullAsync("allLists", listTable.CreateQuery());

the azure .NET service seems to get his thousands of times. I have debugged the services' GetAllList() method on azure - containing the code;

public IQueryable<List> GetAllList()
{
    return Query();
}

and the breakpoint get’s hit a lot. I have checked out what Query() is returning and it looks to be returning the whole dataset (~5000 rows) as I would expect.

Does anybody know what I could be doing wrong to have it called so many times? It looks to be returning the whole dataset for maybe each row in the dataset - causing the sync to be very slow.

I stepped through the controller process when debugging and it doesn’t just look to be calling the GetAllList() method loads of times, it initialises the controller then calls the GetAllList method over and over again.

I’m sure I’ve set something up incorrectly and it’s a simple mistake as I can’t believe this is by design, but can’t for the life of me spot what I have done wrong :(

Any help would be very welcome!

Thanks,
Al.


来源: stackexchange

问:
selecting data in big table for which certain IDs don't exist in same columns. Speed up query
I'm trying to select data in a table for companies and dates that don't exist for a different type/id of data.

Put another way, I want company_id, dates_id, daily_val where wh_calc_id = 344 if the same company_id/dates_id combination doesn't exist where wh_calc_id = 368.

I'm loosely following this example:
Select rows which are not present in other table

These are my two attempts at it:

attempt 1:

```<code>SELECT distinct on (company_id, dates_id) company_id, dates_id, daily_val
FROM   daily_data d1
WHERE  NOT EXISTS (
                       SELECT 1
                       FROM   daily_data d2
                       WHERE  d1.company_id = d2.company_id
                              and d1.dates_id = d2.dates_id
                              and d1.wh_calc_id = 368
                              and d2.wh_calc_id = 368
                   )
    and d1.wh_calc_id = 344
</code>```

The problem:
It's super slow: 27 minutes

attempt 2: [removed]

All in one (giant) table:
company_id int (indexed),
dates_id int (indexed),
wh_calc_id int (indexed),
daily_val numeric

I'm open to adding an index that would help speed things up, but what index?

Postgres 10

<s>PS - I've had to kill both queries before they completed, so I don't really know if they are written correctly. Hopefully my description helps.</s>

答:
I would do it with a left join this way:

SELECT distinct on (company_id, dates_id) company_id, dates_id, daily_val FROM daily_data d1 LEFT JOIN daily_data d2 ON d1.company_id = d2.company_id and d1.dates_id = d2.dates_id and d1.wh_calc_id = 368 and d2.wh_calc_id = 368 WHERE d1.wh_calc_id = 344 AND d2.company_id IS NULL;

and create the index over the columns to use:

Create index on table daily_data ( company_id, dates_id, wh_calc_id);

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to select data in a table for companies and dates that don't exist for a different type/id of data.

Put another way, I want company_id, dates_id, daily_val where wh_calc_id = 344 if the same company_id/dates_id combination doesn't exist where wh_calc_id = 368.

I'm loosely following this example:
Select rows which are not present in other table

These are my two attempts at it:

attempt 1:

SELECT distinct on (company_id, dates_id) company_id, dates_id, daily_val
FROM   daily_data d1
WHERE  NOT EXISTS (
                       SELECT 1
                       FROM   daily_data d2
                       WHERE  d1.company_id = d2.company_id
                              and d1.dates_id = d2.dates_id
                              and d1.wh_calc_id = 368
                              and d2.wh_calc_id = 368
                   )
    and d1.wh_calc_id = 344

The problem:
It's super slow: 27 minutes

attempt 2: [removed]

All in one (giant) table:
company_id int (indexed),
dates_id int (indexed),
wh_calc_id int (indexed),
daily_val numeric

I'm open to adding an index that would help speed things up, but what index?

Postgres 10

<s>PS - I've had to kill both queries before they completed, so I don't really know if they are written correctly. Hopefully my description helps.</s>


问:
Deploy Microsoft Node.js bot using Visual Studio
I have created Azure Bot service for nodeJS LUIS bot.
Downloaded the zip file to for local development.

Now I want to publish the changes back to Azure Bot from Visual studio 2017.

Which different environment variables I need to set to publish from desktop without using Visual studio services.

答:
You can also open the Advanced settings in Azure:

And download the publish profile:

Then, create a new Visual Studio Node.js project using the "From Existing Node.js code" TypeScript template (selecting the folder that contains the files downloaded):

Visual Studio Node Project Wizard 1:

Visual Studio Node Project Wizard 2:

Finally, import the publish profile downloaded earlier:

You should now be able to publish directly from Visual Studio.

ContentLicense: CC BY-SA 4.0


问:
How do I copy a large file in chunks from a source file to a destination file using python?
The file can be say 20GB. The traditional approach of importing,reading a file and then writing to another file is not feasible. </p>

答:
The shutil module has a function designed for this purpose:

```<code>import shutil
shutil.copy(src, dst)
</code>```

Body:
The shutil module has a function designed for this purpose:

import shutil
shutil.copy(src, dst)


答:
Your problem description, despite being well written, unfortunately wrongly attributes the problem to Ansible Vault.

In fact, the problem you reported, comes simply from trying to execute the task which effectively becomes:

```<code>- command: echo abc"def
</code>```

Ansible Vault plays no role in causing this problem -- if you defined the variable directly with foo: abc\"def you'd get the same error message.

The solution is simply to quote the string in the echo command:

```<code>- command: echo '{{ foo }}'
</code>```

Other than that you can use quote filter, but for Vault-protected variable you need to first set a static fact:

```<code>- set_fact:
    bar: "{{ foo }}"
- command: echo {{ bar|quote }}
</code>```

Finally, the simplest solution to the underlying problem is: do not use special characters in passwords. Increase the length instead.

Title: Ansible vaulted variables with quotes in it

Body:
I am using Ansible 2.4.
I can't get following ansible-playbook to run:

test.yml

---
- hosts: "localhost"
  become: no

  vars:
    foo_withsinglequote: !vault |
          $ANSIBLE_VAULT;1.1;AES256
          39313737636336313832376165636465346162366333663137373165363662316263336166393666
          3566643732663063386333303638633962363863306463610a643931396636613361353165653265
          38376630313939626637623538613432373336646663636563623062636238313731326263336263
          3138643931323662620a336534383964663562353162393930613965386465616630363335326138
          3431
    foo_withdoublequote: !vault |
          $ANSIBLE_VAULT;1.1;AES256
          64633863363838326664323238313866616161313937323563636430326432393638336334303336
          3533653339663438356238613937336466623834666537630a646139643033653237353262616662
          30643732313861373130633036346361663130326332303932616433643761633739306137333237
          6263653365386132620a633738663336313532366637613533313361646339623137393461383363
          3332

  tasks:
   - name: Echo foo_withsinglequote
     command: echo "{{ foo_withsinglequote }}"
   - name: Echo foo_withdoublequote
     command: echo "{{ foo_withdoublequote }}"

To generate the vault variables I used following:

$ echo 123 > vlt.txt
$ ansible-vault --vault-password-file=vlt.txt encrypt_string "abc\"def"
$ ansible-vault --vault-password-file=vlt.txt encrypt_string "abc\'def"

To run the playbook:

$ ansible-playbook --vault-password-file=vlt.txt test.yml

This gives following error:

An exception occurred during task execution. To see the full traceback, use -vvv. The error was: ValueError: No closing quotation

fatal: [localhost]: FAILED! => {"changed": false, "failed": true, "module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_8uz23O/ansible_module_command.py\", line 213, in \n    main()\n  File \"/tmp/ansible_8uz23O/ansible_module_command.py\", line 182, in main\n    args = shlex.split(args)\n  File \"/usr/lib/python2.7/shlex.py\", line 279, in split\n    return list(lex)\n  File \"/usr/lib/python2.7/shlex.py\", line 269, in next\n    token = self.get_token()\n  File \"/usr/lib/python2.7/shlex.py\", line 96, in get_token\n    raw = self.read_token()\n  File \"/usr/lib/python2.7/shlex.py\", line 172, in read_token\n    raise ValueError, \"No closing quotation\"\nValueError: No closing quotation\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 0}

How can I quote the vaulted variables correctly? Because I don't know in advance, if the vaulted variables will contain single or double quotes.

Body:
Your problem description, despite being well written, unfortunately wrongly attributes the problem to Ansible Vault.

In fact, the problem you reported, comes simply from trying to execute the task which effectively becomes:

- command: echo abc"def

Ansible Vault plays no role in causing this problem -- if you defined the variable directly with foo: abc\"def you'd get the same error message.

The solution is simply to quote the string in the echo command:

- command: echo '{{ foo }}'

Other than that you can use quote filter, but for Vault-protected variable you need to first set a static fact:

- set_fact:
    bar: "{{ foo }}"
- command: echo {{ bar|quote }}

Finally, the simplest solution to the underlying problem is: do not use special characters in passwords. Increase the length instead.


问:
Firebase Phone Authentication Android gives Error NoSuchMethodError: android.support.v4.app.FragmentManager.isStateSaved
I'm implementing Firebase Google and Phone Authentication in my app.
Sign-In with Google Working fine. But Phone Authentication giving

Error: NoSuchMethodError: android.support.v4.app.FragmentManager.isStateSaved

I'm using Firebase and Firebase-UI in Android

That's the APP Level Build Gradle File

```<code>apply plugin: 'com.android.application'

android {
        compileSdkVersion 26
        defaultConfig {
        applicationId "com.dev_man_team.fiverr.predictnwin"
        minSdkVersion 16
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner
        "android.support.test.runner.AndroidJUnitRunner"
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
       }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

    compile 'com.android.support:recyclerview-v7:26.1.0'
    compile 'com.android.support:design:26.1.0'
    compile 'com.android.support:cardview-v7:26.1.0'
    compile 'com.google.firebase:firebase-database:11.6.0'
    compile 'com.google.firebase:firebase-storage:11.6.0'
    compile 'com.google.firebase:firebase-auth:11.6.0'
    compile 'com.google.android.gms:play-services:11.6.0'

    compile 'com.firebaseui:firebase-ui-database:3.1.0'

    compile 'com.firebaseui:firebase-ui-auth:3.1.0'

    compile 'com.firebaseui:firebase-ui-storage:3.1.0'
}

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

And that's the code

```<code>private FirebaseAuth auth;
private static final int RC_SIGN_IN = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_signup_login);

    auth = FirebaseAuth.getInstance();
    if(auth.getCurrentUser() != null){
        Toast.makeText(getApplicationContext(), "User is Already Signed in", Toast.LENGTH_LONG).show();
    }
    else{

        signUp();
    }
}

private void signUp() {
    List<AuthUI.IdpConfig> providers = new ArrayList<>();
    providers.add(new AuthUI.IdpConfig.Builder(AuthUI.PHONE_VERIFICATION_PROVIDER).build());
    providers.add(new AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER).build());
    startActivityForResult(AuthUI.getInstance().createSignInIntentBuilder().setAvailableProviders(providers).build(), RC_SIGN_IN);
}

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

    if(requestCode == RC_SIGN_IN){
        IdpResponse response = IdpResponse.fromResultIntent(data);

        if(resultCode == RESULT_OK){
            startActivity(new Intent(this, MainActivity.class));
            finish();
            Toast.makeText(getApplicationContext(), "User Signed in", Toast.LENGTH_LONG).show();
        }
    }
}
</code>```

And that's the Error I recieved

11-15 20:48:12.509 9712-9712/com.dev_man_team.fiverr.predictnwin E/UncaughtException: java.lang.NoSuchMethodError: android.support.v4.app.FragmentManager.isStateSaved
                                                                                at com.firebase.ui.auth.ui.phone.CompletableProgressDialog.showAllowingStateLoss(CompletableProgressDialog.java:51)
                                                                                at com.firebase.ui.auth.ui.phone.CompletableProgressDialog.show(CompletableProgressDialog.java:41)
                                                                                at com.firebase.ui.auth.ui.phone.PhoneVerificationActivity.showLoadingDialog(PhoneVerificationActivity.java:390)
                                                                                at com.firebase.ui.auth.ui.phone.PhoneVerificationActivity.verifyPhoneNumber(PhoneVerificationActivity.java:157)
                                                                                at com.firebase.ui.auth.ui.phone.VerifyPhoneNumberFragment.onNext(VerifyPhoneNumberFragment.java:200)
                                                                                at com.firebase.ui.auth.ui.phone.VerifyPhoneNumberFragment.onActivityResult(VerifyPhoneNumberFragment.java:184)
                                                                                at android.support.v4.app.FragmentActivity.onActivityResult(FragmentActivity.java:164)
                                                                                at android.app.Activity.dispatchActivityResult(Activity.java:5387)
                                                                                at android.app.ActivityThread.deliverResults(ActivityThread.java:3205)
                                                                                at android.app.ActivityThread.handleSendResult(ActivityThread.java:3252)
                                                                                at android.app.ActivityThread.access$1200(ActivityThread.java:143)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1289)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                                at android.os.Looper.loop(Looper.java:137)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:4960)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:511)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
                                                                                at dalvik.system.NativeStart.main(Native Method)
  11-15 20:48:12.769 9712-9712/com.dev_man_team.fiverr.predictnwin E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                java.lang.NoSuchMethodError: android.support.v4.app.FragmentManager.isStateSaved
                                                                                at com.firebase.ui.auth.ui.phone.CompletableProgressDialog.showAllowingStateLoss(CompletableProgressDialog.java:51)
                                                                                at com.firebase.ui.auth.ui.phone.CompletableProgressDialog.show(CompletableProgressDialog.java:41)
                                                                                at com.firebase.ui.auth.ui.phone.PhoneVerificationActivity.showLoadingDialog(PhoneVerificationActivity.java:390)
                                                                                at com.firebase.ui.auth.ui.phone.PhoneVerificationActivity.verifyPhoneNumber(PhoneVerificationActivity.java:157)
                                                                                at com.firebase.ui.auth.ui.phone.VerifyPhoneNumberFragment.onNext(VerifyPhoneNumberFragment.java:200)
                                                                                at com.firebase.ui.auth.ui.phone.VerifyPhoneNumberFragment.onActivityResult(VerifyPhoneNumberFragment.java:184)
                                                                                at android.support.v4.app.FragmentActivity.onActivityResult(FragmentActivity.java:164)
                                                                                at android.app.Activity.dispatchActivityResult(Activity.java:5387)
                                                                                at android.app.ActivityThread.deliverResults(ActivityThread.java:3205)
                                                                                at android.app.ActivityThread.handleSendResult(ActivityThread.java:3252)
                                                                                at android.app.ActivityThread.access$1200(ActivityThread.java:143)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1289)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                                at android.os.Looper.loop(Looper.java:137)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:4960)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:511)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
                                                                                at dalvik.system.NativeStart.main(Native Method)

Thanks in advance for correcting my mistakes.
I will appreciate Your help.

答:
Finally found answer of my own question after doing lots of search

With @Bob's three suggestions I added one more thing in my App Level Build Gradle

```<code>compile ('com.google.firebase:firebase-core:11.4.2'){
    exclude group: 'com.google.firebase:firebase-analytics:9.0.0'
}
compile ('com.google.firebase:firebase-auth:11.4.2'){
    exclude group: 'com.google.firebase:firebase-analytics:9.0.0'
}
</code>```

to avoid the conflicts.
Now everything works fine.

Body:
I'm implementing Firebase Google and Phone Authentication in my app.
Sign-In with Google Working fine. But Phone Authentication giving

Error: NoSuchMethodError: android.support.v4.app.FragmentManager.isStateSaved

I'm using Firebase and Firebase-UI in Android

That's the APP Level Build Gradle File

apply plugin: 'com.android.application'

android {
        compileSdkVersion 26
        defaultConfig {
        applicationId "com.dev_man_team.fiverr.predictnwin"
        minSdkVersion 16
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner
        "android.support.test.runner.AndroidJUnitRunner"
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
       }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

    compile 'com.android.support:recyclerview-v7:26.1.0'
    compile 'com.android.support:design:26.1.0'
    compile 'com.android.support:cardview-v7:26.1.0'
    compile 'com.google.firebase:firebase-database:11.6.0'
    compile 'com.google.firebase:firebase-storage:11.6.0'
    compile 'com.google.firebase:firebase-auth:11.6.0'
    compile 'com.google.android.gms:play-services:11.6.0'

    compile 'com.firebaseui:firebase-ui-database:3.1.0'

    compile 'com.firebaseui:firebase-ui-auth:3.1.0'

    compile 'com.firebaseui:firebase-ui-storage:3.1.0'
}

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

And that's the code

private FirebaseAuth auth;
private static final int RC_SIGN_IN = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_signup_login);

    auth = FirebaseAuth.getInstance();
    if(auth.getCurrentUser() != null){
        Toast.makeText(getApplicationContext(), "User is Already Signed in", Toast.LENGTH_LONG).show();
    }
    else{

        signUp();
    }
}

private void signUp() {
    List<AuthUI.IdpConfig> providers = new ArrayList<>();
    providers.add(new AuthUI.IdpConfig.Builder(AuthUI.PHONE_VERIFICATION_PROVIDER).build());
    providers.add(new AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER).build());
    startActivityForResult(AuthUI.getInstance().createSignInIntentBuilder().setAvailableProviders(providers).build(), RC_SIGN_IN);
}

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

    if(requestCode == RC_SIGN_IN){
        IdpResponse response = IdpResponse.fromResultIntent(data);

        if(resultCode == RESULT_OK){
            startActivity(new Intent(this, MainActivity.class));
            finish();
            Toast.makeText(getApplicationContext(), "User Signed in", Toast.LENGTH_LONG).show();
        }
    }
}

And that's the Error I recieved

11-15 20:48:12.509 9712-9712/com.dev_man_team.fiverr.predictnwin E/UncaughtException: java.lang.NoSuchMethodError: android.support.v4.app.FragmentManager.isStateSaved
                                                                                at com.firebase.ui.auth.ui.phone.CompletableProgressDialog.showAllowingStateLoss(CompletableProgressDialog.java:51)
                                                                                at com.firebase.ui.auth.ui.phone.CompletableProgressDialog.show(CompletableProgressDialog.java:41)
                                                                                at com.firebase.ui.auth.ui.phone.PhoneVerificationActivity.showLoadingDialog(PhoneVerificationActivity.java:390)
                                                                                at com.firebase.ui.auth.ui.phone.PhoneVerificationActivity.verifyPhoneNumber(PhoneVerificationActivity.java:157)
                                                                                at com.firebase.ui.auth.ui.phone.VerifyPhoneNumberFragment.onNext(VerifyPhoneNumberFragment.java:200)
                                                                                at com.firebase.ui.auth.ui.phone.VerifyPhoneNumberFragment.onActivityResult(VerifyPhoneNumberFragment.java:184)
                                                                                at android.support.v4.app.FragmentActivity.onActivityResult(FragmentActivity.java:164)
                                                                                at android.app.Activity.dispatchActivityResult(Activity.java:5387)
                                                                                at android.app.ActivityThread.deliverResults(ActivityThread.java:3205)
                                                                                at android.app.ActivityThread.handleSendResult(ActivityThread.java:3252)
                                                                                at android.app.ActivityThread.access$1200(ActivityThread.java:143)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1289)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                                at android.os.Looper.loop(Looper.java:137)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:4960)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:511)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
                                                                                at dalvik.system.NativeStart.main(Native Method)
  11-15 20:48:12.769 9712-9712/com.dev_man_team.fiverr.predictnwin E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                java.lang.NoSuchMethodError: android.support.v4.app.FragmentManager.isStateSaved
                                                                                at com.firebase.ui.auth.ui.phone.CompletableProgressDialog.showAllowingStateLoss(CompletableProgressDialog.java:51)
                                                                                at com.firebase.ui.auth.ui.phone.CompletableProgressDialog.show(CompletableProgressDialog.java:41)
                                                                                at com.firebase.ui.auth.ui.phone.PhoneVerificationActivity.showLoadingDialog(PhoneVerificationActivity.java:390)
                                                                                at com.firebase.ui.auth.ui.phone.PhoneVerificationActivity.verifyPhoneNumber(PhoneVerificationActivity.java:157)
                                                                                at com.firebase.ui.auth.ui.phone.VerifyPhoneNumberFragment.onNext(VerifyPhoneNumberFragment.java:200)
                                                                                at com.firebase.ui.auth.ui.phone.VerifyPhoneNumberFragment.onActivityResult(VerifyPhoneNumberFragment.java:184)
                                                                                at android.support.v4.app.FragmentActivity.onActivityResult(FragmentActivity.java:164)
                                                                                at android.app.Activity.dispatchActivityResult(Activity.java:5387)
                                                                                at android.app.ActivityThread.deliverResults(ActivityThread.java:3205)
                                                                                at android.app.ActivityThread.handleSendResult(ActivityThread.java:3252)
                                                                                at android.app.ActivityThread.access$1200(ActivityThread.java:143)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1289)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                                at android.os.Looper.loop(Looper.java:137)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:4960)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:511)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
                                                                                at dalvik.system.NativeStart.main(Native Method)

Thanks in advance for correcting my mistakes.
I will appreciate Your help.

Body:
Finally found answer of my own question after doing lots of search

With @Bob's three suggestions I added one more thing in my App Level Build Gradle

compile ('com.google.firebase:firebase-core:11.4.2'){
    exclude group: 'com.google.firebase:firebase-analytics:9.0.0'
}
compile ('com.google.firebase:firebase-auth:11.4.2'){
    exclude group: 'com.google.firebase:firebase-analytics:9.0.0'
}

to avoid the conflicts.
Now everything works fine.


问:
Why .txt file in  is getting downloaded instead of displayed?
I am using an  to display a text file:

```<code><div class="document-view">
    <img src="img/302.GIF" />
</div>

$(window).load(function () {
    <s:if test="extention.equalsIgnoreCase('txt')">
      element = '<iframe class="iframe" src="/dmsrepo/<s:property value="docLocation"/>" />';
    </s:if>

    $('.document-view').html(element);
});
</code>```

When I inspect element in the browser I can see the file location.

```<code><iframe class="iframe" src="/dmsrepo/Legal Doc Type/LegalDocType_123456789_1.0.txt" />
</code>```

But the text file is getting downloaded in Chrome, Firefox and IE.

How to resolve this issue?

EDIT: you can reproduce the behavior in the following fiddle, that strangely affects only Firefox, for every page load after the first one.

Simply open the page, then press Run.

Note: it affects also the first load if Firebug Net module is activated.

答:
to display file add below line(s) in .htaccess

```<code>AddType text/plain .txt
AddType text/plain .log
</code>```

This is signal Firefox that you don't have to download the file instead view file as plain text.This technique can be applied to all the files that you need to view instead off download.

Title: Why .txt file in <iframe> is getting downloaded instead of displayed?

Body:
I am using an  to display a text file:

$(window).load(function () {
    <s:if test="extention.equalsIgnoreCase('txt')">
      element = '<iframe class="iframe" src="/dmsrepo/<s:property value="docLocation"/>" />';
    </s:if>

    $('.document-view').html(element);
});

When I inspect element in the browser I can see the file location.

But the text file is getting downloaded in Chrome, Firefox and IE.

How to resolve this issue?

EDIT: you can reproduce the behavior in the following fiddle, that strangely affects only Firefox, for every page load after the first one.

Simply open the page, then press Run.

Note: it affects also the first load if Firebug Net module is activated.

Body:
to display file add below line(s) in .htaccess

AddType text/plain .txt
AddType text/plain .log

This is signal Firefox that you don't have to download the file instead view file as plain text.This technique can be applied to all the files that you need to view instead off download.


问:
how to use strings in my code
Im trying to fix my code , it runs smooth but it just reads the 1st letter of the elements , so like U,C,K,N,O. Runs pretty well with no problems

but when trying to enter : Fe,Cl,Uuu,Pd,Rh. it reads only the 1st letter and gives a wrong answer.

so im trying no fix it , so it reads all of the elements with no problem.

```<code>#include <iostream>
#include <Windows.h>

int main()

{

    using namespace std;

    char Index;

    cout<<"please type an Element to see its Atomic number"<<endl;

    cin>>Index;

    switch (Index)
    {

          case 'H':

            cout<<"tAtomic Number is 2"<<endl;

             break;

          case 'Li':

                cout<<"The full name is (Lithium) , The Atomic number is 3"<<endl;

                break;

               case 'Ac':

              cout<<"The full name is ( Actinium )The Atomic number is 89"<<endl;

              break;

               case 'Al':

              cout<<"The full name is ( Aluminum )The Atomic number is 13"<<endl;

              break;

               case 'Am':

              cout<<"The full name is ( Americium )The Atomic number is 95"<<endl;

              break;

               case 'Sb':

              cout<<"The full name is ( Antimony )The Atomic number is 51"<<endl;

              break;

               case 'Ar':

              cout<<"The full name is ( Argon )The Atomic number is 18"<<endl;

              break;

               case 'As':

              cout<<"The full name is ( Arsenic )The Atomic number is 33"<<endl;

              break;

               case 'At':

              cout<<"The full name is ( Astatine )The Atomic number is 85"<<endl;

              break;

               case 'Ba':

              cout<<"The full name is ( Barium )The Atomic number is 56"<<endl;

              break;

               case 'Bk':

              cout<<"The full name is ( Berkelium )The Atomic number is 97"<<endl;

              break;

               case 'Be':

              cout<<"The full name is ( Beryllium )The Atomic number is 4"<<endl;

              break;

               case 'Bi':

              cout<<"The full name is ( Bismuth )The Atomic number is 83"<<endl;

              break;

               case 'Bh':

              cout<<"The full name is ( Bohrium ) The Atomic number is 107"<<endl;

              break;

               case 'B':

              cout<<"The full name is ( Boron )The Atomic number is 5"<<endl;

              break;

               case 'Br':

              cout<<"The full name is ( Bromine )The Atomic number is 35"<<endl;

              break;

               case 'Cd':

              cout<<"The full name is ( Cadmium  )The Atomic number is 48"<<endl;

              break;

               case 'Ca':

              cout<<"The full name is ( Calcium )The Atomic number is 20"<<endl;

              break;

               case 'Cf':

              cout<<"The full name is ( Californium )The Atomic number is 98"<<endl;

              break;

               case 'C':

              cout<<"The full name is ( Carbon )The Atomic number is 6"<<endl;

              break;

               case 'Ce':

              cout<<"The full name is ( Cerium )The Atomic number is 58"<<endl;

              break;

               case 'Cs':

              cout<<"The full name is ( Cesium )The Atomic number is 55"<<endl;

              break;

               case 'Cl':

              cout<<"The full name is ( Chlorine )The Atomic number is 17"<<endl;

              break;

              case 'Cr':

              cout<<"The full name is ( Chromium )The Atomic number is 24"<<endl;

              break;

              case 'Co':

              cout<<"The full name is ( Cobalt )The Atomic number is 27"<<endl;

              break;

              case 'Cu':

              cout<<"The full name is ( Copper )The Atomic number is 29"<<endl;

              break;

              case 'Cm':

              cout<<"The full name is ( Curium )The Atomic number is 96"<<endl;

              break;

              case 'Ds':

              cout<<"The full name is ( Darmstadtium )The Atomic number is 110"<<endl;

              break;

              case 'Db':

              cout<<"The full name is ( Dubnium )The Atomic number is 105"<<endl;

              break;

              case 'Dy':

              cout<<"The full name is ( Dysprosium )The Atomic number is 66"<<endl;

              break;

              case 'Es':

              cout<<"The full name is ( Einsteinium )The Atomic number is 99"<<endl;

              break;

              case 'Er':

              cout<<"The full name is ( Erbium )The Atomic number is 68"<<endl;

              break;

              case 'Eu':

              cout<<"The full name is ( Europium )The Atomic number is 63"<<endl;

              break;

              case 'Fm':

              cout<<"The full name is ( Fermium )The Atomic number is 100"<<endl;

              break;

              case 'F':

              cout<<"The full name is ( Fluorine )The Atomic number is 9"<<endl;

              break;

              case 'Fr':

              cout<<"The full name is ( Francium )The Atomic number is 87"<<endl;

              break;

              case 'Gd':

              cout<<"The full name is ( Gadolinium )The Atomic number is 64"<<endl;

              break;

              case 'Ga':

              cout<<"The full name is ( Gallium  )The Atomic number is 31"<<endl;

              break;

              case 'Ge':

              cout<<"The full name is ( Germanium )The Atomic number is 32"<<endl;

              break;

              case 'Au':

              cout<<"The full name is ( Gold )The Atomic number is 79"<<endl;

              break;

              case 'Hf':

              cout<<"The full name is ( Hafnium )The Atomic number is 72"<<endl;

              break;

              case 'Hs':

              cout<<"The full name is ( Hassium )The Atomic number is 108"<<endl;

              break;

              case 'He':

              cout<<"The full name is ( Helium )The Atomic number is 2"<<endl;

              break;

              case 'Ho':

              cout<<"The full name is ( Holmium  )The Atomic number is 67"<<endl;

              break;

              case 'In':

              cout<<"The full name is ( Indium )The Atomic number is 49"<<endl;

              break;

              case 'I':

              cout<<"The full name is ( Iodine )The Atomic number is 53"<<endl;

              break;

              case 'Ir':

              cout<<"The full name is ( Iridium  )The Atomic number is 77"<<endl;

              break;

                case 'Fe':

              cout<<"The full name is ( Iron )The Atomic number is 26"<<endl;

              break;

                case 'Kr':

              cout<<"The full name is ( Krypton )The Atomic number is 36"<<endl;

              break;

                case 'La':

              cout<<"The full name is ( Lanthanum )The Atomic number is 57"<<endl;

              break;

                case 'Lr':

              cout<<"The full name is ( Lawrencium )The Atomic number is 103"<<endl;

              break;

                case 'Pb':

              cout<<"The full name is ( Lead )The Atomic number is 82"<<endl;

              break;

                case 'Lu':

              cout<<"The full name is ( Lutetium )The Atomic number is 71"<<endl;

              break;

                case 'Mg':

              cout<<"The full name is ( Magnesium )The Atomic number is 12"<<endl;

              break;

                case 'Mn':

              cout<<"The full name is ( Manganese )The Atomic number is 25"<<endl;

              break;

                case 'Mt':

              cout<<"The full name is ( Meitnerium )The Atomic number is 109"<<endl;

              break;

                case 'Md':

              cout<<"The full name is ( Mendelevium  )The Atomic number is 101"<<endl;

              break;

                case 'Hg':

              cout<<"The full name is ( Mercury )The Atomic number is 80"<<endl;

              break;

                case 'Mo':

              cout<<"The full name is ( Molybdenum )The Atomic number is 42"<<endl;

              break;

                case 'Ne':

              cout<<"The full name is ( Neon )The Atomic number is 77"<<endl;

              break;

                case 'Nd':

              cout<<"The full name is ( Neodymium )The Atomic number is 60"<<endl;

              break;

                case 'Np':

              cout<<"The full name is ( Neptunium )The Atomic number is 93"<<endl;

              break;

                case 'Ni':

              cout<<"The full name is ( Nickel )The Atomic number is 28"<<endl;

              break;

                case 'Nb':

              cout<<"The full name is ( Niobium )The Atomic number is 41"<<endl;

              break;

              case 'N':

              cout<<"The full name is ( Nitrogen )The Atomic number is 7"<<endl;

              break;

              case 'No':

              cout<<"The full name is ( Nobelium )The Atomic number is 102"<<endl;

              break;

              case 'Os':

              cout<<"The full name is ( Osmium  )The Atomic number is 76"<<endl;

              break;

              case 'O':

              cout<<"The full name is ( Oxygen  )The Atomic number is 8"<<endl;

              break;

              case 'Pd':

              cout<<"The full name is ( Palladium )The Atomic number is 46"<<endl;

              break;

              case 'P':

              cout<<"The full name is ( Phosphorus  )The Atomic number is 15"<<endl;

              break;

              case 'Pt':

              cout<<"The full name is ( Platinum )The Atomic number is 78"<<endl;

              break;

              case 'Pu':

              cout<<"The full name is ( Plutonium )The Atomic number is 94"<<endl;

              break;

              case 'Po':

              cout<<"The full name is ( Polonium )The Atomic number is 84"<<endl;

              break;

              case 'K':

              cout<<"The full name is ( Potassium )The Atomic number is 19"<<endl;

              break;

              case 'Pr':

              cout<<"The full name is ( Praseodymium )The Atomic number is 59"<<endl;

              break;

              case 'Pm':

              cout<<"The full name is ( Promethium )The Atomic number is 61"<<endl;

              break;

              case 'Pa':

              cout<<"The full name is ( Protactinium )The Atomic number is 91"<<endl;

              break;

              case 'Ra':

              cout<<"The full name is ( Radium )The Atomic number is 88"<<endl;

              break;

              case 'Rn':

              cout<<"The full name is ( Radon )The Atomic number is 86"<<endl;

              break;

              case 'Re':

              cout<<"The full name is ( Rhenium )The Atomic number is 75"<<endl;

              break;

              case 'Rh':

              cout<<"The full name is ( Rhodium )The Atomic number is 45"<<endl;

              break;

              case 'Rg':

              cout<<"The full name is ( Roentgenium )The Atomic number is 111"<<endl;

              break;

              case 'Rb':

              cout<<"The full name is ( Rubidium )The Atomic number is 37"<<endl;

              break;

              case 'Ru':

              cout<<"The full name is ( Ruthenium )The Atomic number is 44"<<endl;

              break;

              case 'Rf':

              cout<<"The full name is ( Rutherfordium )The Atomic number is 104"<<endl;

              break;

              case 'Sm':

              cout<<"The full name is ( Samarium )The Atomic number is 62"<<endl;

              break;

              case 'Sc':

              cout<<"The full name is ( Scandium )The Atomic number is 21"<<endl;

              break;

              case 'Sg':

              cout<<"The full name is ( Seaborgium )The Atomic number is 106"<<endl;

              break;

              case 'Se':

              cout<<"The full name is ( Selenium )The Atomic number is 34"<<endl;

              break;

              case 'Si':

              cout<<"The full name is ( Silicon  )The Atomic number is 14"<<endl;

              case 'Ag':

              cout<<"The full name is ( Silver )The Atomic number is 47"<<endl;

              break;

              case 'Na':

              cout<<"The full name is ( Sodium )The Atomic number is 11"<<endl;

              break;

              case 'Sr':

              cout<<"The full name is ( Strontium )The Atomic number is 38"<<endl;

              break;

              case 'S':

              cout<<"The full name is ( Sulfur )The Atomic number is 16"<<endl;

              break;

              case 'Ta':

              cout<<"The full name is ( Tantalum )The Atomic number is 73"<<endl;

              break;

              case 'Tc':

              cout<<"The full name is ( Technetium )The Atomic number is 43"<<endl;

              break;

                  case 'Te':

              cout<<"The full name is ( Tellurium  )The Atomic number is 52"<<endl;

              break;

                  case 'Tb':

              cout<<"The full name is ( Terbium )The Atomic number is 65"<<endl;

              break;

                  case 'Tl':

              cout<<"The full name is ( Thallium )The Atomic number is 81"<<endl;

              break;

                  case 'Th':

              cout<<"The full name is ( Thorium )The Atomic number is 90"<<endl;

              break;

                  case 'Tm':

              cout<<"The full name is ( Thulium )The Atomic number is 69"<<endl;

              break;

                  case 'Sn':

              cout<<"The full name is ( Tin )The Atomic number is 50"<<endl;

              break;
                  case 'Ti':

              cout<<"The full name is ( Titanium )The Atomic number is 22"<<endl;

              break;
                  case 'W':

              cout<<"The full name is ( Tungsten )The Atomic number is 74"<<endl;

              break;
                  case 'Uub':

              cout<<"The full name is ( Ununbium )The Atomic number is 112"<<endl;

              break;
                  case 'Uuh':

              cout<<"The full name is ( Ununhexium )The Atomic number is 116"<<endl;

              break;
                  case 'Uuo':

              cout<<"The full name is ( Ununoctium )The Atomic number is 118"<<endl;

              break;
                  case 'Uup':

              cout<<"The full name is ( Ununpentium  )The Atomic number is 115"<<endl;

              break;
                  case 'Uuq':

                      cout<<"The full name is ( Ununquadium  )The Atomic number is 114"<<endl;
              break;

                  case 'Uus':

              cout<<"The full name is ( Ununseptium  )The Atomic number is 117"<<endl;

              break;

                  case 'Uut':

              cout<<"The full name is ( Ununtrium )The Atomic number is 113"<<endl;

              break;

                  case 'Uuu':

              cout<<"The full name is ( Ununium  )The Atomic number is 111"<<endl;

              break;

                  case 'U':

              cout<<"The full name is ( Uranium  )The Atomic number is 92"<<endl;

              break;

                case 'V':

              cout<<"The full name is ( Vanadium )The Atomic number is 23"<<endl;

              break;

                case 'Xe':

              cout<<"The full name is ( Xenon )The Atomic number is 54"<<endl;

              break;

                case 'Yb':

              cout<<"The full name is ( Ytterbium )The Atomic number is 70"<<endl;

              break;

                case 'Y':

              cout<<"The full name is ( Yttrium  )The Atomic number is 39"<<endl;

              break;

                case 'Zn':

              cout<<"The full name is ( Zinc )The Atomic number is 30"<<endl;

              break;
                case 'Zr':

              cout<<"The full name is ( Zirconium )The Atomic number is 40"<<endl;

              break;

                default:

                    cout<<"There is no element with that Symbol !! , please close the program and try again"<<endl;

    return 0;

    Sleep (5000);

 }
}
</code>```

答:
You may use std::map as switch case doesn't handle std::string:

```<code>const std::map<std::string, std::string> m = {
    {"H", tAtomic Number is 2"},
    {"Li", "The full name is (Lithium) , The Atomic number is 3"},
    {"Ac", "The full name is ( Actinium )The Atomic number is 89"},
    // ...
};
std::cout << "please type an Element to see its Atomic number" << std::endl;
std::string input;
std::cin >> input;

const auto it = m.find(input);
if (it == m.end()) {
    std::cout << "There is no element with that Symbol !!"
        "Please close the program and try again" << std::endl;
} else {
    std::cout << it->second << std::endl;
}
</code>```

Title: how to use strings in my code

Body:
Im trying to fix my code , it runs smooth but it just reads the 1st letter of the elements , so like U,C,K,N,O. Runs pretty well with no problems

but when trying to enter : Fe,Cl,Uuu,Pd,Rh. it reads only the 1st letter and gives a wrong answer.

so im trying no fix it , so it reads all of the elements with no problem.

#include <iostream>
#include <Windows.h>

int main()

{

    using namespace std;

    char Index;

    cout<<"please type an Element to see its Atomic number"<<endl;

    cin>>Index;

    switch (Index)
    {

          case 'H':

            cout<<"tAtomic Number is 2"<<endl;

             break;

          case 'Li':

                cout<<"The full name is (Lithium) , The Atomic number is 3"<<endl;

                break;

               case 'Ac':

              cout<<"The full name is ( Actinium )The Atomic number is 89"<<endl;

              break;

               case 'Al':

              cout<<"The full name is ( Aluminum )The Atomic number is 13"<<endl;

              break;

               case 'Am':

              cout<<"The full name is ( Americium )The Atomic number is 95"<<endl;

              break;

               case 'Sb':

              cout<<"The full name is ( Antimony )The Atomic number is 51"<<endl;

              break;

               case 'Ar':

              cout<<"The full name is ( Argon )The Atomic number is 18"<<endl;

              break;

               case 'As':

              cout<<"The full name is ( Arsenic )The Atomic number is 33"<<endl;

              break;

               case 'At':

              cout<<"The full name is ( Astatine )The Atomic number is 85"<<endl;

              break;

               case 'Ba':

              cout<<"The full name is ( Barium )The Atomic number is 56"<<endl;

              break;

               case 'Bk':

              cout<<"The full name is ( Berkelium )The Atomic number is 97"<<endl;

              break;

               case 'Be':

              cout<<"The full name is ( Beryllium )The Atomic number is 4"<<endl;

              break;

               case 'Bi':

              cout<<"The full name is ( Bismuth )The Atomic number is 83"<<endl;

              break;

               case 'Bh':

              cout<<"The full name is ( Bohrium ) The Atomic number is 107"<<endl;

              break;

               case 'B':

              cout<<"The full name is ( Boron )The Atomic number is 5"<<endl;

              break;

               case 'Br':

              cout<<"The full name is ( Bromine )The Atomic number is 35"<<endl;

              break;

               case 'Cd':

              cout<<"The full name is ( Cadmium  )The Atomic number is 48"<<endl;

              break;

               case 'Ca':

              cout<<"The full name is ( Calcium )The Atomic number is 20"<<endl;

              break;

               case 'Cf':

              cout<<"The full name is ( Californium )The Atomic number is 98"<<endl;

              break;

               case 'C':

              cout<<"The full name is ( Carbon )The Atomic number is 6"<<endl;

              break;

               case 'Ce':

              cout<<"The full name is ( Cerium )The Atomic number is 58"<<endl;

              break;

               case 'Cs':

              cout<<"The full name is ( Cesium )The Atomic number is 55"<<endl;

              break;

               case 'Cl':

              cout<<"The full name is ( Chlorine )The Atomic number is 17"<<endl;

              break;

              case 'Cr':

              cout<<"The full name is ( Chromium )The Atomic number is 24"<<endl;

              break;

              case 'Co':

              cout<<"The full name is ( Cobalt )The Atomic number is 27"<<endl;

              break;

              case 'Cu':

              cout<<"The full name is ( Copper )The Atomic number is 29"<<endl;

              break;

              case 'Cm':

              cout<<"The full name is ( Curium )The Atomic number is 96"<<endl;

              break;

              case 'Ds':

              cout<<"The full name is ( Darmstadtium )The Atomic number is 110"<<endl;

              break;

              case 'Db':

              cout<<"The full name is ( Dubnium )The Atomic number is 105"<<endl;

              break;

              case 'Dy':

              cout<<"The full name is ( Dysprosium )The Atomic number is 66"<<endl;

              break;

              case 'Es':

              cout<<"The full name is ( Einsteinium )The Atomic number is 99"<<endl;

              break;

              case 'Er':

              cout<<"The full name is ( Erbium )The Atomic number is 68"<<endl;

              break;

              case 'Eu':

              cout<<"The full name is ( Europium )The Atomic number is 63"<<endl;

              break;

              case 'Fm':

              cout<<"The full name is ( Fermium )The Atomic number is 100"<<endl;

              break;

              case 'F':

              cout<<"The full name is ( Fluorine )The Atomic number is 9"<<endl;

              break;

              case 'Fr':

              cout<<"The full name is ( Francium )The Atomic number is 87"<<endl;

              break;

              case 'Gd':

              cout<<"The full name is ( Gadolinium )The Atomic number is 64"<<endl;

              break;

              case 'Ga':

              cout<<"The full name is ( Gallium  )The Atomic number is 31"<<endl;

              break;

              case 'Ge':

              cout<<"The full name is ( Germanium )The Atomic number is 32"<<endl;

              break;

              case 'Au':

              cout<<"The full name is ( Gold )The Atomic number is 79"<<endl;

              break;

              case 'Hf':

              cout<<"The full name is ( Hafnium )The Atomic number is 72"<<endl;

              break;

              case 'Hs':

              cout<<"The full name is ( Hassium )The Atomic number is 108"<<endl;

              break;

              case 'He':

              cout<<"The full name is ( Helium )The Atomic number is 2"<<endl;

              break;

              case 'Ho':

              cout<<"The full name is ( Holmium  )The Atomic number is 67"<<endl;

              break;

              case 'In':

              cout<<"The full name is ( Indium )The Atomic number is 49"<<endl;

              break;

              case 'I':

              cout<<"The full name is ( Iodine )The Atomic number is 53"<<endl;

              break;

              case 'Ir':

              cout<<"The full name is ( Iridium  )The Atomic number is 77"<<endl;

              break;

                case 'Fe':

              cout<<"The full name is ( Iron )The Atomic number is 26"<<endl;

              break;

                case 'Kr':

              cout<<"The full name is ( Krypton )The Atomic number is 36"<<endl;

              break;

                case 'La':

              cout<<"The full name is ( Lanthanum )The Atomic number is 57"<<endl;

              break;

                case 'Lr':

              cout<<"The full name is ( Lawrencium )The Atomic number is 103"<<endl;

              break;

                case 'Pb':

              cout<<"The full name is ( Lead )The Atomic number is 82"<<endl;

              break;

                case 'Lu':

              cout<<"The full name is ( Lutetium )The Atomic number is 71"<<endl;

              break;

                case 'Mg':

              cout<<"The full name is ( Magnesium )The Atomic number is 12"<<endl;

              break;

                case 'Mn':

              cout<<"The full name is ( Manganese )The Atomic number is 25"<<endl;

              break;

                case 'Mt':

              cout<<"The full name is ( Meitnerium )The Atomic number is 109"<<endl;

              break;

                case 'Md':

              cout<<"The full name is ( Mendelevium  )The Atomic number is 101"<<endl;

              break;

                case 'Hg':

              cout<<"The full name is ( Mercury )The Atomic number is 80"<<endl;

              break;

                case 'Mo':

              cout<<"The full name is ( Molybdenum )The Atomic number is 42"<<endl;

              break;

                case 'Ne':

              cout<<"The full name is ( Neon )The Atomic number is 77"<<endl;

              break;

                case 'Nd':

              cout<<"The full name is ( Neodymium )The Atomic number is 60"<<endl;

              break;

                case 'Np':

              cout<<"The full name is ( Neptunium )The Atomic number is 93"<<endl;

              break;

                case 'Ni':

              cout<<"The full name is ( Nickel )The Atomic number is 28"<<endl;

              break;

                case 'Nb':

              cout<<"The full name is ( Niobium )The Atomic number is 41"<<endl;

              break;

              case 'N':

              cout<<"The full name is ( Nitrogen )The Atomic number is 7"<<endl;

              break;

              case 'No':

              cout<<"The full name is ( Nobelium )The Atomic number is 102"<<endl;

              break;

              case 'Os':

              cout<<"The full name is ( Osmium  )The Atomic number is 76"<<endl;

              break;

              case 'O':

              cout<<"The full name is ( Oxygen  )The Atomic number is 8"<<endl;

              break;

              case 'Pd':

              cout<<"The full name is ( Palladium )The Atomic number is 46"<<endl;

              break;

              case 'P':

              cout<<"The full name is ( Phosphorus  )The Atomic number is 15"<<endl;

              break;

              case 'Pt':

              cout<<"The full name is ( Platinum )The Atomic number is 78"<<endl;

              break;

              case 'Pu':

              cout<<"The full name is ( Plutonium )The Atomic number is 94"<<endl;

              break;

              case 'Po':

              cout<<"The full name is ( Polonium )The Atomic number is 84"<<endl;

              break;

              case 'K':

              cout<<"The full name is ( Potassium )The Atomic number is 19"<<endl;

              break;

              case 'Pr':

              cout<<"The full name is ( Praseodymium )The Atomic number is 59"<<endl;

              break;

              case 'Pm':

              cout<<"The full name is ( Promethium )The Atomic number is 61"<<endl;

              break;

              case 'Pa':

              cout<<"The full name is ( Protactinium )The Atomic number is 91"<<endl;

              break;

              case 'Ra':

              cout<<"The full name is ( Radium )The Atomic number is 88"<<endl;

              break;

              case 'Rn':

              cout<<"The full name is ( Radon )The Atomic number is 86"<<endl;

              break;

              case 'Re':

              cout<<"The full name is ( Rhenium )The Atomic number is 75"<<endl;

              break;

              case 'Rh':

              cout<<"The full name is ( Rhodium )The Atomic number is 45"<<endl;

              break;

              case 'Rg':

              cout<<"The full name is ( Roentgenium )The Atomic number is 111"<<endl;

              break;

              case 'Rb':

              cout<<"The full name is ( Rubidium )The Atomic number is 37"<<endl;

              break;

              case 'Ru':

              cout<<"The full name is ( Ruthenium )The Atomic number is 44"<<endl;

              break;

              case 'Rf':

              cout<<"The full name is ( Rutherfordium )The Atomic number is 104"<<endl;

              break;

              case 'Sm':

              cout<<"The full name is ( Samarium )The Atomic number is 62"<<endl;

              break;

              case 'Sc':

              cout<<"The full name is ( Scandium )The Atomic number is 21"<<endl;

              break;

              case 'Sg':

              cout<<"The full name is ( Seaborgium )The Atomic number is 106"<<endl;

              break;

              case 'Se':

              cout<<"The full name is ( Selenium )The Atomic number is 34"<<endl;

              break;

              case 'Si':

              cout<<"The full name is ( Silicon  )The Atomic number is 14"<<endl;

              case 'Ag':

              cout<<"The full name is ( Silver )The Atomic number is 47"<<endl;

              break;

              case 'Na':

              cout<<"The full name is ( Sodium )The Atomic number is 11"<<endl;

              break;

              case 'Sr':

              cout<<"The full name is ( Strontium )The Atomic number is 38"<<endl;

              break;

              case 'S':

              cout<<"The full name is ( Sulfur )The Atomic number is 16"<<endl;

              break;

              case 'Ta':

              cout<<"The full name is ( Tantalum )The Atomic number is 73"<<endl;

              break;

              case 'Tc':

              cout<<"The full name is ( Technetium )The Atomic number is 43"<<endl;

              break;

                  case 'Te':

              cout<<"The full name is ( Tellurium  )The Atomic number is 52"<<endl;

              break;

                  case 'Tb':

              cout<<"The full name is ( Terbium )The Atomic number is 65"<<endl;

              break;

                  case 'Tl':

              cout<<"The full name is ( Thallium )The Atomic number is 81"<<endl;

              break;

                  case 'Th':

              cout<<"The full name is ( Thorium )The Atomic number is 90"<<endl;

              break;

                  case 'Tm':

              cout<<"The full name is ( Thulium )The Atomic number is 69"<<endl;

              break;

                  case 'Sn':

              cout<<"The full name is ( Tin )The Atomic number is 50"<<endl;

              break;
                  case 'Ti':

              cout<<"The full name is ( Titanium )The Atomic number is 22"<<endl;

              break;
                  case 'W':

              cout<<"The full name is ( Tungsten )The Atomic number is 74"<<endl;

              break;
                  case 'Uub':

              cout<<"The full name is ( Ununbium )The Atomic number is 112"<<endl;

              break;
                  case 'Uuh':

              cout<<"The full name is ( Ununhexium )The Atomic number is 116"<<endl;

              break;
                  case 'Uuo':

              cout<<"The full name is ( Ununoctium )The Atomic number is 118"<<endl;

              break;
                  case 'Uup':

              cout<<"The full name is ( Ununpentium  )The Atomic number is 115"<<endl;

              break;
                  case 'Uuq':

                      cout<<"The full name is ( Ununquadium  )The Atomic number is 114"<<endl;
              break;

                  case 'Uus':

              cout<<"The full name is ( Ununseptium  )The Atomic number is 117"<<endl;

              break;

                  case 'Uut':

              cout<<"The full name is ( Ununtrium )The Atomic number is 113"<<endl;

              break;

                  case 'Uuu':

              cout<<"The full name is ( Ununium  )The Atomic number is 111"<<endl;

              break;

                  case 'U':

              cout<<"The full name is ( Uranium  )The Atomic number is 92"<<endl;

              break;

                case 'V':

              cout<<"The full name is ( Vanadium )The Atomic number is 23"<<endl;

              break;

                case 'Xe':

              cout<<"The full name is ( Xenon )The Atomic number is 54"<<endl;

              break;

                case 'Yb':

              cout<<"The full name is ( Ytterbium )The Atomic number is 70"<<endl;

              break;

                case 'Y':

              cout<<"The full name is ( Yttrium  )The Atomic number is 39"<<endl;

              break;

                case 'Zn':

              cout<<"The full name is ( Zinc )The Atomic number is 30"<<endl;

              break;
                case 'Zr':

              cout<<"The full name is ( Zirconium )The Atomic number is 40"<<endl;

              break;

                default:

                    cout<<"There is no element with that Symbol !! , please close the program and try again"<<endl;

    return 0;

    Sleep (5000);

 }
}

Body:
You may use std::map as switch case doesn't handle std::string:

const std::map<std::string, std::string> m = {
    {"H", tAtomic Number is 2"},
    {"Li", "The full name is (Lithium) , The Atomic number is 3"},
    {"Ac", "The full name is ( Actinium )The Atomic number is 89"},
    // ...
};
std::cout << "please type an Element to see its Atomic number" << std::endl;
std::string input;
std::cin >> input;

const auto it = m.find(input);
if (it == m.end()) {
    std::cout << "There is no element with that Symbol !!"
        "Please close the program and try again" << std::endl;
} else {
    std::cout << it->second << std::endl;
}


问:
Get any key from keyboard in C++ including keys like control
I'm programming in C++ and have run into a wall.

I need to get input from the keyboard.  The problem is that I also need to get input from keys like control, scroll lock, windows key, etc.  I also need to be able to differentiate between the numpad and regular numbers 0-9.

I tried using _getch().  While it can get keys like arrow keys and the numpad, I can't get keys like control, shift and scroll lock.

Does anyone have any suggestions?

答:
There is no standard way to do this because C++ does not assume the system even has all those things.

A good solution for what you are trying to do is the SDL library. Look here:
https://www.libsdl.org/


问:
What is the purpose of FrameLayout and in which scenario should we use it?
What purpose does FrameLayout serve in Android? Is there any specific scenario for which it is designed for?

In my Android application, I have a scenario where I have to show two ImageViews, one over the other. This is a .png image file with a 9-patch drawable over this image.

Which ViewGroup should I use for this purpose: RelativeLayout or FrameLayout?

I also want to know the different scenarios that each of the ViewGroups should be used for.

答:
I don't recall how i got to this question but here is my answer that could help anyone:

As you can see here

FrameLayout is designed to block out an area on the screen to display a single item. Generally, FrameLayout should be used to hold a single child view, because it can be difficult to organize child views in a way that's scalable to different screen sizes without the children overlapping each other.

In general is not useful to have 2 views one over the other because you're going to have overdraw effect (an area of the screen that is getting drawn by the gpu more than once which is really useless).

If you really have to, then you need to use the onDraw method (you can see an example here) and Canvas API (have a look here) and the clipRect method (you can see an example here)

Regarding FrameLayout or RelativeLayout, if you want to keep things simple or your activity has already enough nested layouts, better use FrameLayout. In 2017, there is the constraint layout which could be of some help as well.


问:
Wordpress title limiting to 15 characters
I am using wordpress and I want to show upto 15 characters for my post title.

I have used this:

```
$myposts = get_posts('numberposts=11&offset=0');
foreach($myposts as $post) :
        substr(the_title(), 0, 15);
endforeach;
```

I have removed the PHP tags to look properly here...basically the code is marked as bold.

but it is not working.

Any suggestion is highly appreciable.

答:
the_title() outputs the title directly instead of returning it. Use get_the_title() instead.

```<code><?php echo substr(get_the_title(), 0, 15)?>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am using wordpress and I want to show upto 15 characters for my post title.

I have used this:

$myposts = get_posts('numberposts=11&offset=0');
foreach($myposts as $post) :
        substr(the_title(), 0, 15);
endforeach;

I have removed the PHP tags to look properly here...basically the code is marked as bold.

but it is not working.

Any suggestion is highly appreciable.

Body:
the_title() outputs the title directly instead of returning it. Use get_the_title() instead.

<?php echo substr(get_the_title(), 0, 15)?>


问:
JS: Return value from EventListener function
i'm trying to return an array of instances of my Class. However the return is simply returning from the window.addEventListener('load', function(){} ); function I believe. As when I type plugins into the control it is undefined.

```<code>;class Parallax {

    constructor(node) {

        // Settings and defaults
        // this.settings = {
        //     container: null,
        //     panels: [],
        //     defaultSpeed: 0.5
        // };

    }

    static initialize() {

        // Ensure DOM has loaded
        window.addEventListener('load', function() {
            // Does page contain any parallax panels?
            let panels = document.querySelectorAll('[data-parallax]');
            if (panels.length > 0) {

                let instances = [];

                // Parallax panels found, create instances of class and return them for reference
                for (const panel in panels) {
                    if (panels.hasOwnProperty(panel)) {
                        instances.push(new this(panels[panel]));
                    }
                }

                return instances;
            } else {
                // Page doesn't appear to have Parallax
                return false;
            }
        }.bind(this));
    }
}
window.plugins = { "parallax-instances": Parallax.initialize() };
</code>```

Not too sure how to go about doing this, I have tried assigning the window.addEventListener to a variable, however that doesn't return the value. I am retaining the class scope by binding this to my function call within the event listener.

Edit:
I did want to start the plugin by simply having the below code, however not too sure how to return possible multiple instances of the class as of course doing the below runs the constructor method first.

```<code>window.plugins = { "parallax-instances": new Parallax };
</code>```

Edit 2
If I return the instances outside of the EventListener I get my desired result. However this could potentially return instances before the page has loaded right?

```<code>static initialize() {

        this.instances = [];

        // Ensure DOM has loaded
        window.addEventListener('load', function() {
            // Does page contain any parallax panels?
            let panels = document.querySelectorAll('[data-parallax]');
            if (panels.length > 0) {

                // Parallax panels found, create instances of class and return them for reference
                for (const panel in panels) {
                    if (panels.hasOwnProperty(panel)) {
                        this.instances.push(new this(panels[panel]));
                    }
                }
            }
        }.bind(this));

        return this.instances;
    }
</code>```

What I get in the console:

```<code>{parallax-instances: Array(2)}
    parallax-instances:Array(2)
        0:Parallax {}
        1:Parallax {}
        length:2
    __proto__:Array(0)
    __proto__:Object
</code>```

答:
An event listener function is a callback, and runs only when the event happens (in your case, on load).

Callbacks cannot return a value. You could use a variable in the outer scope (e.g. within your class), and reassign it within your event listener.

E.g.

```<code>constructor () {
  this.instances = []
}
</code>```

And then (instead of returning from your event listener):

```<code>this.instances = instances
</code>```

Body:
i'm trying to return an array of instances of my Class. However the return is simply returning from the window.addEventListener('load', function(){} ); function I believe. As when I type plugins into the control it is undefined.

;class Parallax {

    constructor(node) {

        // Settings and defaults
        // this.settings = {
        //     container: null,
        //     panels: [],
        //     defaultSpeed: 0.5
        // };

    }

    static initialize() {

        // Ensure DOM has loaded
        window.addEventListener('load', function() {
            // Does page contain any parallax panels?
            let panels = document.querySelectorAll('[data-parallax]');
            if (panels.length > 0) {

                let instances = [];

                // Parallax panels found, create instances of class and return them for reference
                for (const panel in panels) {
                    if (panels.hasOwnProperty(panel)) {
                        instances.push(new this(panels[panel]));
                    }
                }

                return instances;
            } else {
                // Page doesn't appear to have Parallax
                return false;
            }
        }.bind(this));
    }
}
window.plugins = { "parallax-instances": Parallax.initialize() };

Not too sure how to go about doing this, I have tried assigning the window.addEventListener to a variable, however that doesn't return the value. I am retaining the class scope by binding this to my function call within the event listener.

Edit:
I did want to start the plugin by simply having the below code, however not too sure how to return possible multiple instances of the class as of course doing the below runs the constructor method first.

window.plugins = { "parallax-instances": new Parallax };

Edit 2
If I return the instances outside of the EventListener I get my desired result. However this could potentially return instances before the page has loaded right?

static initialize() {

        this.instances = [];

        // Ensure DOM has loaded
        window.addEventListener('load', function() {
            // Does page contain any parallax panels?
            let panels = document.querySelectorAll('[data-parallax]');
            if (panels.length > 0) {

                // Parallax panels found, create instances of class and return them for reference
                for (const panel in panels) {
                    if (panels.hasOwnProperty(panel)) {
                        this.instances.push(new this(panels[panel]));
                    }
                }
            }
        }.bind(this));

        return this.instances;
    }

What I get in the console:

{parallax-instances: Array(2)}
    parallax-instances:Array(2)
        0:Parallax {}
        1:Parallax {}
        length:2
    __proto__:Array(0)
    __proto__:Object

Body:
An event listener function is a callback, and runs only when the event happens (in your case, on load).

Callbacks cannot return a value. You could use a variable in the outer scope (e.g. within your class), and reassign it within your event listener.

E.g.

constructor () {
  this.instances = []
}

And then (instead of returning from your event listener):

this.instances = instances


问:
Merge Request trigger for multibranch pipeline in Jenkins
How can you trigger a multi-branch pipeline on a merge request? The configurations do not save for specific branches in a multi-branch pipeline. And yes I do know that a single pipeline has an option to trigger on merge requests but I am looking for a solution for MULTI-BRANCH pipelines. I can't seem to find a solution anywhere. </p>

答:
You should be able to use a combination of webhooks as well as the Jenkins Git service to trigger a multi-branch pipeline.

Your webhook url should look something like <your-jenkins-url>/github-webhook.


问:
How to create unique variable scope names with given prefix?
I am writing my own functional layers like

```<code>def vgg_block(x, is_training, output_depth,... name = "vgg_block"):

    with tf.variable_scope(name):
        if pool_size is not None:
            x = tf.layers.max_pooling2d(x, pool_size=pool_size, strides=pool_strides, padding=pool_padding)

        for i_conv in range(n_convs):
            x = conv2d_bn(x, is_training, output_depth, kernel_size=conv_size, strides=conv_strides, padding=conv_padding, bn=conv_bn,
                          activation=conv_activation)

    return x
</code>```

and would like they can name automatically like build-in ones.

Unfortunately, if I write as above, I am receiving duplicate errors, because my inner functions create the same inner scopes.

Is it possible to ask TF to generate new uniue variable scope name on each call?

答: do tf.variable_scope(name=None, default_name=name) which is guaranteed to create a new variable scope with a name like name.

Body:
I am writing my own functional layers like

def vgg_block(x, is_training, output_depth,... name = "vgg_block"):

    with tf.variable_scope(name):
        if pool_size is not None:
            x = tf.layers.max_pooling2d(x, pool_size=pool_size, strides=pool_strides, padding=pool_padding)

        for i_conv in range(n_convs):
            x = conv2d_bn(x, is_training, output_depth, kernel_size=conv_size, strides=conv_strides, padding=conv_padding, bn=conv_bn,
                          activation=conv_activation)

    return x

and would like they can name automatically like build-in ones.

Unfortunately, if I write as above, I am receiving duplicate errors, because my inner functions create the same inner scopes.

Is it possible to ask TF to generate new uniue variable scope name on each call?


问:
Docker: can not communicate between containers
I have a Docker setup with a php-fpm container, a node container and an nginx container which serves as a proxy. Now in the browser (http://project.dev), the php container responds with json like I expect. All good. However, when I make a request from the node container to this php container (view code), I get an error on the request: ECONNRESET. So apparently, the node container can not communicate with the php container. The nginx error does not seem to add an entry.

```<code>Error: read ECONNRESET at _errnoException(util.js: 1031: 13) at TCP.onread(net.js: 619: 25)
errno: 'ECONNRESET',
code: 'ECONNRESET',
syscall: 'read'
</code>```

Any ideas?

I've made a github repo: https://github.com/thomastilkema/docker-nginx-php-fpm-node

Trimmed version of docker-compose.yml (view file)

```<code>nginx:
  depends_on:
    - php-fpm
    - node
  networks:
    - app
  ports:
    - 80:80

php-fpm:
  networks:
    - app

node:
  networks:
    - app

networks:
  app:
    driver: overlay
</code>```

Trimmed version of nginx.conf (view file)

```<code>http {
  upstream php-fpm {
    server php-fpm:9000;
  }

  upstream node {
    server node:4000;
  }

  server {
    listen 80 reuseport;
    server_name api.project.dev;

    location ~ \.php$ {
      fastcgi_pass php-fpm;
      ...
    }
  }

  server {
    listen 80;
    server_name project.dev;

    location / {
      proxy_pass  http://node;
    }
  }
}
</code>```

php-fpm/Dockerfile (view file)

```<code>FROM php:7.1-fpm-alpine

WORKDIR /var/www

EXPOSE 9000

CMD ["php-fpm"]
</code>```

Request which gives an error

```<code>const response = await axios.get('http://php-fpm:9000');
</code>```

How to reproduce

Create a swarm manager (and a worker) node

Find out the ip address of your swarm manager node (usually 192.168.99.100): docker-machine ip manager or docker-machine ls. Edit your hosts file (on a Mac, sudo vi /private/etc/hosts) by adding 192.168.99.100 project.dev and 192.168.99.100 api.project.dev

git clone https://github.com/thomastilkema/docker-nginx-php-fpm-node project

cd project ./scripts/up.sh

Have a look at the logs of the container: docker logs <container-id> -f

答:
ECONNRESET is the other end closing the connection which can usually be attributed to a protocol error.

The FastCGI Process Manager (FPM) uses the FastCGI protocol to transport data.

Go via the nginx container, which translates the HTTP request to FastCGI

```<code>axios.get('http://nginx/whatever.php')
</code>```

Body:
I have a Docker setup with a php-fpm container, a node container and an nginx container which serves as a proxy. Now in the browser (http://project.dev), the php container responds with json like I expect. All good. However, when I make a request from the node container to this php container (view code), I get an error on the request: ECONNRESET. So apparently, the node container can not communicate with the php container. The nginx error does not seem to add an entry.

Error: read ECONNRESET at _errnoException(util.js: 1031: 13) at TCP.onread(net.js: 619: 25)
errno: 'ECONNRESET',
code: 'ECONNRESET',
syscall: 'read'

Any ideas?

I've made a github repo: https://github.com/thomastilkema/docker-nginx-php-fpm-node

Trimmed version of docker-compose.yml (view file)

nginx:
  depends_on:
    - php-fpm
    - node
  networks:
    - app
  ports:
    - 80:80

php-fpm:
  networks:
    - app

node:
  networks:
    - app

networks:
  app:
    driver: overlay

Trimmed version of nginx.conf (view file)

http {
  upstream php-fpm {
    server php-fpm:9000;
  }

  upstream node {
    server node:4000;
  }

  server {
    listen 80 reuseport;
    server_name api.project.dev;

    location ~ \.php$ {
      fastcgi_pass php-fpm;
      ...
    }
  }

  server {
    listen 80;
    server_name project.dev;

    location / {
      proxy_pass  http://node;
    }
  }
}

php-fpm/Dockerfile (view file)

FROM php:7.1-fpm-alpine

WORKDIR /var/www

EXPOSE 9000

CMD ["php-fpm"]

Request which gives an error

const response = await axios.get('http://php-fpm:9000');

How to reproduce

Create a swarm manager (and a worker) node

Find out the ip address of your swarm manager node (usually 192.168.99.100): docker-machine ip manager or docker-machine ls. Edit your hosts file (on a Mac, sudo vi /private/etc/hosts) by adding 192.168.99.100 project.dev and 192.168.99.100 api.project.dev

git clone https://github.com/thomastilkema/docker-nginx-php-fpm-node project

cd project ./scripts/up.sh

Have a look at the logs of the container: docker logs <container-id> -f

Body:
ECONNRESET is the other end closing the connection which can usually be attributed to a protocol error.

The FastCGI Process Manager (FPM) uses the FastCGI protocol to transport data.

Go via the nginx container, which translates the HTTP request to FastCGI

axios.get('http://nginx/whatever.php')


问:
JavaScript variable changing between two values on a regular basis
I want a variable's value regularly changing between 0 and 1.  If I have a variable whose value is 0 (counter = 0), how can I increase it by 1 (counter = 1) after a few seconds, then decrease it back to 0 ( counter = 0) after another few seconds? An endless loop basically is what I want.

I'm assuming this will require setTimeout or setInterval, but I've absolutely no idea how I'd go about this. I'm very unfamiliar with the syntax; I'm very much a newbie. Does anyone have any pointers?

Thanks!

答:
```<code>var counter = 0;
var changeCounter = function () {
  counter = counter === 0 ? 1 : 0;
  console.log('counter', counter);
  setTimeout(changeCounter, 1000);
}
changeCounter();
</code>```


问:
How to mock WebServiceContext injected into Web Service
I am struggling to Unit test the methods in my web service. All of the methods look at the injected WebServiceContext and pull a userId from that in order to make sure that the user is authorized. I have spent many hours trying to figure out how to mock up the WebServiceContext, but no matter what I try, the context is always null.

My end goal is to be able to return a userId that I specify in my test class so that I can proceed on to test the actual functionality of the rest of the method.

This is a stripped down version of how most of the methods are setup:

```<code>@HandlerChain(file = "/handler.xml")
@javax.jws.WebService (...)
public class SoapImpl
{
    @Resource
    private WebServiceContext context;

    public void methodUnderTest()
    {

        // context is NULL here - throws null pointer
        Principal userprincipal = context.getUserPrincipal();

        String userId = userprincipal.getName();

        // Do some stuff - I want to test this stuff, but can't get here
    }

}
</code>```

This is how I am attempting to mock the context and test

```<code>@RunWith(MockitoJUnitRunner.class)
@PrepareForTest(SoapImpl.class)
public class SoapImplTest {

    @Mock
    WebServiceContext context;

    @Mock
    Principal userPrincipal;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testCreateOverrideRules() {

        SoapImpl testImpl = new SoapImpl();

        when(context.getUserPrincipal).thenReturn(userPrincipal);
        when(userPrincipal.getName()).thenReturn("testUser");

        testImpl.methodUnderTest();

        assertEquals(1,1);
    }

}
</code>```

I know about dependency injection and passing the context in through the constructor, but I am not sure that I can do that here, because the context is injected through the @resource annotation. A constructor is never called. I don't fully understand how I would implement that.

Also, WebServiceContext and Principal are interfaces, so they cannot be instantiated, which makes this even more confusing. Can anyone help me out here? How can I mock the WebServiceContext and the Principal so I can get past this part of the method and move on to what I really want to test?

UPDATE
I was able to solve the problem by using the @InjectMocks annotation as seen in the code below:

```<code>@RunWith(MockitoJUnitRunner.class)
@PrepareForTest(SoapImpl.class)
public class SoapImplTest {

    @InjectMocks
    private SoapImpl testImpl = new SoapImpl();

    @Mock
    WebServiceContext context;

    @Mock
    Principal userPrincipal;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testCreateOverrideRules() {

        when(context.getUserPrincipal).thenReturn(userPrincipal);
        when(userPrincipal.getName()).thenReturn("testUser");

        testImpl.methodUnderTest();

        assertEquals(1,1);
    }

}
</code>```

答:
1) You should have a constructor or setter that sets the context in your class under test.  If you don't, you'll want to add one for this exact reason.

2) You don't need to instantiate WebServiceContext or Principal.  Simply create mocks for them using Mockito.mock(WebServiceContext.class) and Mockito.mock(Principal.class).  Then add Mockito.when(mockWebServiceContext).. to add behavior.

Keep in mind that if you're doing unit testing, you want to test only the logic in your method under test, and not any additional methods or integrations.  This is why you want mock instances of both WebServiceContext and Principal.  You do not want an integration test (presumably).

Body:
I am struggling to Unit test the methods in my web service. All of the methods look at the injected WebServiceContext and pull a userId from that in order to make sure that the user is authorized. I have spent many hours trying to figure out how to mock up the WebServiceContext, but no matter what I try, the context is always null.

My end goal is to be able to return a userId that I specify in my test class so that I can proceed on to test the actual functionality of the rest of the method.

This is a stripped down version of how most of the methods are setup:

@HandlerChain(file = "/handler.xml")
@javax.jws.WebService (...)
public class SoapImpl
{
    @Resource
    private WebServiceContext context;

    public void methodUnderTest()
    {

        // context is NULL here - throws null pointer
        Principal userprincipal = context.getUserPrincipal();

        String userId = userprincipal.getName();

        // Do some stuff - I want to test this stuff, but can't get here
    }

}

This is how I am attempting to mock the context and test

@RunWith(MockitoJUnitRunner.class)
@PrepareForTest(SoapImpl.class)
public class SoapImplTest {

    @Mock
    WebServiceContext context;

    @Mock
    Principal userPrincipal;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testCreateOverrideRules() {

        SoapImpl testImpl = new SoapImpl();

        when(context.getUserPrincipal).thenReturn(userPrincipal);
        when(userPrincipal.getName()).thenReturn("testUser");

        testImpl.methodUnderTest();

        assertEquals(1,1);
    }

}

I know about dependency injection and passing the context in through the constructor, but I am not sure that I can do that here, because the context is injected through the @resource annotation. A constructor is never called. I don't fully understand how I would implement that.

Also, WebServiceContext and Principal are interfaces, so they cannot be instantiated, which makes this even more confusing. Can anyone help me out here? How can I mock the WebServiceContext and the Principal so I can get past this part of the method and move on to what I really want to test?

UPDATE
I was able to solve the problem by using the @InjectMocks annotation as seen in the code below:

@RunWith(MockitoJUnitRunner.class)
@PrepareForTest(SoapImpl.class)
public class SoapImplTest {

    @InjectMocks
    private SoapImpl testImpl = new SoapImpl();

    @Mock
    WebServiceContext context;

    @Mock
    Principal userPrincipal;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testCreateOverrideRules() {

        when(context.getUserPrincipal).thenReturn(userPrincipal);
        when(userPrincipal.getName()).thenReturn("testUser");

        testImpl.methodUnderTest();

        assertEquals(1,1);
    }

}


问:
Using \COPY to load CSV with JSON fields into Postgres
I'm attempting to load TSV data from a file into a Postgres table using the \COPY command.

Here's an example data row:

```<code>2017-11-22 23:00:00     "{\"id\":123,\"class\":101,\"level\":3}"
</code>```

Here's the psql command I'm using:

```<code>\COPY bogus.test_table (timestamp, sample_json) FROM '/local/file.txt' DELIMITER E'\t'
</code>```

Here's the error I'm receiving:

```<code>ERROR:  invalid input syntax for type json
DETAIL:  Token "sample_json" is invalid.
CONTEXT:  JSON data, line 1: "{"sample_json...
COPY test_table, line 1, column sample_json: ""{\"id\":123,\"class\":101,\"level\":3}""
</code>```

I verified the JSON is in the correct JSON format and read a couple similar questions, but I'm still not sure what's going on here. An explanation would be awesome

答:
To load your data file as it is:</p>

```<code>\COPY bogus.test_table (timestamp, sample_json) FROM '/local/file.txt' CSV DELIMITER E'\t' QUOTE '"' ESCAPE '\'
</code>```

Body:
I'm attempting to load TSV data from a file into a Postgres table using the \COPY command.

Here's an example data row:

2017-11-22 23:00:00     "{\"id\":123,\"class\":101,\"level\":3}"

Here's the psql command I'm using:

\COPY bogus.test_table (timestamp, sample_json) FROM '/local/file.txt' DELIMITER E'\t'

Here's the error I'm receiving:

ERROR:  invalid input syntax for type json
DETAIL:  Token "sample_json" is invalid.
CONTEXT:  JSON data, line 1: "{"sample_json...
COPY test_table, line 1, column sample_json: ""{\"id\":123,\"class\":101,\"level\":3}""

I verified the JSON is in the correct JSON format and read a couple similar questions, but I'm still not sure what's going on here. An explanation would be awesome

Body:
To load your data file as it is:

\COPY bogus.test_table (timestamp, sample_json) FROM '/local/file.txt' CSV DELIMITER E'\t' QUOTE '"' ESCAPE '\'