问:
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.

答:
Three suggestions:

(1) You are using FirebaseUI version 3.1.0 with newer version 11.6.0 of  Firebase and Google Play libraries. The FirebaseUI documentation explains that this requires upgrading transitive dependencies.  Following the instructions in the documentation, you should add these dependencies:

```<code>compile 'com.android.support:customtabs:26.1.0'
compile 'com.android.support:support-v4:26.1.0'
compile 'com.android.support:palette-v7:26.1.0'
</code>```

(2) You are including ALL of Google Play services:

```<code>compile 'com.google.android.gms:play-services:11.6.0'
</code>```

This needlessly increases you APK size and build time and will cause your app to exceed the 65K method reference limit on older devices.  Better to only include the specific APIs you need, such as play-services-auth. (List of APIs here)

(3) Your build.gradle does not specifiy the buildToolsVersion.  I don't know what default is used.  Safer to specify one, for example:

```<code>compileSdkVersion 26
buildToolsVersion "26.0.2"
</code>```

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:
Three suggestions:

(1) You are using FirebaseUI version 3.1.0 with newer version 11.6.0 of  Firebase and Google Play libraries. The FirebaseUI documentation explains that this requires upgrading transitive dependencies.  Following the instructions in the documentation, you should add these dependencies:

compile 'com.android.support:customtabs:26.1.0'
compile 'com.android.support:support-v4:26.1.0'
compile 'com.android.support:palette-v7:26.1.0'

(2) You are including ALL of Google Play services:

compile 'com.google.android.gms:play-services:11.6.0'

This needlessly increases you APK size and build time and will cause your app to exceed the 65K method reference limit on older devices.  Better to only include the specific APIs you need, such as play-services-auth. (List of APIs here)

(3) Your build.gradle does not specifiy the buildToolsVersion.  I don't know what default is used.  Safer to specify one, for example:

compileSdkVersion 26
buildToolsVersion "26.0.2"


来源: stackexchange

问:
retrieving column name from index (Python)
I am looping into a large dataframe with several columns to find some elements, while keeping track of the row and column position with counters.

When I find the element, I would like to find the column header corresponding to that based on the counters. Is there a simple way to do that?

For example, given:

data = [{'a': 200, 'b': 150, 'c': 200, 'd': 140, 'e':100}]

df6 = pd.DataFrame(data)

and counter=1, how do I get the corresponding column header 'b' ?

Thank you!

答:
You can use the index selection from the column index of a dataframe.

```<code>data = [{'a': 200, 'b': 150, 'c': 200, 'd': 140, 'e':100}]
df6 = pd.DataFrame(data)
counter = 1
df6.columns[counter]
</code>```

Output:

```<code>'b'
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can use the index selection from the column index of a dataframe.

data = [{'a': 200, 'b': 150, 'c': 200, 'd': 140, 'e':100}]
df6 = pd.DataFrame(data)
counter = 1
df6.columns[counter]

Output:

'b'


问:
module.exports Cannot set property of undefined
I am trying to move all react components to separate repo so that they can be shared. I am getting the above error

ui-react/index.js

```<code>'use strict';

import Button from "./components/Button/Button";

module.exports.Button = Button;
</code>```

FileB

```<code>import  {Button} from  'ui-react';
</code>```

When i do this i get an error called.

```<code>'ui-react' does not contain an export named 'Button'
</code>```

PS: In package.json of ui-react i have set main to index.js and i have also tried import "ui-react/index"

答:
No need to write module.exports. You can write </p>

```<code>export { Button };
</code>```

Body:
I am trying to move all react components to separate repo so that they can be shared. I am getting the above error

ui-react/index.js

'use strict';

import Button from "./components/Button/Button";

module.exports.Button = Button;

FileB

import  {Button} from  'ui-react';

When i do this i get an error called.

'ui-react' does not contain an export named 'Button'

PS: In package.json of ui-react i have set main to index.js and i have also tried import "ui-react/index"

Body:
No need to write module.exports. You can write

export { Button };


问:
creating JSON format
I want to create JSON object like below,

```<code>{"Validate":"Check","Parameters":[{"name":"Greg", "value":"1"},{"name":"Mike","value":"2"}]};
</code>```

and I have two arrays like below,

```<code>["Greg", "Mike] and ["1", "2"]
</code>```

What is the best way to combine these arrays to populate the JSON object I described above by using JS?

答:
are you looking for something like this?

var keys = ['key1', 'key2', 'key3'];
var nums = [1, 2, 3]

var result = {};
keys.forEach((key, i) => result[key] = nums[i]);
console.log(result);```

Title: creating JSON format

Body:
I want to create JSON object like below,

{"Validate":"Check","Parameters":[{"name":"Greg", "value":"1"},{"name":"Mike","value":"2"}]};

and I have two arrays like below,

["Greg", "Mike] and ["1", "2"]

What is the best way to combine these arrays to populate the JSON object I described above by using JS?


问:
Infinite scroll of finite items
I have a GridView that has items inside 5x50.

I need to scroll them in all directions and instead of stopping when reached the end just start from the top/left.

for example left-to-right scroll

before scroll

```<code>1 2 3 4 5
6 7 8 9 10
</code>```

after scroll to the right

```<code>5 1 2 3 4
10 6 7 8 9
</code>```

and for top-to-bottom (or bottom-to-top)

before scroll to the bottom

```<code>1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
</code>```

after scroll

```<code>6 7 8 9 10
11 12 13 14 15
1 2 3 4 5
</code>```

I try to make it smooth scroll as GridView native scroll.

答:
This solution is based on @azizbekian source code (thanks for interesting example). It was really fun to me to find something close to what you asked (both at the same time). So, here is my modified code:

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

    private static final int spanCount = 5;
    private static final int totalItemCount = 15;

    private GridLayoutManager gridLayoutManager;
    private RecyclerView recyclerView;

    private int orientation = 1;

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

        recyclerView = (RecyclerView) findViewById(R.id.recycler);
        recyclerView.setAdapter(new MyAdapter(totalItemCount));

        // Shamelessly stolen from devunwired bit.ly/2yCqVIp
        recyclerView.addItemDecoration(new GridDividerDecoration(this));

        gridLayoutManager = new GridLayoutManager(this, spanCount);
        recyclerView.setLayoutManager(gridLayoutManager);

        RecyclerView.OnScrollListener listener = new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recycler, int dx, int dy) {
                super.onScrolled(recycler, dx, dy);

                if (dx > 0) {
                    orientation = LinearLayoutManager.HORIZONTAL;

                } else if (dx < 0) {
                    orientation = LinearLayoutManager.VERTICAL;

                } else if (dy > 0) {
                    orientation = LinearLayoutManager.VERTICAL;

                } else if (dy < 0) {
                    orientation = LinearLayoutManager.HORIZONTAL;
                }

                recycler.post(new Runnable() {
                    @Override
                    public void run() {
                        gridLayoutManager.setOrientation(orientation);
                        recyclerView.setLayoutManager(gridLayoutManager);
                        recyclerView.getAdapter().notifyDataSetChanged();
                    }
                });
            }
        };

        recyclerView.addOnScrollListener(listener);
    }

    static class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {

        private final int totalSizeOfItems;
        private boolean hasBeenSetup = false;

        MyAdapter(int totalSizeOfItems) {
            this.totalSizeOfItems = totalSizeOfItems;
        }

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
            final int cellSize = parent.getMeasuredWidth() / spanCount;
            view.setMinimumWidth(cellSize);
            view.setMinimumHeight(cellSize);
            setupRecyclerHeightIfNeeded(parent, cellSize);
            return new MyViewHolder(view);
        }

        // We need to perform this operation once, not each time `onCreateViewHolder` is called
        private void setupRecyclerHeightIfNeeded(final View parent, int cellSize) {
            if (hasBeenSetup) return;

            hasBeenSetup = true;
            ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) parent.getLayoutParams();

            int numOfRows = (int) (totalItemCount / (double) spanCount);
            params.height = numOfRows * cellSize + 100; // modified based on my phone height

            new Handler().post(new Runnable() {
                @Override
                public void run() {
                    parent.requestLayout();
                }
            });
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int pos) {
            int position = holder.getAdapterPosition() % totalSizeOfItems;
            holder.textView.setText(Integer.toString(position + 1));
        }

        @Override
        public int getItemCount() {
            // this will result the list to be "infinite"
            return Integer.MAX_VALUE;
        }
    }

    static class MyViewHolder extends RecyclerView.ViewHolder {

        TextView textView;

        MyViewHolder(View itemView) {
            super(itemView);
            textView = (TextView) itemView;
        }
    }
}
</code>```

The layout scrolls up for vertical orientation and scrolls left for horizontal. Output is following (sorry for ugly animation):

Hope it will help you.

Title: Infinite scroll of finite items

Body:
I have a GridView that has items inside 5x50.

I need to scroll them in all directions and instead of stopping when reached the end just start from the top/left.

for example left-to-right scroll

before scroll

1 2 3 4 5
6 7 8 9 10

after scroll to the right

5 1 2 3 4
10 6 7 8 9

and for top-to-bottom (or bottom-to-top)

before scroll to the bottom

1 2 3 4 5
6 7 8 9 10
11 12 13 14 15

after scroll

6 7 8 9 10
11 12 13 14 15
1 2 3 4 5

I try to make it smooth scroll as GridView native scroll.

Body:
This solution is based on @azizbekian source code (thanks for interesting example). It was really fun to me to find something close to what you asked (both at the same time). So, here is my modified code:

public class MainActivity extends AppCompatActivity {

    private static final int spanCount = 5;
    private static final int totalItemCount = 15;

    private GridLayoutManager gridLayoutManager;
    private RecyclerView recyclerView;

    private int orientation = 1;

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

        recyclerView = (RecyclerView) findViewById(R.id.recycler);
        recyclerView.setAdapter(new MyAdapter(totalItemCount));

        // Shamelessly stolen from devunwired bit.ly/2yCqVIp
        recyclerView.addItemDecoration(new GridDividerDecoration(this));

        gridLayoutManager = new GridLayoutManager(this, spanCount);
        recyclerView.setLayoutManager(gridLayoutManager);

        RecyclerView.OnScrollListener listener = new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recycler, int dx, int dy) {
                super.onScrolled(recycler, dx, dy);

                if (dx > 0) {
                    orientation = LinearLayoutManager.HORIZONTAL;

                } else if (dx < 0) {
                    orientation = LinearLayoutManager.VERTICAL;

                } else if (dy > 0) {
                    orientation = LinearLayoutManager.VERTICAL;

                } else if (dy < 0) {
                    orientation = LinearLayoutManager.HORIZONTAL;
                }

                recycler.post(new Runnable() {
                    @Override
                    public void run() {
                        gridLayoutManager.setOrientation(orientation);
                        recyclerView.setLayoutManager(gridLayoutManager);
                        recyclerView.getAdapter().notifyDataSetChanged();
                    }
                });
            }
        };

        recyclerView.addOnScrollListener(listener);
    }

    static class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {

        private final int totalSizeOfItems;
        private boolean hasBeenSetup = false;

        MyAdapter(int totalSizeOfItems) {
            this.totalSizeOfItems = totalSizeOfItems;
        }

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
            final int cellSize = parent.getMeasuredWidth() / spanCount;
            view.setMinimumWidth(cellSize);
            view.setMinimumHeight(cellSize);
            setupRecyclerHeightIfNeeded(parent, cellSize);
            return new MyViewHolder(view);
        }

        // We need to perform this operation once, not each time `onCreateViewHolder` is called
        private void setupRecyclerHeightIfNeeded(final View parent, int cellSize) {
            if (hasBeenSetup) return;

            hasBeenSetup = true;
            ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) parent.getLayoutParams();

            int numOfRows = (int) (totalItemCount / (double) spanCount);
            params.height = numOfRows * cellSize + 100; // modified based on my phone height

            new Handler().post(new Runnable() {
                @Override
                public void run() {
                    parent.requestLayout();
                }
            });
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int pos) {
            int position = holder.getAdapterPosition() % totalSizeOfItems;
            holder.textView.setText(Integer.toString(position + 1));
        }

        @Override
        public int getItemCount() {
            // this will result the list to be "infinite"
            return Integer.MAX_VALUE;
        }
    }

    static class MyViewHolder extends RecyclerView.ViewHolder {

        TextView textView;

        MyViewHolder(View itemView) {
            super(itemView);
            textView = (TextView) itemView;
        }
    }
}

The layout scrolls up for vertical orientation and scrolls left for horizontal. Output is following (sorry for ugly animation):

Hope it will help you.


问:
Programmatically Adding Views to Parent LinearLayout Duplicates Last Entry when Rotating Device
I've only been doing android programming for a few months, so I could be doing something silly here...

In my activity, I'm using a layout file with a LinearLayout that I'm programmatically adding child views to in the activity's OnCreate().  There is a layout file for the child view, and it contains 3 EditTexts that I'm populating with data I have saved somewhere.

When I navigate to the activity and onCreate() is first called, every child view is populated how I would expect.  However, if I rotate the display from portrait -> landscape or vice-versa, when the page refreshes, all child views have the content of the last child view.  When I step through the code with breakpoints, everything looks fine to me: the parent LinearLayout has the expected child views, and the child views are populated with the expected data.  So, I'm at a loss as to why all child views have the data from the last child, and why this only happens when rotating.  I'm using the same layout files here regardless of device size or orientation.

Any thoughts?

edit_profile_activity.xml:

```<code><android.support.design.widget.CoordinatorLayout
    ...>

    <android.support.design.widget.AppBarLayout
        ...>

        <android.support.v7.widget.Toolbar
            .../>

    </android.support.design.widget.AppBarLayout>

    <!-- The main content view -->
    <android.support.v4.widget.NestedScrollView
        ...>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:scrollbarAlwaysDrawVerticalTrack="true"
            android:focusable="true"
            android:focusableInTouchMode="true">

            <!-- Edit Allies -->
            <LinearLayout
                android:id="@+id/profile_edit_ally_layout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingLeft="@dimen/left_margin"
                android:paddingRight="@dimen/right_margin"
                android:orientation="vertical">

                <!-- This content is added programmatically. -->

            </LinearLayout>

        </LinearLayout>
    </android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
</code>```

edit_profile_activity_ally_list_item.xml:

```<code><LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <EditText
        android:id="@+id/profile_edit_ally_name_edit_text"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:hint="Name"
        android:imeOptions="flagNoExtractUi"
        android:inputType="textNoSuggestions"
        android:maxLines="1"
        android:privateImeOptions="nm"
        android:selectAllOnFocus="true"
        android:textAppearance="@style/FontEditText"/>
    <EditText
        android:id="@+id/profile_edit_ally_init_mod_edit_text"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_marginLeft="@dimen/left_margin"
        android:hint="Init Mod"
        android:imeOptions="flagNoExtractUi"
        android:inputType="numberSigned"
        android:maxLines="1"
        android:privateImeOptions="nm"
        android:selectAllOnFocus="true"
        android:textAppearance="@style/FontEditText"/>
    <EditText
        android:id="@+id/profile_edit_ally_caster_level_edit_text"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_marginLeft="@dimen/left_margin"
        android:hint="Caster Level"
        android:imeOptions="flagNoExtractUi"
        android:inputType="numberSigned"
        android:maxLines="1"
        android:privateImeOptions="nm"
        android:selectAllOnFocus="true"
        android:textAppearance="@style/FontEditText"/>
    <ImageButton
        android:id="@+id/profile_edit_delete_ally_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:background="@drawable/ic_delete"/>
</LinearLayout>
</code>```

In my activity:

```<code>@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    // Set the content of the activity to use the activity_main.xml layout file
    setContentView(R.layout.edit_profile_activity);

    // ...

    mAllyLayout = (LinearLayout) findViewById(R.id.profile_edit_ally_layout);
    for (TreeMap.Entry<String, AllyDB_Data> entry : mProfileData.mAllies.entrySet())
    {
        addAllyRowToLayout(entry.getKey(),
            Integer.toString(entry.getValue().mCasterLevel),
            Integer.toString(entry.getValue().mInitMod));
    }

    // Make sure there's at least one "empty" ally set.
    if (mAllyLayout.getChildCount() <= 0)
    {
        addAllyRowToLayout(null, null, null);
    }

    // ...
}

// ...

private void addAllyRowToLayout(String name, String casterLevel, String initMod)
{
    // Inflate the Ally Row
    View ally_layout_row = getLayoutInflater().inflate(R.layout.edit_profile_activity_ally_list_item, null, false);

    // EditText Name
    EditText name_edit_text = (EditText) ally_layout_row.findViewById(R.id.profile_edit_ally_name_edit_text);
    name_edit_text.setTextSize(14.0f);
    name_edit_text.setTextColor(Color.DKGRAY);
    if (name != null)
    {
        if (name.isEmpty() == false)
        {
            name_edit_text.setText(name);
        }
    }
    name_edit_text.addTextChangedListener(new TextWatcher()
    {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count)
        {
            invalidateOptionsMenu();
        }

        @Override
        public void afterTextChanged(Editable s) {}
    });

    // EditText Init Mod
    EditText init_mod_edit_text = (EditText) ally_layout_row.findViewById(R.id.profile_edit_ally_init_mod_edit_text);
    init_mod_edit_text.setTextSize(14.0f);
    init_mod_edit_text.setTextColor(Color.DKGRAY);
    if (initMod != null)
    {
        if (initMod.isEmpty() == false)
        {
            init_mod_edit_text.setText(initMod);
        }
    }

    // EditText Caster Level
    EditText caster_level_edit_text = (EditText) ally_layout_row.findViewById(R.id.profile_edit_ally_caster_level_edit_text);
    caster_level_edit_text.setTextSize(14.0f);
    caster_level_edit_text.setTextColor(Color.DKGRAY);
    if (casterLevel != null)
    {
        if (casterLevel.isEmpty() == false)
        {
            caster_level_edit_text.setText(casterLevel);
        }
    }

    // ImageButton Delete Ally Button
    ImageButton delete_button = (ImageButton) ally_layout_row.findViewById(R.id.profile_edit_delete_ally_button);
    delete_button.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            View parent_view = (View) v.getParent();
            if (parent_view != null)
            {
                mAllyLayout.removeView(parent_view);
            }
            if (mAllyLayout.getChildCount() == 0)
            {
                addAllyRowToLayout("", "", "");
            }
        }
    });

    // Add the Ally Row to the Ally Layout.
    mAllyLayout.addView(ally_layout_row);
}
</code>```

Edit 1
There's an if statement in the activity's onCreate() that I failed to show when I first posted. if (allyLayout.getChildCount() <= 0) ...

Edit 2
Looking at this post gave me the idea to see what was happening in onRestoreInstanceState(Bundle savedInstanceState).  Surprisingly to me, overriding it and making it empty, took care of my problem.  I'm not sure if that's the most orthodox solution.

答:
After this line :

```<code>mAllyLayout = (LinearLayout) findViewById(R.id.profile_edit_ally_layout);
</code>```

Check if your linear layout has some views.

```<code>   if (mAllyLayout.getChildCount()>0){
    //add your views

    }
</code>```

Update
If you don't want to handle data after rotation add this on your manifest:

```<code><activity
            android:name="Your activity"
            android:configChanges="orientation|keyboardHidden|screenSize"/>
</code>```

Body:
I've only been doing android programming for a few months, so I could be doing something silly here...

In my activity, I'm using a layout file with a LinearLayout that I'm programmatically adding child views to in the activity's OnCreate().  There is a layout file for the child view, and it contains 3 EditTexts that I'm populating with data I have saved somewhere.

When I navigate to the activity and onCreate() is first called, every child view is populated how I would expect.  However, if I rotate the display from portrait -> landscape or vice-versa, when the page refreshes, all child views have the content of the last child view.  When I step through the code with breakpoints, everything looks fine to me: the parent LinearLayout has the expected child views, and the child views are populated with the expected data.  So, I'm at a loss as to why all child views have the data from the last child, and why this only happens when rotating.  I'm using the same layout files here regardless of device size or orientation.

Any thoughts?

edit_profile_activity.xml:

<android.support.design.widget.CoordinatorLayout
    ...>

    <android.support.design.widget.AppBarLayout
        ...>

        <android.support.v7.widget.Toolbar
            .../>

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView
        ...>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:scrollbarAlwaysDrawVerticalTrack="true"
            android:focusable="true"
            android:focusableInTouchMode="true">

            <LinearLayout
                android:id="@+id/profile_edit_ally_layout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingLeft="@dimen/left_margin"
                android:paddingRight="@dimen/right_margin"
                android:orientation="vertical">

            </LinearLayout>

        </LinearLayout>
    </android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>

edit_profile_activity_ally_list_item.xml:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <EditText
        android:id="@+id/profile_edit_ally_name_edit_text"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:hint="Name"
        android:imeOptions="flagNoExtractUi"
        android:inputType="textNoSuggestions"
        android:maxLines="1"
        android:privateImeOptions="nm"
        android:selectAllOnFocus="true"
        android:textAppearance="@style/FontEditText"/>
    <EditText
        android:id="@+id/profile_edit_ally_init_mod_edit_text"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_marginLeft="@dimen/left_margin"
        android:hint="Init Mod"
        android:imeOptions="flagNoExtractUi"
        android:inputType="numberSigned"
        android:maxLines="1"
        android:privateImeOptions="nm"
        android:selectAllOnFocus="true"
        android:textAppearance="@style/FontEditText"/>
    <EditText
        android:id="@+id/profile_edit_ally_caster_level_edit_text"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_marginLeft="@dimen/left_margin"
        android:hint="Caster Level"
        android:imeOptions="flagNoExtractUi"
        android:inputType="numberSigned"
        android:maxLines="1"
        android:privateImeOptions="nm"
        android:selectAllOnFocus="true"
        android:textAppearance="@style/FontEditText"/>
    <ImageButton
        android:id="@+id/profile_edit_delete_ally_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:background="@drawable/ic_delete"/>
</LinearLayout>

In my activity:

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

    // Set the content of the activity to use the activity_main.xml layout file
    setContentView(R.layout.edit_profile_activity);

    // ...

    mAllyLayout = (LinearLayout) findViewById(R.id.profile_edit_ally_layout);
    for (TreeMap.Entry<String, AllyDB_Data> entry : mProfileData.mAllies.entrySet())
    {
        addAllyRowToLayout(entry.getKey(),
            Integer.toString(entry.getValue().mCasterLevel),
            Integer.toString(entry.getValue().mInitMod));
    }

    // Make sure there's at least one "empty" ally set.
    if (mAllyLayout.getChildCount() <= 0)
    {
        addAllyRowToLayout(null, null, null);
    }

    // ...
}

// ...

private void addAllyRowToLayout(String name, String casterLevel, String initMod)
{
    // Inflate the Ally Row
    View ally_layout_row = getLayoutInflater().inflate(R.layout.edit_profile_activity_ally_list_item, null, false);

    // EditText Name
    EditText name_edit_text = (EditText) ally_layout_row.findViewById(R.id.profile_edit_ally_name_edit_text);
    name_edit_text.setTextSize(14.0f);
    name_edit_text.setTextColor(Color.DKGRAY);
    if (name != null)
    {
        if (name.isEmpty() == false)
        {
            name_edit_text.setText(name);
        }
    }
    name_edit_text.addTextChangedListener(new TextWatcher()
    {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count)
        {
            invalidateOptionsMenu();
        }

        @Override
        public void afterTextChanged(Editable s) {}
    });

    // EditText Init Mod
    EditText init_mod_edit_text = (EditText) ally_layout_row.findViewById(R.id.profile_edit_ally_init_mod_edit_text);
    init_mod_edit_text.setTextSize(14.0f);
    init_mod_edit_text.setTextColor(Color.DKGRAY);
    if (initMod != null)
    {
        if (initMod.isEmpty() == false)
        {
            init_mod_edit_text.setText(initMod);
        }
    }

    // EditText Caster Level
    EditText caster_level_edit_text = (EditText) ally_layout_row.findViewById(R.id.profile_edit_ally_caster_level_edit_text);
    caster_level_edit_text.setTextSize(14.0f);
    caster_level_edit_text.setTextColor(Color.DKGRAY);
    if (casterLevel != null)
    {
        if (casterLevel.isEmpty() == false)
        {
            caster_level_edit_text.setText(casterLevel);
        }
    }

    // ImageButton Delete Ally Button
    ImageButton delete_button = (ImageButton) ally_layout_row.findViewById(R.id.profile_edit_delete_ally_button);
    delete_button.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            View parent_view = (View) v.getParent();
            if (parent_view != null)
            {
                mAllyLayout.removeView(parent_view);
            }
            if (mAllyLayout.getChildCount() == 0)
            {
                addAllyRowToLayout("", "", "");
            }
        }
    });

    // Add the Ally Row to the Ally Layout.
    mAllyLayout.addView(ally_layout_row);
}

Edit 1
There's an if statement in the activity's onCreate() that I failed to show when I first posted. if (allyLayout.getChildCount() <= 0) ...

Edit 2
Looking at this post gave me the idea to see what was happening in onRestoreInstanceState(Bundle savedInstanceState).  Surprisingly to me, overriding it and making it empty, took care of my problem.  I'm not sure if that's the most orthodox solution.

Body:
After this line :

mAllyLayout = (LinearLayout) findViewById(R.id.profile_edit_ally_layout);

Check if your linear layout has some views.

   if (mAllyLayout.getChildCount()>0){
    //add your views

    }

Update
If you don't want to handle data after rotation add this on your manifest:

<activity
            android:name="Your activity"
            android:configChanges="orientation|keyboardHidden|screenSize"/>


问:
Protractor in STS IDE -> Could not find update-config.json
Currently I have Protractor v.5.1.1, Node.js v.6.10.0

All protractor tests work in window console but when I try to run them from STS IDE I get below error. Of course i did 'webdriver-manager update' but it doesn't help at all. Does anyone has an idea how to resolve this problem?

Below the error respectively when I use or do not 'directConnect'

```<code>[22:21:48] I/launcher - Running 1 instances of WebDriver
[22:21:48] I/direct - Using ChromeDriver directly...
[22:21:48] E/direct - Error code: 135
[22:21:48] E/direct - Error message: Could not find update-config.json. Run    'webdriver-manager update' to download binaries.
[22:21:48] E/direct - Error: Could not find update-config.json. Run 'webdriver-manager update' to download binaries.
at IError  (D:\STS_workspace\jgh\node_modules\protractor\built\exitCodes.js:5:1)
at ProtractorError (D:\STS_workspace\jgh\node_modules\protractor\built\exitCodes.js:10:9)
at BrowserError (D:\STS_workspace\jgh\node_modules\protractor\built\exitCodes.js:51:9)
at Direct.getNewDriver (D:\STS_workspace\jgh\node_modules\protractor\built\driverProviders\direct.js:62:31)
at Runner.createBrowser (D:\STS_workspace\jgh\node_modules\protractor\built\runner.js:194:43)
at q.then.then (D:\STS_workspace\jgh\node_modules\protractor\built\runner.js:338:29)
at _fulfilled (D:\STS_workspace\jgh\node_modules\q\q.js:834:54)
at self.promiseDispatch.done (D:\STS_workspace\jgh\node_modules\q\q.js:863:30)
at Promise.promise.promiseDispatch (D:\STS_workspace\jgh\node_modules\q\q.js:796:13)
at D:\STS_workspace\jgh\node_modules\q\q.js:556:49
[22:21:48] E/launcher - Process exited with error code 135
</code>```

or

```<code>[21:19:23] I/launcher - Running 1 instances of WebDriver
[21:19:23] E/local - Error code: 135
[21:19:23] E/local - Error message: No update-config.json found. Run    'webdriver-manager update' to download binaries.
[21:19:23] E/local - Error: No update-config.json found. Run 'webdriver- manager update' to download binaries.
   at IError (D:\STS_workspace\jgh\node_modules\protractor\built\exitCodes.js:5:1)
   at ProtractorError (D:\STS_workspace\jgh\node_modules\protractor\built\exitCodes.js:10:9)
   at BrowserError (D:\STS_workspace\jgh\node_modules\protractor\built\exitCodes.js:51:9)
   at Local.addDefaultBinaryLocs_ (D:\STS_workspace\jgh\node_modules\protractor\built\driverProviders\local.js:40:23)
   at Local.setupDriverEnv (D:\STS_workspace\jgh\node_modules\protractor\built\driverProviders\local.js:81:14)
   at Local.setupEnv  (D:\STS_workspace\jgh\node_modules\protractor\built\driverProviders\driverProvider.js:110:34)
   at q.then (D:\STS_workspace\jgh\node_modules\protractor\built\runner.js:334:41)
   at _fulfilled (D:\STS_workspace\jgh\node_modules\q\q.js:834:54)
   at self.promiseDispatch.done    (D:\STS_workspace\jgh\node_modules\q\q.js:863:30)
   at Promise.promise.promiseDispatch     (D:\STS_workspace\jgh\node_modules\q\q.js:796:13)
[21:19:23] E/launcher - Process exited with error code 135
</code>```

My conf.js looks like:

```<code>var SpecReporter = require('jasmine-spec-reporter').SpecReporter;

exports.config = {
  //    directConnect:true,
  specs: ['spec4.js'],
 framework: 'jasmine2' ,

 onPrepare: function () {
  jasmine.getEnv().addReporter(new SpecReporter({
  spec: {
    displayStacktrace: true,
    displaySuccessesSummary: true,
    displayFailuresSummary: true,
    displayPendingSummary: true,
    displaySpecDuration: true,
      },

    }));
  },

  jasmineNodeOpts: {
    defaultTimeoutInterval: 25000,
    print: function () {},
},
</code>```

I don't have selenium folder in the path   node_modules/protractor/node_modules/webdriver-manager but I have package.json where I added "webdriver-update": "webdriver-manager update".
                                                                                This is the output of npm run webdriver-update:

```<code>    D:\STS_workspace\jgh>npm run webdriver-update
    npm WARN invalid config proxy="http:"
    npm WARN invalid config Must be a full url with 'http://'
    npm WARN invalid config proxy="http:"
    npm WARN invalid config Must be a full url with 'http://'
    npm ERR! Windows_NT 10.0.14393
    npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program     Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "webdriver-update"
    npm ERR! node v6.10.0
    npm ERR! npm  v3.10.10
    npm ERR! path D:\STS_workspace\jgh\package.json
    npm ERR! code ENOENT
    npm ERR! errno -4058
    npm ERR! syscall open
    npm ERR! enoent ENOENT: no such file or directory, open 'D:\STS_workspace\jgh\package.json'
    npm ERR! enoent ENOENT: no such file or directory, open 'D:\STS_workspace\jgh\package.json'
    npm ERR! enoent This is most likely not a problem with npm itself
    npm ERR! enoent and is related to npm not being able to find a file.
    npm ERR! enoent

npm ERR! Please include the following file with any support request:
npm ERR!     D:\STS_workspace\jgh\npm-debug.log
</code>```

答:
You just need to run this command and it fixes it - npm run webdriver-update it updates you webdriver in node_modules section under node_modules/protractor.

These 2 lines are the main culprits. Just try running that command and it should fix your issue.

```<code>[22:21:48] E/direct - Error message: Could not find update-config.json. Run 'webdriver-manager update' to download binaries.
[22:21:48] E/direct - Error: Could not find update-config.json. Run 'webdriver-manager update' to download binaries.
</code>```

Hope that helps!

Body:
Currently I have Protractor v.5.1.1, Node.js v.6.10.0

All protractor tests work in window console but when I try to run them from STS IDE I get below error. Of course i did 'webdriver-manager update' but it doesn't help at all. Does anyone has an idea how to resolve this problem?

Below the error respectively when I use or do not 'directConnect'

[22:21:48] I/launcher - Running 1 instances of WebDriver
[22:21:48] I/direct - Using ChromeDriver directly...
[22:21:48] E/direct - Error code: 135
[22:21:48] E/direct - Error message: Could not find update-config.json. Run    'webdriver-manager update' to download binaries.
[22:21:48] E/direct - Error: Could not find update-config.json. Run 'webdriver-manager update' to download binaries.
at IError  (D:\STS_workspace\jgh\node_modules\protractor\built\exitCodes.js:5:1)
at ProtractorError (D:\STS_workspace\jgh\node_modules\protractor\built\exitCodes.js:10:9)
at BrowserError (D:\STS_workspace\jgh\node_modules\protractor\built\exitCodes.js:51:9)
at Direct.getNewDriver (D:\STS_workspace\jgh\node_modules\protractor\built\driverProviders\direct.js:62:31)
at Runner.createBrowser (D:\STS_workspace\jgh\node_modules\protractor\built\runner.js:194:43)
at q.then.then (D:\STS_workspace\jgh\node_modules\protractor\built\runner.js:338:29)
at _fulfilled (D:\STS_workspace\jgh\node_modules\q\q.js:834:54)
at self.promiseDispatch.done (D:\STS_workspace\jgh\node_modules\q\q.js:863:30)
at Promise.promise.promiseDispatch (D:\STS_workspace\jgh\node_modules\q\q.js:796:13)
at D:\STS_workspace\jgh\node_modules\q\q.js:556:49
[22:21:48] E/launcher - Process exited with error code 135

or

[21:19:23] I/launcher - Running 1 instances of WebDriver
[21:19:23] E/local - Error code: 135
[21:19:23] E/local - Error message: No update-config.json found. Run    'webdriver-manager update' to download binaries.
[21:19:23] E/local - Error: No update-config.json found. Run 'webdriver- manager update' to download binaries.
   at IError (D:\STS_workspace\jgh\node_modules\protractor\built\exitCodes.js:5:1)
   at ProtractorError (D:\STS_workspace\jgh\node_modules\protractor\built\exitCodes.js:10:9)
   at BrowserError (D:\STS_workspace\jgh\node_modules\protractor\built\exitCodes.js:51:9)
   at Local.addDefaultBinaryLocs_ (D:\STS_workspace\jgh\node_modules\protractor\built\driverProviders\local.js:40:23)
   at Local.setupDriverEnv (D:\STS_workspace\jgh\node_modules\protractor\built\driverProviders\local.js:81:14)
   at Local.setupEnv  (D:\STS_workspace\jgh\node_modules\protractor\built\driverProviders\driverProvider.js:110:34)
   at q.then (D:\STS_workspace\jgh\node_modules\protractor\built\runner.js:334:41)
   at _fulfilled (D:\STS_workspace\jgh\node_modules\q\q.js:834:54)
   at self.promiseDispatch.done    (D:\STS_workspace\jgh\node_modules\q\q.js:863:30)
   at Promise.promise.promiseDispatch     (D:\STS_workspace\jgh\node_modules\q\q.js:796:13)
[21:19:23] E/launcher - Process exited with error code 135

My conf.js looks like:

var SpecReporter = require('jasmine-spec-reporter').SpecReporter;

exports.config = {
  //    directConnect:true,
  specs: ['spec4.js'],
 framework: 'jasmine2' ,

 onPrepare: function () {
  jasmine.getEnv().addReporter(new SpecReporter({
  spec: {
    displayStacktrace: true,
    displaySuccessesSummary: true,
    displayFailuresSummary: true,
    displayPendingSummary: true,
    displaySpecDuration: true,
      },

    }));
  },

  jasmineNodeOpts: {
    defaultTimeoutInterval: 25000,
    print: function () {},
},

I don't have selenium folder in the path   node_modules/protractor/node_modules/webdriver-manager but I have package.json where I added "webdriver-update": "webdriver-manager update".
                                                                                This is the output of npm run webdriver-update:

    D:\STS_workspace\jgh>npm run webdriver-update
    npm WARN invalid config proxy="http:"
    npm WARN invalid config Must be a full url with 'http://'
    npm WARN invalid config proxy="http:"
    npm WARN invalid config Must be a full url with 'http://'
    npm ERR! Windows_NT 10.0.14393
    npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program     Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "webdriver-update"
    npm ERR! node v6.10.0
    npm ERR! npm  v3.10.10
    npm ERR! path D:\STS_workspace\jgh\package.json
    npm ERR! code ENOENT
    npm ERR! errno -4058
    npm ERR! syscall open
    npm ERR! enoent ENOENT: no such file or directory, open 'D:\STS_workspace\jgh\package.json'
    npm ERR! enoent ENOENT: no such file or directory, open 'D:\STS_workspace\jgh\package.json'
    npm ERR! enoent This is most likely not a problem with npm itself
    npm ERR! enoent and is related to npm not being able to find a file.
    npm ERR! enoent

npm ERR! Please include the following file with any support request:
npm ERR!     D:\STS_workspace\jgh\npm-debug.log

Body:
You just need to run this command and it fixes it - npm run webdriver-update it updates you webdriver in node_modules section under node_modules/protractor.

These 2 lines are the main culprits. Just try running that command and it should fix your issue.

[22:21:48] E/direct - Error message: Could not find update-config.json. Run 'webdriver-manager update' to download binaries.
[22:21:48] E/direct - Error: Could not find update-config.json. Run 'webdriver-manager update' to download binaries.

Hope that helps!

ContentLicense: CC BY-SA 4.0


问:
How to load a woff2 font into IE with CSS?
I have IE11 on IE10 mode, and I want to load a css file. I have this

```<code>@font-face {
    font-family: celestesansbold;
    src: url('celestesanscomp-bold-webfont.woff2');
}
</code>```

And then in the console I see this

```<code>CSS3111: @font-face encountered unknown error.
celestesanscomp-bold-webfont.woff2
</code>```

And in the network tab I see

```<code>Name    Protocol    Method  Result  Content type    Received    Time    Initiator
.../celestesanscomp-bold-webfont.woff2  HTTP    GET 200 font/woff2  (from cache)    0 s
</code>```

And the don't does not load correctly on the page, the text does not change.

Does anyone know what's wrong?

However regular woff files work, but this is woff2.

Thanks

答:
IE doesn't support woff2. That's why you need to provide woff.

In fact, woff is the standard and it's all you need.

You only load woff2 because it provides better features for less bandwidth in browsers that do support it.

Older versions of IE used to need eot, but it's deprecated now.

However, providing more than one font type file does not mean the browser loads all of them. It stops loading them when it finds one it successfully activates. Which means their order is quite important.  You want to put the more modern/efficient ones first and the larger ones (fallbacks) last.
It should be: woff2, woff, eot, svg, ttf/otf.

Body:
I have IE11 on IE10 mode, and I want to load a css file. I have this

@font-face {
    font-family: celestesansbold;
    src: url('celestesanscomp-bold-webfont.woff2');
}

And then in the console I see this

CSS3111: @font-face encountered unknown error.
celestesanscomp-bold-webfont.woff2

And in the network tab I see

Name    Protocol    Method  Result  Content type    Received    Time    Initiator
.../celestesanscomp-bold-webfont.woff2  HTTP    GET 200 font/woff2  (from cache)    0 s

And the don't does not load correctly on the page, the text does not change.

Does anyone know what's wrong?

However regular woff files work, but this is woff2.

Thanks


问:
How to convert date to timestamp?
I want to convert date to timestamp, my input is 26-02-2012. I used

```<code>new Date(myDate).getTime();
</code>```

It says NaN.. Can any one tell how to convert this?

答:
this refactored code will do it

```<code>let toTimestamp = strDate => Date.parse(strDate)
</code>```

this works on all modern browsers except ie8-

Title: How to convert date to timestamp?

Body:
I want to convert date to timestamp, my input is 26-02-2012. I used

new Date(myDate).getTime();

It says NaN.. Can any one tell how to convert this?

Body:
this refactored code will do it

let toTimestamp = strDate => Date.parse(strDate)

this works on all modern browsers except ie8-


问:
Can't convert Expression<Int> to Expression<AnyObject>
I am using SQLite.swift library.

I have several Expressions,

```<code>let idColumn = Expression<Int>("id")
let nameColumn = Expression<String>("name")
</code>```

I would like to have a dictionary host them, So, I did:

```<code>let columns: [String: Expression<AnyObject>] = [
   "id": idColumn,
   "name": nameColumn
]
</code>```

But I get compiler error:

```<code>Cannot convert value of type 'Expression<Int>' to expected dictionary value type 'Expression<AnyObject>'
</code>```

Why is this error? Why Int type can’t be AnyObject?

I also tried Any instead of AnyObject:

```<code>let columns: [String: Expression<Any>] = [
       "id" : idColumn,
       "name": nameColumn
    ]
</code>```

Similar error shows:

```<code>Cannot convert value of type 'Expression<Int>' to expected dictionary value type 'Expression<Any>'
</code>```

I don't understand this... Could someone please explain to me?

答:
Naked Int and String types can be converted to AnyObject. But this does not apply when they are wrapped in a generic type: Expression<Int> can not be converted to Expression<AnyObject>. That's how Swift works today (Swift 4):

```<code>// OK
let i: Int = 1
let i2 = i as AnyObject

// Error: cannot convert value of type 'S<Int>' to type 'S<AnyObject>' in coercion
struct S<T> { }
let s = S<Int>()
let s2 = s as S<AnyObject>
</code>```

Besides, even if it would, the expressions you would extract from the dictionary would have lost their column type: you could not use them directly in SQLite.swift, as exemplified by your other question.

Body:
I am using SQLite.swift library.

I have several Expressions,

let idColumn = Expression<Int>("id")
let nameColumn = Expression<String>("name")

I would like to have a dictionary host them, So, I did:

let columns: [String: Expression<AnyObject>] = [
   "id": idColumn,
   "name": nameColumn
]

But I get compiler error:

Cannot convert value of type 'Expression<Int>' to expected dictionary value type 'Expression<AnyObject>'

Why is this error? Why Int type can’t be AnyObject?

I also tried Any instead of AnyObject:

let columns: [String: Expression<Any>] = [
       "id" : idColumn,
       "name": nameColumn
    ]

Similar error shows:

Cannot convert value of type 'Expression<Int>' to expected dictionary value type 'Expression<Any>'

I don't understand this... Could someone please explain to me?

Body:
Naked Int and String types can be converted to AnyObject. But this does not apply when they are wrapped in a generic type: Expression<Int> can not be converted to Expression<AnyObject>. That's how Swift works today (Swift 4):

// OK
let i: Int = 1
let i2 = i as AnyObject

// Error: cannot convert value of type 'S<Int>' to type 'S<AnyObject>' in coercion
struct S<T> { }
let s = S<Int>()
let s2 = s as S<AnyObject>

Besides, even if it would, the expressions you would extract from the dictionary would have lost their column type: you could not use them directly in SQLite.swift, as exemplified by your other question.


问:
Retrofit uploading a picture
I'm using Retrofit v.2.2.0 to upload a picture to my server but the server returns a null value stating no image has been uploaded. The logs shows the image is uploaded and the file name is correct when uploaded. What can be the problem yet it works in postman?

UploadProfilePicture.java

```<code>public class UploadProfilePicture extends ContextWrapper {

private GetOnUpload onUpload;
private File imageFile,filesDir,file;
private Uri fileUri;
private String profilePic = "profile_pic";
private String fileName;
private ParcelFileDescriptor parcelFileDescriptor;
private FileDescriptor fileDescriptor;
private  Bitmap profileImage;
private OutputStream os;
private OkHttpLogClientAPI okHttpLogClientAPI;
private GetOnUpload mInterfaceService;

public UploadProfilePicture(Context base) {
    super(base);

    okHttpLogClientAPI = new OkHttpLogClientAPI(getBaseContext());

    mInterfaceService = okHttpLogClientAPI.logger().create(GetOnUpload.class);

}

public void uploadPic(Uri fileUri,String fileName, final OnSetUploadProfilePic setOnUpload) {
    //Build Req estBodies for the map object and a MultipartBody.Part to encapsulate the prof_pic_drawer

    this.fileUri = fileUri;
    this.fileName = fileName;
    try {
        getBitmapFromUri();
    } catch (IOException e) {
        e.printStackTrace();
    }
    file = persistImage();

    RequestBody finalRequestBody = builder.build();
    RequestBody requestFile =
            RequestBody.create(MediaType.parse("multipart/form-data"), getBytesFromBitmap(profileImage));

    // MultipartBody.Part is used to send also the actual file name
    MultipartBody.Part body =
            MultipartBody.Part.createFormData("file", "avatar.jpg", requestFile);
        Call<ResponseUserModel> call = mInterfaceService.upload(body);

        call.enqueue(new Callback<ResponseUserModel>() {

            @Override
            public void onResponse(Call<Response> call, Response<Response> response) {

                if (response.isSuccessful()) {
                    setOnUpload.uploadMessage(response.body());

                } else {
                    Toast.makeText(getBaseContext(), getString(R.string.failed_to_upload), Toast.LENGTH_SHORT).show();
                }

            }

            @Override
            public void onFailure(Call<Response> call, Throwable t) {

                Toast.makeText(getBaseContext(), getString(R.string.failed_to_upload), Toast.LENGTH_SHORT).show();

            }
        });
    }
}

public static byte[] getBytesFromBitmap(Bitmap bitmap) {
    if (bitmap!=null) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
        return stream.toByteArray();
    }
    return null;
}

private MultipartBody.Part prepareFilePart() {

    //TODO: Use FileUtils to get the actual file by uri

    try {
        getBitmapFromUri();
        file = persistImage();

    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        RequestBody requestFile = RequestBody.create(
                MediaType.parse(getBaseContext().getContentResolver().getType(fileUri)), file);
            return MultipartBody.Part.createFormData("file", file.getName(), requestFile);

    } catch (NullPointerException e) {

        Toast.makeText(getBaseContext(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();

        return null;
    }

}

private RequestBody createPartFromString(String descriptionString) {
    return RequestBody.create(MultipartBody.FORM, descriptionString);
}

private void getBitmapFromUri() throws IOException {
    profileImage = MediaStore.Images.Media.getBitmap(this.getContentResolver(), fileUri);
}

private File persistImage() {
    filesDir = getFilesDir();
     imageFile = new File(filesDir, fileName + ".jpg");

    OutputStream os;
    try {
        os = new FileOutputStream(imageFile);
        profileImage.compress(Bitmap.CompressFormat.JPEG, 70, os);
        os.flush();
        os.close();
    } catch (Exception e) {
        Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
    }

    return imageFile;
}}
</code>```

GetOnUpload.java

```<code>public interface GetOnUpload {
 @Multipart
@POST(Constants.UPLOAD_URL)
Call<Response> upload(@Part MultipartBody.Part file);}
</code>```

Log

http://local.com/api/v1/avatar http/1.1
11-14 18:40:02.742 8851-9593/com.local.test D/OkHttp: Content-Type: multipart/form-data; boundary=d43da080-f2c3-4743-8cfd-9526cc0bd2f7
11-14 18:40:02.742 8851-9593/com.local.test D/OkHttp: Content-Length: 12424
11-14 18:40:02.743 8851-9593/com.local.test D/OkHttp: --d43da080-f2c3-4743-8cfd-9526cc0bd2f7
11-14 18:40:02.743 8851-9593/com.local.test D/OkHttp: Content-Disposition: form-data; name="file"; filename="avatar.jpg"
11-14 18:40:02.743 8851-9593/com.local.test D/OkHttp: Content-Type: multipart/form-data
11-14 18:40:02.743 8851-9593/com.local.test D/OkHttp: Content-Length: 12201
11-14 18:40:02.743 8851-9593/com.local.test D/OkHttp:
11-14 18:40:02.744 8851-9593/com.local.test D/OkHttp: --d43da080-f2c3-4743-8cfd-9526cc0bd2f7--
11-14 18:40:02.744 8851-9593/com.local.test D/OkHttp: --> END POST (12424-byte body)

11-14 18:40:03.332 8851-9593/com.local.test D/OkHttp: <-- 200 OK http://local.com/api/v1/avatar (587ms)
11-14 18:40:03.332 8851-9593/com.local.test D/OkHttp: Server: nginx/1.10.3 (Ubuntu)
11-14 18:40:03.332 8851-9593/com.local.test D/OkHttp: Content-Type: application/json
11-14 18:40:03.332 8851-9593/com.local.test D/OkHttp: Transfer-Encoding: chunked
11-14 18:40:03.332 8851-9593/com.local.test D/OkHttp: Connection: keep-alive
11-14 18:40:03.332 8851-9593/com.local.test D/OkHttp: Cache-Control: no-cache, private
11-14 18:40:03.332 8851-9593/com.local.test D/OkHttp: Date: Tue, 14 Nov 2017 15:40:03 GMT
11-14 18:40:03.332 8851-9593/com.local.test D/OkHttp: X-RateLimit-Limit: 60
11-14 18:40:03.332 8851-9593/com.local.test D/OkHttp: X-RateLimit-Remaining: 59
11-14 18:40:03.333 8851-9593/com.local.test D/OkHttp: {"user":"Failed","status":"Image file not uploaded"}

答:
It seems there is a problem with OKHttp so when posting a file and data to the server with retrofit use this format</p>

```<code> file = new File(fileUri.getPath());
        RequestBody fileBody = RequestBody.create(MediaType.parse("image/*"),file);
        RequestBody dataBody = RequestBody.create(MediaType.parse("text/plain"), "id");
        Call<Response> call = mInterfaceService.upload(fileBody,dataBody);

        call.enqueue(new Callback<Response>() {

            @Override
            public void onResponse(Call<Response> call, Response<Response> response) {

                if (response.isSuccessful()) {
                    setOnUpload.uploadMessage(response.body());

                    if(file.exists())
                        file.delete();
                } else {
                    Toast.makeText(getBaseContext(), getString(R.string.failed_to_upload), Toast.LENGTH_SHORT).show();
                }

            }

public interface GetOnUpload {

@Multipart
@POST(Constants.UPLOAD_URL)

Call<Response> upload(@Part("file\";filename=\"avatar.jpg\" ") RequestBody file,@Part("id")RequestBody user);

 }
</code>```

Title: Retrofit uploading a picture

Body:
I'm using Retrofit v.2.2.0 to upload a picture to my server but the server returns a null value stating no image has been uploaded. The logs shows the image is uploaded and the file name is correct when uploaded. What can be the problem yet it works in postman?

UploadProfilePicture.java

public class UploadProfilePicture extends ContextWrapper {

private GetOnUpload onUpload;
private File imageFile,filesDir,file;
private Uri fileUri;
private String profilePic = "profile_pic";
private String fileName;
private ParcelFileDescriptor parcelFileDescriptor;
private FileDescriptor fileDescriptor;
private  Bitmap profileImage;
private OutputStream os;
private OkHttpLogClientAPI okHttpLogClientAPI;
private GetOnUpload mInterfaceService;

public UploadProfilePicture(Context base) {
    super(base);

    okHttpLogClientAPI = new OkHttpLogClientAPI(getBaseContext());

    mInterfaceService = okHttpLogClientAPI.logger().create(GetOnUpload.class);

}

public void uploadPic(Uri fileUri,String fileName, final OnSetUploadProfilePic setOnUpload) {
    //Build Req estBodies for the map object and a MultipartBody.Part to encapsulate the prof_pic_drawer

    this.fileUri = fileUri;
    this.fileName = fileName;
    try {
        getBitmapFromUri();
    } catch (IOException e) {
        e.printStackTrace();
    }
    file = persistImage();

    RequestBody finalRequestBody = builder.build();
    RequestBody requestFile =
            RequestBody.create(MediaType.parse("multipart/form-data"), getBytesFromBitmap(profileImage));

    // MultipartBody.Part is used to send also the actual file name
    MultipartBody.Part body =
            MultipartBody.Part.createFormData("file", "avatar.jpg", requestFile);
        Call<ResponseUserModel> call = mInterfaceService.upload(body);

        call.enqueue(new Callback<ResponseUserModel>() {

            @Override
            public void onResponse(Call<Response> call, Response<Response> response) {

                if (response.isSuccessful()) {
                    setOnUpload.uploadMessage(response.body());

                } else {
                    Toast.makeText(getBaseContext(), getString(R.string.failed_to_upload), Toast.LENGTH_SHORT).show();
                }

            }

            @Override
            public void onFailure(Call<Response> call, Throwable t) {

                Toast.makeText(getBaseContext(), getString(R.string.failed_to_upload), Toast.LENGTH_SHORT).show();

            }
        });
    }
}

public static byte[] getBytesFromBitmap(Bitmap bitmap) {
    if (bitmap!=null) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
        return stream.toByteArray();
    }
    return null;
}

private MultipartBody.Part prepareFilePart() {

    //TODO: Use FileUtils to get the actual file by uri

    try {
        getBitmapFromUri();
        file = persistImage();

    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        RequestBody requestFile = RequestBody.create(
                MediaType.parse(getBaseContext().getContentResolver().getType(fileUri)), file);
            return MultipartBody.Part.createFormData("file", file.getName(), requestFile);

    } catch (NullPointerException e) {

        Toast.makeText(getBaseContext(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();

        return null;
    }

}

private RequestBody createPartFromString(String descriptionString) {
    return RequestBody.create(MultipartBody.FORM, descriptionString);
}

private void getBitmapFromUri() throws IOException {
    profileImage = MediaStore.Images.Media.getBitmap(this.getContentResolver(), fileUri);
}

private File persistImage() {
    filesDir = getFilesDir();
     imageFile = new File(filesDir, fileName + ".jpg");

    OutputStream os;
    try {
        os = new FileOutputStream(imageFile);
        profileImage.compress(Bitmap.CompressFormat.JPEG, 70, os);
        os.flush();
        os.close();
    } catch (Exception e) {
        Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
    }

    return imageFile;
}}

GetOnUpload.java

public interface GetOnUpload {
 @Multipart
@POST(Constants.UPLOAD_URL)
Call<Response> upload(@Part MultipartBody.Part file);}

Log

http://local.com/api/v1/avatar http/1.1
11-14 18:40:02.742 8851-9593/com.local.test D/OkHttp: Content-Type: multipart/form-data; boundary=d43da080-f2c3-4743-8cfd-9526cc0bd2f7
11-14 18:40:02.742 8851-9593/com.local.test D/OkHttp: Content-Length: 12424
11-14 18:40:02.743 8851-9593/com.local.test D/OkHttp: --d43da080-f2c3-4743-8cfd-9526cc0bd2f7
11-14 18:40:02.743 8851-9593/com.local.test D/OkHttp: Content-Disposition: form-data; name="file"; filename="avatar.jpg"
11-14 18:40:02.743 8851-9593/com.local.test D/OkHttp: Content-Type: multipart/form-data
11-14 18:40:02.743 8851-9593/com.local.test D/OkHttp: Content-Length: 12201
11-14 18:40:02.743 8851-9593/com.local.test D/OkHttp:
11-14 18:40:02.744 8851-9593/com.local.test D/OkHttp: --d43da080-f2c3-4743-8cfd-9526cc0bd2f7--
11-14 18:40:02.744 8851-9593/com.local.test D/OkHttp: --> END POST (12424-byte body)

11-14 18:40:03.332 8851-9593/com.local.test D/OkHttp: <-- 200 OK http://local.com/api/v1/avatar (587ms)
11-14 18:40:03.332 8851-9593/com.local.test D/OkHttp: Server: nginx/1.10.3 (Ubuntu)
11-14 18:40:03.332 8851-9593/com.local.test D/OkHttp: Content-Type: application/json
11-14 18:40:03.332 8851-9593/com.local.test D/OkHttp: Transfer-Encoding: chunked
11-14 18:40:03.332 8851-9593/com.local.test D/OkHttp: Connection: keep-alive
11-14 18:40:03.332 8851-9593/com.local.test D/OkHttp: Cache-Control: no-cache, private
11-14 18:40:03.332 8851-9593/com.local.test D/OkHttp: Date: Tue, 14 Nov 2017 15:40:03 GMT
11-14 18:40:03.332 8851-9593/com.local.test D/OkHttp: X-RateLimit-Limit: 60
11-14 18:40:03.332 8851-9593/com.local.test D/OkHttp: X-RateLimit-Remaining: 59
11-14 18:40:03.333 8851-9593/com.local.test D/OkHttp: {"user":"Failed","status":"Image file not uploaded"}

Body:
It seems there is a problem with OKHttp so when posting a file and data to the server with retrofit use this format

 file = new File(fileUri.getPath());
        RequestBody fileBody = RequestBody.create(MediaType.parse("image/*"),file);
        RequestBody dataBody = RequestBody.create(MediaType.parse("text/plain"), "id");
        Call<Response> call = mInterfaceService.upload(fileBody,dataBody);

        call.enqueue(new Callback<Response>() {

            @Override
            public void onResponse(Call<Response> call, Response<Response> response) {

                if (response.isSuccessful()) {
                    setOnUpload.uploadMessage(response.body());

                    if(file.exists())
                        file.delete();
                } else {
                    Toast.makeText(getBaseContext(), getString(R.string.failed_to_upload), Toast.LENGTH_SHORT).show();
                }

            }

public interface GetOnUpload {

@Multipart
@POST(Constants.UPLOAD_URL)

Call<Response> upload(@Part("file\";filename=\"avatar.jpg\" ") RequestBody file,@Part("id")RequestBody user);

 }


问:
Comparison of XSD Code Generators
I'm doing some research in code generation from xsd schema files.
My requirements:

Must generate C# 2.0 code (or above), using generic collections where needed.

Must generate comments from the xsd comments

Must generate fully serializable code.

Should be able to generate resuable basetypes when generating from multiple xsd's with the same includes.

(see also my other questions: How can I generate multiple classes from xsd’s with common includes? and How can I generate comments from xs:documentation tags in a wsdl?

I have found the following options:

Use xsd.exe (supplied with the SDK and Visual Studio)

XSDCodeGen from Daniel Cazzulino

Xsd2Code

CodeXS

XsdObjectGen by Microsoft

XSDClassGen (Seems to be missing in action)

Did I miss any? Because (1), (2) and (5) do not generate 2.0 code, and I have problems with serializing code from (3). What do you use when generating code?

答:
I believe XSD2Code is the best tool currently available (in 2011).

I recently went through the same process at work of analysing the available tools out there so i thought i would provide an updated answer that relates to VS2010.

Our main driver was that xsd.exe does not generate XML doc from the XSD annotations, which we wanted as we have hundreds of type definitions.  I tried all the tools listed above as well as others and most were either deprecated, unmaintained or unable to match the current functionality of xsd.exe available in VS2010.

Xsd2Code however is a superb tool and seems to be actively maintained.  It provides all the functionality that was listed above and a lot more - the CodePlex page also has great examples of how the various options affect output.

It also has tight VS integration, including context menu integration and a custom build tool (which means that if you reference the XSDs in your project and specify the custom tool, it will automatically update the code as you update the XSD).  All in all saved us a lot of work.

A quick summary of the other tools i looked at:

Dingo - Seems to be more aligned to Java

XSDCodeGen - More of a demo on how to write a custom build tool

CodeXS - Quite a good tool, but less integration, features and no longer maintained

XSDObjectGen - No longer maintained, less functionality than current xsd.exe

XSDClassGen - Could not locate it

OXM Library - Recommend looking at this project, maintained and great functionality

LINQ to XSD - Very cool project, but not what i was looking for

Addendum:
If you do decided to go ahead with XSD2Code, there are a number of issues i found working with the command-line tool.  In particular, there are some bugs with the argument processing that require some arguments to be in a certain order as well as some undocumented dependencies (eg - automatic parameters & .NET version are order specific and dependent).  The following are the steps i used to generate the code using XSD2Code and then cleanup the output - take the bits that apply to you as necessary:

Run the following batch file to generate the initial code, changing the paths to the correct locations:

```<code>@echo off

set XsdPath=C:\schemas
set OutPath=%XsdPath%\Code
set ExePath=C:\Progra~1\Xsd2Code
set Namespace=InsertNamespaceHere

echo.Starting processing XSD files ...
for /f %%a IN ('dir %XsdPath%\*.xsd /a-d /b /s') do call:ProcessXsd %%a

echo.Finished processing XSD files ...
echo.&pause&
goto:eof

:ProcessXsd
%ExePath%\Xsd2Code %~1 %Namespace% %XsdPath%\Code\%~n1%.cs /pl Net35 /if- /dc /sc /eit
echo.Processed %~n1
goto:eof
</code>```

Perform the following steps to tidy up the generated code, as necessary:

Regex replace - current project, case, whole word - [System.Runtime.Serialization.DataContractAttribute(Name:b=:b:q,:bNamespace:b=:b*{:q})] with [DataContract(Namespace = \1)]**

Replace - current project, case, whole word - [System.Runtime.Serialization.DataMemberAttribute()] with [DataMember]

Regex replace - current project, case, whole word - System.Nullable<{:w}> with \1?

Regex replace - open documents, case, whole word - {:w}TYPE with \1

Replace - open documents, case, whole word - System.DateTime with DateTime, then add missing using statements

Replace - open documents, case, whole word - [System.Xml.Serialization.XmlIgnoreAttribute()] with [XmlIgnore]

Replace - current project - System.Xml.Serialization.XmlArrayAttribute with XmlArray

Replace - current project - System.Xml.Serialization.XmlArrayItemAttribute with XmlArrayItem

Regex replace - current project - ,[:Wh]+/// <remarks/> with ,

OwnerDisplayName: Edoode

Title: Comparison of XSD Code Generators

Body:
I believe XSD2Code is the best tool currently available (in 2011).

I recently went through the same process at work of analysing the available tools out there so i thought i would provide an updated answer that relates to VS2010.

Our main driver was that xsd.exe does not generate XML doc from the XSD annotations, which we wanted as we have hundreds of type definitions.  I tried all the tools listed above as well as others and most were either deprecated, unmaintained or unable to match the current functionality of xsd.exe available in VS2010.

Xsd2Code however is a superb tool and seems to be actively maintained.  It provides all the functionality that was listed above and a lot more - the CodePlex page also has great examples of how the various options affect output.

It also has tight VS integration, including context menu integration and a custom build tool (which means that if you reference the XSDs in your project and specify the custom tool, it will automatically update the code as you update the XSD).  All in all saved us a lot of work.

A quick summary of the other tools i looked at:

Dingo - Seems to be more aligned to Java

XSDCodeGen - More of a demo on how to write a custom build tool

CodeXS - Quite a good tool, but less integration, features and no longer maintained

XSDObjectGen - No longer maintained, less functionality than current xsd.exe

XSDClassGen - Could not locate it

OXM Library - Recommend looking at this project, maintained and great functionality

LINQ to XSD - Very cool project, but not what i was looking for

Addendum:
If you do decided to go ahead with XSD2Code, there are a number of issues i found working with the command-line tool.  In particular, there are some bugs with the argument processing that require some arguments to be in a certain order as well as some undocumented dependencies (eg - automatic parameters & .NET version are order specific and dependent).  The following are the steps i used to generate the code using XSD2Code and then cleanup the output - take the bits that apply to you as necessary:

Run the following batch file to generate the initial code, changing the paths to the correct locations:

@echo off

set XsdPath=C:\schemas
set OutPath=%XsdPath%\Code
set ExePath=C:\Progra~1\Xsd2Code
set Namespace=InsertNamespaceHere

echo.Starting processing XSD files ...
for /f %%a IN ('dir %XsdPath%\*.xsd /a-d /b /s') do call:ProcessXsd %%a

echo.Finished processing XSD files ...
echo.&pause&
goto:eof

:ProcessXsd
%ExePath%\Xsd2Code %~1 %Namespace% %XsdPath%\Code\%~n1%.cs /pl Net35 /if- /dc /sc /eit
echo.Processed %~n1
goto:eof

Perform the following steps to tidy up the generated code, as necessary:

Regex replace - current project, case, whole word - [System.Runtime.Serialization.DataContractAttribute(Name:b=:b:q,:bNamespace:b=:b*{:q})] with [DataContract(Namespace = \1)]**

Replace - current project, case, whole word - [System.Runtime.Serialization.DataMemberAttribute()] with [DataMember]

Regex replace - current project, case, whole word - System.Nullable<{:w}> with \1?

Regex replace - open documents, case, whole word - {:w}TYPE with \1

Replace - open documents, case, whole word - System.DateTime with DateTime, then add missing using statements

Replace - open documents, case, whole word - [System.Xml.Serialization.XmlIgnoreAttribute()] with [XmlIgnore]

Replace - current project - System.Xml.Serialization.XmlArrayAttribute with XmlArray

Replace - current project - System.Xml.Serialization.XmlArrayItemAttribute with XmlArrayItem

Regex replace - current project - ,[:Wh]+/// &lt;remarks/&gt; with ,


问:
Finding max value using reduce
New to clojure with a java background. I have the following table and need to transform the table to a hash-map that maps products to the city that has the highest sale. For example, the output should look like:

```<code>{"Pencil": "Toronto"
"Bread": "Ottawa"}

(def table [
    {:product "Pencil"
    :city "Toronto"
    :year "2010"
    :sales "2653.00"}
    {:product "Pencil"
    :city "Oshawa"
    :year "2010"
    :sales "525.00"}
    {:product "Bread"
    :city "Toronto"
    :year "2010"
    :sales "136,264.00"}
    {:product "Bread"
    :city "Oshawa"
    :year "nil"
    :sales "242,634.00"}
    {:product "Bread"
    :city "Ottawa"
    :year "2011"
    :sales "426,164.00"}])
</code>```

This is what I have so far:

```<code>(reduce (fn [product-cities {:keys [product sales]}]
         (update-in product-cities [product] (fnil conj []) sales))
       {}
       table)
</code>```

This produces the outcome:

```<code>{"Bread"
["136,264.00"
"242,634.00"
"426,164.00"],
 "Pencil" ["2653.00" "525.00"]}
</code>```

How can i compare the sales of each city and and only keep the name of the city with the highest sales? Having a really tough time with this. Thanks

答:
A spinoff idea based on @leetwinski answer.
Idea is to use sort-by on sales' values as it's a bit more basic in the language. </p>

```<code>(defn process [table]
  (let [parseDouble #(Double/parseDouble (clojure.string/replace % #"," ""))
        parsedTable (for [a table] (update a :sales parseDouble))]
    (->> parsedTable
         (sort-by :sales)
         (group-by :product)
         vals
         (map (comp (juxt :product :city) last))
         (into {}))))
 (process table)
=>{"Bread" "Ottawa" "Pencil" "Toronto"}
</code>```

Title: Finding max value using reduce

Body:
New to clojure with a java background. I have the following table and need to transform the table to a hash-map that maps products to the city that has the highest sale. For example, the output should look like:

{"Pencil": "Toronto"
"Bread": "Ottawa"}

(def table [
    {:product "Pencil"
    :city "Toronto"
    :year "2010"
    :sales "2653.00"}
    {:product "Pencil"
    :city "Oshawa"
    :year "2010"
    :sales "525.00"}
    {:product "Bread"
    :city "Toronto"
    :year "2010"
    :sales "136,264.00"}
    {:product "Bread"
    :city "Oshawa"
    :year "nil"
    :sales "242,634.00"}
    {:product "Bread"
    :city "Ottawa"
    :year "2011"
    :sales "426,164.00"}])

This is what I have so far:

(reduce (fn [product-cities {:keys [product sales]}]
         (update-in product-cities [product] (fnil conj []) sales))
       {}
       table)

This produces the outcome:

{"Bread"
["136,264.00"
"242,634.00"
"426,164.00"],
 "Pencil" ["2653.00" "525.00"]}

How can i compare the sales of each city and and only keep the name of the city with the highest sales? Having a really tough time with this. Thanks

Body:
A spinoff idea based on @leetwinski answer.
Idea is to use sort-by on sales' values as it's a bit more basic in the language.

(defn process [table]
  (let [parseDouble #(Double/parseDouble (clojure.string/replace % #"," ""))
        parsedTable (for [a table] (update a :sales parseDouble))]
    (->> parsedTable
         (sort-by :sales)
         (group-by :product)
         vals
         (map (comp (juxt :product :city) last))
         (into {}))))
 (process table)
=>{"Bread" "Ottawa" "Pencil" "Toronto"}