问:
How to move from one fragment to another fragment on click of a RecyclerView item
I want to click an item on the RecyclerView (on a list fragment) and then go to the detail fragment with some data of the item.

I already knew how to use intent in activity, but I cannot find example to do with RecyclerView item.

```<code>//In first Activity
Intent intent = new Intent();
intent.setClass(this,SecondActivity.class);
Bundle bundle = new Bundle();
bundle.putDouble("height",height);
bundle.putString("sex",sex);
intent.putExtras(bundle);
startActivity(intent);

//In second Activity
Bundle bundle1=this.getIntent().getExtras();
String sex=bundle1.getString("sex");
double height=bundle1.getDouble("height");
</code>```

I am stuck in Adapter. Can anyone explain to me step by step?

Thanks!

My adapter code

```<code>public class GPAAdapter extends RecyclerView.Adapter<GPAAdapter.ViewHolder> {
private List<GPAModel> mGPAList;

class ViewHolder extends RecyclerView.ViewHolder {
    TextView lessonNameText;
    TextView lessonCodeText;
    TextView teacherNameText;
    TextView semesterNameText;
    View listView;
    public ViewHolder(View gpaItemView) {
        super(gpaItemView);
        lessonNameText = (TextView) gpaItemView.findViewById(R.id.gpa_lessonName);
        lessonCodeText = (TextView) gpaItemView.findViewById(R.id.gpa_lessonCode);
        teacherNameText = (TextView) gpaItemView.findViewById(R.id.gpa_teacherName);
        semesterNameText = (TextView) gpaItemView.findViewById(R.id.gpa_semesterName);
        listView = gpaItemView;
    }
}
public GPAAdapter(List<GPAModel> dataList) {
    mGPAList = dataList;
}

@Override
public  ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.gpa_item, parent, false);
    final ViewHolder holder = new ViewHolder(view);
    return holder;
}
public void setData(List<GPAModel> viewData) {
    mGPAList.clear();
    mGPAList.addAll(viewData);
    notifyDataSetChanged();
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    GPAModel data = mGPAList.get(position);
    holder.setIsRecyclable(true);
    holder.lessonNameText.setText(data.getLessonName());
    holder.lessonCodeText.setText(data.getLessonCode());
    holder.teacherNameText.setText(data.getTeacherName());
    holder.semesterNameText.setText(data.getSemesterName());

    //save position in itemView with TAG
    holder.itemView.setTag(position);
}
@Override
public int getItemCount() {
    return mGPAList.size();
}

//define interface
public static interface OnItemClickListener {
    void onItemClick(View view , int position);
}
private OnItemClickListener mOnItemClickListener = null;

//Alert: method does not override method from its superclass
@Override
public void onClick(View v) {
    if (mOnItemClickListener != null) {
        //getTag of position
        mOnItemClickListener.onItemClick(v,(int)v.getTag());
    }
}

public void setOnItemClickListener(OnItemClickListener listener) {
    this.mOnItemClickListener = listener;
}
</code>```

}

My list fragment

```<code>private FragmentManager manager;
private FragmentTransaction ft;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View gpaView = inflater.inflate(R.layout.fragment_gpa, container, false);
    RecyclerView gpaRecyclerView = (RecyclerView) gpaView.findViewById(R.id.gpa_list);
    LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
    gpaRecyclerView.setLayoutManager(layoutManager);
    GPAAdapter adapter = new GPAAdapter(getData());
    gpaRecyclerView.setAdapter(adapter);
    return gpaView;

    //how use .setArguments(bundle) in fragment?
    super.onCreate(savedInstanceState);
    manager = getFragmentManager();

    GPAAdapter.setOnItemClickListener(new OnItemClickListener(){
        @Override
        public void onItemClick(View view , int position){
            Toast.makeText(MainActivity.this, data[position], 600).show();
        }
    });
}

private List<GPAModel> getData() {
}
</code>```

答:
Call getFragmentManager on Recycler.Adapter is a bit hard for me. So I here choose send click message to a new Activity (for detail show).

Hope my code can help somebody.

My adapter code

```<code>public class GPAAdapter extends RecyclerView.Adapter<GPAAdapter.ViewHolder> {
private ArrayList<GPAModel> mGPAList;
Context context;

class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    TextView lessonNameText;
    TextView lessonCodeText;
    TextView teacherNameText;
    TextView semesterNameText;
    View listView;
    ArrayList<GPAModel> list = new ArrayList<GPAModel>();
    Context ctx;

    public ViewHolder(View gpaItemView, Context myCtx, ArrayList<GPAModel> myList) {
        super(gpaItemView);
        gpaItemView.setOnClickListener(this);
        this.list = myList;
        this.ctx = myCtx;
        lessonNameText = (TextView) gpaItemView.findViewById(R.id.gpa_lessonName);
        lessonCodeText = (TextView) gpaItemView.findViewById(R.id.gpa_lessonCode);
        teacherNameText = (TextView) gpaItemView.findViewById(R.id.gpa_teacherName);
        semesterNameText = (TextView) gpaItemView.findViewById(R.id.gpa_semesterName);
        listView = gpaItemView;
    }

    @Override
    public void onClick(View view) {
        int position = getAdapterPosition();
        GPAModel sendGPA = this.list.get(position);
        Intent intent = new Intent(this.ctx, GPADetail.class);
        intent.putExtra("lessonName", sendGPA.getLessonName());
        intent.putExtra("lessonCode", sendGPA.getLessonCode());
        intent.putExtra("creditPoint", sendGPA.getCreditPoint());
        intent.putExtra("teacherName", sendGPA.getTeacherName());
        intent.putExtra("semesterName", sendGPA.getSemesterName());
        intent.putExtra("totalStudentNumber", sendGPA.getTotalStudentNumber());
        //
        ArrayList<String> scoreValue = new ArrayList<String>();
        scoreValue = sendGPA.getScoreValue();
        intent.putExtra("scoreValue", scoreValue);
        //
        ArrayList<Float> studentCount = new ArrayList<Float>();
        studentCount = sendGPA.getStudentCount();
        intent.putExtra("studentCount",studentCount);
        this.ctx.startActivity(intent);

    }
}
public GPAAdapter(ArrayList<GPAModel> myList, Context myContext) {

    this.mGPAList = myList;
    this.context = myContext;
}
@Override
public  ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.gpa_item, parent, false);
    final ViewHolder holder = new ViewHolder(view, context, mGPAList);
    return holder;
}
public void setData(List<GPAModel> viewData) {
    mGPAList.clear();
    mGPAList.addAll(viewData);
    notifyDataSetChanged();
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    GPAModel data = mGPAList.get(position);
    holder.setIsRecyclable(true);
    holder.lessonNameText.setText(data.getLessonName());
    holder.lessonCodeText.setText(data.getLessonCode());
    holder.teacherNameText.setText(data.getTeacherName());
    holder.semesterNameText.setText(data.getSemesterName());
}
@Override
public int getItemCount() {
    return mGPAList.size();
}
</code>```

}

My list fragment

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View gpaView = inflater.inflate(R.layout.fragment_gpa, container, false);
    RecyclerView gpaRecyclerView = (RecyclerView) gpaView.findViewById(R.id.gpa_list);
    LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
    gpaRecyclerView.setLayoutManager(layoutManager);
    GPAAdapter adapter = new GPAAdapter(getData());
    gpaRecyclerView.setAdapter(adapter);
    return gpaView;

}

private List<GPAModel> getData() {
}
</code>```

Body:
I want to click an item on the RecyclerView (on a list fragment) and then go to the detail fragment with some data of the item.

I already knew how to use intent in activity, but I cannot find example to do with RecyclerView item.

//In first Activity
Intent intent = new Intent();
intent.setClass(this,SecondActivity.class);
Bundle bundle = new Bundle();
bundle.putDouble("height",height);
bundle.putString("sex",sex);
intent.putExtras(bundle);
startActivity(intent);

//In second Activity
Bundle bundle1=this.getIntent().getExtras();
String sex=bundle1.getString("sex");
double height=bundle1.getDouble("height");

I am stuck in Adapter. Can anyone explain to me step by step?

Thanks!

My adapter code

public class GPAAdapter extends RecyclerView.Adapter<GPAAdapter.ViewHolder> {
private List<GPAModel> mGPAList;

class ViewHolder extends RecyclerView.ViewHolder {
    TextView lessonNameText;
    TextView lessonCodeText;
    TextView teacherNameText;
    TextView semesterNameText;
    View listView;
    public ViewHolder(View gpaItemView) {
        super(gpaItemView);
        lessonNameText = (TextView) gpaItemView.findViewById(R.id.gpa_lessonName);
        lessonCodeText = (TextView) gpaItemView.findViewById(R.id.gpa_lessonCode);
        teacherNameText = (TextView) gpaItemView.findViewById(R.id.gpa_teacherName);
        semesterNameText = (TextView) gpaItemView.findViewById(R.id.gpa_semesterName);
        listView = gpaItemView;
    }
}
public GPAAdapter(List<GPAModel> dataList) {
    mGPAList = dataList;
}

@Override
public  ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.gpa_item, parent, false);
    final ViewHolder holder = new ViewHolder(view);
    return holder;
}
public void setData(List<GPAModel> viewData) {
    mGPAList.clear();
    mGPAList.addAll(viewData);
    notifyDataSetChanged();
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    GPAModel data = mGPAList.get(position);
    holder.setIsRecyclable(true);
    holder.lessonNameText.setText(data.getLessonName());
    holder.lessonCodeText.setText(data.getLessonCode());
    holder.teacherNameText.setText(data.getTeacherName());
    holder.semesterNameText.setText(data.getSemesterName());

    //save position in itemView with TAG
    holder.itemView.setTag(position);
}
@Override
public int getItemCount() {
    return mGPAList.size();
}

//define interface
public static interface OnItemClickListener {
    void onItemClick(View view , int position);
}
private OnItemClickListener mOnItemClickListener = null;

//Alert: method does not override method from its superclass
@Override
public void onClick(View v) {
    if (mOnItemClickListener != null) {
        //getTag of position
        mOnItemClickListener.onItemClick(v,(int)v.getTag());
    }
}

public void setOnItemClickListener(OnItemClickListener listener) {
    this.mOnItemClickListener = listener;
}

}

My list fragment

private FragmentManager manager;
private FragmentTransaction ft;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View gpaView = inflater.inflate(R.layout.fragment_gpa, container, false);
    RecyclerView gpaRecyclerView = (RecyclerView) gpaView.findViewById(R.id.gpa_list);
    LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
    gpaRecyclerView.setLayoutManager(layoutManager);
    GPAAdapter adapter = new GPAAdapter(getData());
    gpaRecyclerView.setAdapter(adapter);
    return gpaView;

    //how use .setArguments(bundle) in fragment?
    super.onCreate(savedInstanceState);
    manager = getFragmentManager();

    GPAAdapter.setOnItemClickListener(new OnItemClickListener(){
        @Override
        public void onItemClick(View view , int position){
            Toast.makeText(MainActivity.this, data[position], 600).show();
        }
    });
}

private List<GPAModel> getData() {
}

Body:
Call getFragmentManager on Recycler.Adapter is a bit hard for me. So I here choose send click message to a new Activity (for detail show).

Hope my code can help somebody.

My adapter code

public class GPAAdapter extends RecyclerView.Adapter<GPAAdapter.ViewHolder> {
private ArrayList<GPAModel> mGPAList;
Context context;

class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    TextView lessonNameText;
    TextView lessonCodeText;
    TextView teacherNameText;
    TextView semesterNameText;
    View listView;
    ArrayList<GPAModel> list = new ArrayList<GPAModel>();
    Context ctx;

    public ViewHolder(View gpaItemView, Context myCtx, ArrayList<GPAModel> myList) {
        super(gpaItemView);
        gpaItemView.setOnClickListener(this);
        this.list = myList;
        this.ctx = myCtx;
        lessonNameText = (TextView) gpaItemView.findViewById(R.id.gpa_lessonName);
        lessonCodeText = (TextView) gpaItemView.findViewById(R.id.gpa_lessonCode);
        teacherNameText = (TextView) gpaItemView.findViewById(R.id.gpa_teacherName);
        semesterNameText = (TextView) gpaItemView.findViewById(R.id.gpa_semesterName);
        listView = gpaItemView;
    }

    @Override
    public void onClick(View view) {
        int position = getAdapterPosition();
        GPAModel sendGPA = this.list.get(position);
        Intent intent = new Intent(this.ctx, GPADetail.class);
        intent.putExtra("lessonName", sendGPA.getLessonName());
        intent.putExtra("lessonCode", sendGPA.getLessonCode());
        intent.putExtra("creditPoint", sendGPA.getCreditPoint());
        intent.putExtra("teacherName", sendGPA.getTeacherName());
        intent.putExtra("semesterName", sendGPA.getSemesterName());
        intent.putExtra("totalStudentNumber", sendGPA.getTotalStudentNumber());
        //
        ArrayList<String> scoreValue = new ArrayList<String>();
        scoreValue = sendGPA.getScoreValue();
        intent.putExtra("scoreValue", scoreValue);
        //
        ArrayList<Float> studentCount = new ArrayList<Float>();
        studentCount = sendGPA.getStudentCount();
        intent.putExtra("studentCount",studentCount);
        this.ctx.startActivity(intent);

    }
}
public GPAAdapter(ArrayList<GPAModel> myList, Context myContext) {

    this.mGPAList = myList;
    this.context = myContext;
}
@Override
public  ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.gpa_item, parent, false);
    final ViewHolder holder = new ViewHolder(view, context, mGPAList);
    return holder;
}
public void setData(List<GPAModel> viewData) {
    mGPAList.clear();
    mGPAList.addAll(viewData);
    notifyDataSetChanged();
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    GPAModel data = mGPAList.get(position);
    holder.setIsRecyclable(true);
    holder.lessonNameText.setText(data.getLessonName());
    holder.lessonCodeText.setText(data.getLessonCode());
    holder.teacherNameText.setText(data.getTeacherName());
    holder.semesterNameText.setText(data.getSemesterName());
}
@Override
public int getItemCount() {
    return mGPAList.size();
}

}

My list fragment

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View gpaView = inflater.inflate(R.layout.fragment_gpa, container, false);
    RecyclerView gpaRecyclerView = (RecyclerView) gpaView.findViewById(R.id.gpa_list);
    LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
    gpaRecyclerView.setLayoutManager(layoutManager);
    GPAAdapter adapter = new GPAAdapter(getData());
    gpaRecyclerView.setAdapter(adapter);
    return gpaView;

}

private List<GPAModel> getData() {
}


来源: stackexchange

问:
Export SQL data to a predefined Excel printing format and put it on intranet
Previously, I created a SSRS report and set the report properties to landscape, tabloid and 17 x 11 printing format. When user goes online and ran the report and export it to Excel the predefined printing format did not take place. I do not think SSRS cannot invoke the Excel printing format. I need something that I can place Excel on intranet and can call a view or stored procedure for user to export it with my predefined printing format. Also on the report I have group by section and bold the line on each new group. Can this be done on Excel? Any recommendation? Thanks.</p>

答:
Instead of pushing the data into Excel via SSRS, you might consider pulling the data into a pre-formatted Excel sheet with Microsoft Query. The Excel file would sit somewhere on your intranet that a user can access, and when they open the file they can refresh the data: it does require a bit more training for the user.

Use Microsoft Query to retrieve external data

ContentLicense: CC BY-SA 3.0


问:
Upgrade to studio 3.0 is crashing my app with dalvik.system.BaseDexClassLoader.findClass
This is just happening after a migration from studio 2.x to studio 3.0 with android 4.4. Android 6 runs fine.
I googled this issue but didn't find crisp response. Just a particular app has this behavior. I have other apps which are fine.

The update process has broken something but what? Why is it impacting android 4.x only?

I tried clean sync, rebuild,restart studio, restart tablet, ...

here is my gradle:

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

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "com.narb.test"
        minSdkVersion 18
        targetSdkVersion 24
        versionName '3.2'
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        versionNameSuffix '-9-nov-2017'
        multiDexEnabled true
        versionCode 53
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile files('libs/commons-net-3.5.jar')
    compile 'com.android.support:appcompat-v7:26.1.0'
    compile 'com.android.support:support-v4:26.1.0'
    compile 'com.google.android.gms:play-services-maps:10.0.1'
    testCompile 'junit:junit:4.12'
    compile 'org.jsoup:jsoup:1.10.3'
}
</code>```

and the logcat:

```<code>java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.narb.test/com.narb.test.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "com.narb.test.MainActivity" on path: DexPathList[[zip file "/data/app/com.narb.test-29.apk"],nativeLibraryDirectories=[/data/app-lib/com.narb.test-29, /vendor/lib, /system/lib]]
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2470)
     at android.app.ActivityThread.access$900(ActivityThread.java:174)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1307)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:146)
     at android.app.ActivityThread.main(ActivityThread.java:5593)
     at java.lang.reflect.Method.invokeNative(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:515)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
     at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.narb.test.MainActivity" on path: DexPathList[[zip file "/data/app/com.narb.test-29.apk"],nativeLibraryDirectories=[/data/app-lib/com.narb.test-29, /vendor/lib, /system/lib]]
     at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:67)
     at java.lang.ClassLoader.loadClass(ClassLoader.java:497)
     at java.lang.ClassLoader.loadClass(ClassLoader.java:457)
     at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2296)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2470)
     at android.app.ActivityThread.access$900(ActivityThread.java:174)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1307)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:146)
     at android.app.ActivityThread.main(ActivityThread.java:5593)
     at java.lang.reflect.Method.invokeNative(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:515)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
     at dalvik.system.NativeStart.main(Native Method)
</code>```

and the manifest:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.narb.test">

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

    <application
        android:allowBackup="true"
        android:largeHeap="true"
        android:configChanges="keyboardHidden|screenSize"
        android:icon="@drawable/networksafe"
        android:label="test"
        android:logo="@drawable/networksafe"
        android:screenOrientation="portrait"
        android:supportsRtl="true"

        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service
            android:name=".vpn.services"
            android:enabled="true"
            android:exported="true"
            android:permission="android.permission.BIND_VPN_SERVICE">

            <intent-filter>
                <action android:name="android.Net.Services"/>
            </intent-filter>
        </service>
        <activity
            android:name=".Activities.Settings"
            android:windowSoftInputMode="stateHidden" />
        <activity android:name=".Activities.About" />
        <activity android:name=".Activities.History" />

        <service
            android:name=".Socket"
            android:exported="false" />

        <service
            android:name=".ServiceMonitoring"
            android:exported="false" />

        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/.
        -->
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity android:name=".Activities.RateMe"></activity>
    </application>

</manifest>
</code>```

答:
In your case, if you don't need multidex, then disabling it is the right solution. If you need it in the future, follow the instructions linked below to use the MultiDexApplication.

For context, there are two types of multidex, legacy and native. For devices API 21 and above, the platform just reads multiple dex files directly from the APK.

For devices before API 21, there is the multidex support library that patches the classloader to add in the extra dex files as part of an Application class. Anything that can be loaded before this happens needs to be in the main dex, and you need to use MultiDexApplication (or a subclass, or call MultiDex.install(this) from your Application onAtttachBaseContext)

Android studio 3.0 switched to creating the minimal main dex for debug builds, that is, only keeping the smallest set of files in the main dex. This is for build performance and to make these crashes reproducible, rather than it being luck if a class was included in the main dex or not.

In your case, your app fit in one dex in 2.3, but in 3.0 with the new minimal main dex behavior, that class was not in the main dex. However because you are not using the MultiDexApplication, the classloader is never patched, so the classes in the secondary dex file cannot be loaded.

For more information see https://developer.android.com/studio/build/multidex.html#mdex-gradle

Body:
This is just happening after a migration from studio 2.x to studio 3.0 with android 4.4. Android 6 runs fine.
I googled this issue but didn't find crisp response. Just a particular app has this behavior. I have other apps which are fine.

The update process has broken something but what? Why is it impacting android 4.x only?

I tried clean sync, rebuild,restart studio, restart tablet, ...

here is my gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "com.narb.test"
        minSdkVersion 18
        targetSdkVersion 24
        versionName '3.2'
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        versionNameSuffix '-9-nov-2017'
        multiDexEnabled true
        versionCode 53
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile files('libs/commons-net-3.5.jar')
    compile 'com.android.support:appcompat-v7:26.1.0'
    compile 'com.android.support:support-v4:26.1.0'
    compile 'com.google.android.gms:play-services-maps:10.0.1'
    testCompile 'junit:junit:4.12'
    compile 'org.jsoup:jsoup:1.10.3'
}

and the logcat:

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.narb.test/com.narb.test.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "com.narb.test.MainActivity" on path: DexPathList[[zip file "/data/app/com.narb.test-29.apk"],nativeLibraryDirectories=[/data/app-lib/com.narb.test-29, /vendor/lib, /system/lib]]
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2470)
     at android.app.ActivityThread.access$900(ActivityThread.java:174)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1307)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:146)
     at android.app.ActivityThread.main(ActivityThread.java:5593)
     at java.lang.reflect.Method.invokeNative(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:515)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
     at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.narb.test.MainActivity" on path: DexPathList[[zip file "/data/app/com.narb.test-29.apk"],nativeLibraryDirectories=[/data/app-lib/com.narb.test-29, /vendor/lib, /system/lib]]
     at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:67)
     at java.lang.ClassLoader.loadClass(ClassLoader.java:497)
     at java.lang.ClassLoader.loadClass(ClassLoader.java:457)
     at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2296)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2470)
     at android.app.ActivityThread.access$900(ActivityThread.java:174)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1307)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:146)
     at android.app.ActivityThread.main(ActivityThread.java:5593)
     at java.lang.reflect.Method.invokeNative(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:515)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
     at dalvik.system.NativeStart.main(Native Method)

and the manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.narb.test">

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

    <application
        android:allowBackup="true"
        android:largeHeap="true"
        android:configChanges="keyboardHidden|screenSize"
        android:icon="@drawable/networksafe"
        android:label="test"
        android:logo="@drawable/networksafe"
        android:screenOrientation="portrait"
        android:supportsRtl="true"

        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service
            android:name=".vpn.services"
            android:enabled="true"
            android:exported="true"
            android:permission="android.permission.BIND_VPN_SERVICE">

            <intent-filter>
                <action android:name="android.Net.Services"/>
            </intent-filter>
        </service>
        <activity
            android:name=".Activities.Settings"
            android:windowSoftInputMode="stateHidden" />
        <activity android:name=".Activities.About" />
        <activity android:name=".Activities.History" />

        <service
            android:name=".Socket"
            android:exported="false" />

        <service
            android:name=".ServiceMonitoring"
            android:exported="false" />

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity android:name=".Activities.RateMe"></activity>
    </application>

</manifest>


问:
Artifact has not been packaged yet
I am letting Maven copy some dependency files into a specific location for a GWT project. The maven-dependency-plugin does the job and so far it works. The only Problem is that I'm getting an error from Eclipse that says:

Artifact has not been packaged yet. When used on reactor artifact, copy should be executed after packaging: see MDEP-187.

I have tried to change the <phase> but that did not work. How can I get rid of that error and why is it there because Maven builds as intended.

<plugins>
  <plugin>
    <artifactId>maven-dependency-plugin</artifactId>
    <executions>
      <execution>
        <phase>install</phase>
        <goals>
          <goal>copy-dependencies</goal>
        </goals>
        <configuration>
          <outputDirectory>${project.basedir}/war/WEB-INF/lib</outputDirectory>
        </configuration>
      </execution>
    </executions>
  </plugin>
</plugins>
```

答:
I had to wrap plugins tag under pluginManagement to make the error go away.</p>

```<code><pluginManagement>
        <plugins>
            <plugin>
               <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>3.0.0</version>
                <executions>
                    <execution>
                        <id>copy-dependencies</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>../../lib/</outputDirectory>
                            <overWriteReleases>false</overWriteReleases>
                            <overWriteSnapshots>false</overWriteSnapshots>
                            <overWriteIfNewer>true</overWriteIfNewer>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
</pluginManagement>
</code>```

ContentLicense: CC BY-SA 4.0

Title: Artifact has not been packaged yet

Body:
I had to wrap plugins tag under pluginManagement to make the error go away.

<pluginManagement>
        <plugins>
            <plugin>
               <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>3.0.0</version>
                <executions>
                    <execution>
                        <id>copy-dependencies</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>../../lib/</outputDirectory>
                            <overWriteReleases>false</overWriteReleases>
                            <overWriteSnapshots>false</overWriteSnapshots>
                            <overWriteIfNewer>true</overWriteIfNewer>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
</pluginManagement>


问:
Location of OpenCV & haarcascade_frontalface_default.xml
I am working with image processing using OpenCV. I have installed OopenCV 3.3.0 in Conda. I would like to find out the full path where my OpenCV is installed and where haarcascade_frontalface_default.xml is located. Any help is appreciated. </p>

答: It's in the directory etc/haarcascades inside the OpenCV build directory


问:
How to bind Vue data to a dropdown
I am learning Vue, and can't tell what I have done wrong here.  Data is being returned from the server (5 records), but is not getting put into the <select>; all I get is a single option that says {{dept.DName}}

```<code><html>
<head><link href="Content/bootstrap.min.css" rel="stylesheet" />
    <meta charset="utf-8" />
    <title></title>
</head>
<body class="container">
<div>
    <select id="deptList">
        <option v-model="selected" v-for="dept in app.depts" v-bind:value="dept.Did">
            {{dept.DName}}
        </option>
    </select>
</div>
<script src="Scripts/jquery-1.9.1.min.js"></script>
<script src="Scripts/moment.min.js"></script>
<script src="https://unpkg.com/vue"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-resource@1.3.4"></script>
<script src="Scripts/vue-controller.js"></script>
<script src="Scripts/bootstrap.min.js"></script>
</body>
</html>
</code>```

Scripts/vue-controller.js contains:

```<code>var app = new Vue({
    data: {
        el: "body",
        depts: [],
        emps: [],
        selected: ""
    },
    methods: {
        getDepts: function () {
            console.log("I'm a little teapot");  // this appears in the log
            this.$http.get("/Dept/Index").then(function(response) {
                this.depts = response.data;
                console.log(this.depts);  //the expected data does appear in the log
                },
                function(error) {
                    console.log(error.statusText);
                });
        }
    },
    created: function () {
        this.getDepts();
    }
})
</code>```

I am a C# developer and so I am halfway sure I am messing up the this/that context stuff, but have been unable to figure out what is happening.

答:
There are several issues.

el is not a data property, it is a root property of the Vue definition object.

You should never bind to body. In fact, Vue will prevent it. Bind to an appropriate element in the content of the body.

v-model should be on the select.

You do not need app.depts. All data properties can be referenced by name in the template.

console.clear()

const departments = [
  {Did: 1, DName: "Department 1"},
  {Did: 2, DName: "Department 2"},
  {Did: 3, DName: "Department 3"},
]

var app = new Vue({
  el: "#app",

  data: {
    depts: [],
    emps: [],
    selected: ""
  },
  methods: {
    getDepts: function () {
      console.log("I'm a little teapot");  // this appears in the log
      this.$http.post("https://httpbin.org/post", departments).then(function(response) {
        this.depts = response.body.json;
      },
      function(error) {
        console.log(error.statusText);
      });
    }
  },
  created: function () {
    this.getDepts();
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.9/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/1.3.4/vue-resource.js"></script>
<div id="app">
      <select  v-model="selected" id="deptList">
        <option v-for="dept in depts" v-bind:value="dept.Did">
            {{dept.DName}}
        </option>
    </select>
    <hr>
    Selected Department: {{selected}}
</div></code>```

Note: I modified the ajax call so that it would work in this environment. Your code for the ajax portion looked fine assuming you are using VueResource.

Title: How to bind Vue data to a dropdown

Body:
I am learning Vue, and can't tell what I have done wrong here.  Data is being returned from the server (5 records), but is not getting put into the <select>; all I get is a single option that says {{dept.DName}}

<link href="Content/bootstrap.min.css" rel="stylesheet" />
    <meta charset="utf-8" />
    <title></title>

    <select id="deptList">
        <option v-model="selected" v-for="dept in app.depts" v-bind:value="dept.Did">
            {{dept.DName}}
        </option>
    </select>

Scripts/vue-controller.js contains:

var app = new Vue({
    data: {
        el: "body",
        depts: [],
        emps: [],
        selected: ""
    },
    methods: {
        getDepts: function () {
            console.log("I'm a little teapot");  // this appears in the log
            this.$http.get("/Dept/Index").then(function(response) {
                this.depts = response.data;
                console.log(this.depts);  //the expected data does appear in the log
                },
                function(error) {
                    console.log(error.statusText);
                });
        }
    },
    created: function () {
        this.getDepts();
    }
})

I am a C# developer and so I am halfway sure I am messing up the this/that context stuff, but have been unable to figure out what is happening.

Body:
There are several issues.

el is not a data property, it is a root property of the Vue definition object.

You should never bind to body. In fact, Vue will prevent it. Bind to an appropriate element in the content of the body.

v-model should be on the select.

You do not need app.depts. All data properties can be referenced by name in the template.

console.clear()

const departments = [
  {Did: 1, DName: "Department 1"},
  {Did: 2, DName: "Department 2"},
  {Did: 3, DName: "Department 3"},
]

var app = new Vue({
  el: "#app",

  data: {
    depts: [],
    emps: [],
    selected: ""
  },
  methods: {
    getDepts: function () {
      console.log("I'm a little teapot");  // this appears in the log
      this.$http.post("https://httpbin.org/post", departments).then(function(response) {
        this.depts = response.body.json;
      },
      function(error) {
        console.log(error.statusText);
      });
    }
  },
  created: function () {
    this.getDepts();
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.9/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/1.3.4/vue-resource.js"></script>
<div id="app">
      <select  v-model="selected" id="deptList">
        <option v-for="dept in depts" v-bind:value="dept.Did">
            {{dept.DName}}
        </option>
    </select>
    <hr>
    Selected Department: {{selected}}
</div>

Note: I modified the ajax call so that it would work in this environment. Your code for the ajax portion looked fine assuming you are using VueResource.


问:
Javascript and Python - Best communication method
I am trying to make a html/javascript controlled raspberry pi robot.

So far, I have installed a LAMP server and I am hosting a local webpage with buttons which trigger events and sends commands to my robot via AJAX. AJAX calls a php script which calls a python script (no CGI) to control the robot.

This solution is currently working for me and I can control my raspberry pi hardware from html and simple send data back and forth.

Now what I want to do is, on my web page, have an on/off button which initializes and shuts down the robot, as well as having other events (currently measuring tilt angles from an accelerometer in an android device) to control the speed of the robot. This is where I am getting confused by the procedure of how things will work.

When I make an AJAX call to start the robot, that ajax call does not close until the python script ends (robot shuts off). So I have a python script running (start.py) which contains my robot object where the methods for changing the speed are stored. If I have seperate events in JS to change the speed (sends a call to changespeed.py), how can I change the properties of an object which is stored in a  different python script (start.py) that is already running (See figure below)?

Possible solutions I have thought of thus far:

1) store the object somewhere in memory. Perhaps as a python object, or store its properties in a SQL database. This way, changespeed.py (or Javascript directly) can change the speed properties in that memory, and start.py can continuously read them.

2) Rather than having the new speed values sent to python through AJAX, let python try to retrieve the values from javascript variables. in other words, instead of javascript giving data to python, have python take the data from javascript (scraping?).

3) abandon my current method of having javascript and python communicate through AJAX and php, and set up a websocket to exchange data. I dont know how this works quite yet but it may be the solution I need.

4) I also have not done any programming with interrupts and I dont know much about it. Is it possible to have my main script running and when the speed needs to change, I can send an interrupt at any moment?

I am sorry if my question is a little vague or wordy. I have a lot going on in my head right now. Let me know if it is unclear. Thank you.

TLDR: what is the best way to have javascript execute python scripts and then feed data to that script asynchronously

Map of operations

答:
I have successfully set up a websocket between my webpage and my robot using Flask-socketIO. I am now able to control my robot using the accelerometer in my android phone, but the response from the robot is way too slow. sometimes it takes up to 2 seconds for the robot to respond to a command from my phone. I believe part of the issue is that my robot is connected to my WLAN through a wifi extender in my house. So rather than passing data through the wifi extender, to the router, back through the extender, and finally to the robot, I am planning on using my 2nd wifi antenna as an access point, and connect to the robot directly.

Eventually I plan on getting into android app development (I want to connect my 2nd smartphone to the robot via USB and have access to the accelerometer, magnetometer, GPS, and camera). Once I do, I will look into connecting my phone and robot via bluetooth rather than websocket.

I still dont know if this is the best method, but this is my solution at the moment.


问:
How to import data into a varray using sqlldr
I am trying to import data into Oracle database using sqlldr.

I am using this documentation, but not successfully: sqlldr and sqlldr2

Decribing what I am doing:

create the varray type and the table:

```<code>CREATE OR REPLACE TYPE fv_integer_varray_12 AS VARRAY(12) OF INTEGER NOT NULL;

CREATE OR REPLACE TYPE VC_Array_MInteger_12 AS Object (
  fv_array fv_integer_varray_12,
  MEMBER FUNCTION   typeDimension   RETURN NUMBER ,
  MEMBER FUNCTION typeName RETURN VARCHAR2);
/

CREATE TABLE fv_varray_12 (
id NUMBER,
fv fv_integer_varray_12,
PRIMARY KEY (id)
);
</code>```

Create the control file:

```<code>options (errors=9999999, rows=5)
load data
 characterset WE8MSWIN1252
 infile '<path>'
 badfile '<path>'
 discardfile '<path>'
 into table fv_varray_12
 fields terminated by " "
( id, fv VARRAY COUNT(12) (fv))
</code>```

The data to be load is:

```<code>8 18 29 38 9 16 15 14 16 18 16 13 15
9 22 31 32 8 13 18 10 15 18 16 13 13
</code>```

When I try to load it through the command:

```<code>sqlldr user/pass control=imp_fv_12dim.ctl
</code>```

I get the error:

SQL*Loader-403: Referenced column  not present in table FV_VARRAY_12.

But it is not true as both the id and fv columns are there.

There must be something wrong in my control file. How can I fix it?

答:
You are just missing the keyword CONSTANT:

```<code>fv VARRAY COUNT(CONSTANT 12) (fv)
</code>```

That is missing from the example in the documentation (but then their data also look odd); but it is shown as required in the count_spec syntax diagram, which is linked to from the 12c documentaion on loading VARRAYs - but is also available in earlier versions of the documentation too..

With your sample data and just that modification to the control file:

```<code>options (errors=9999999, rows=5)
load data
characterset WE8MSWIN1252
infile 'imp_fv_12dim.dat'
badfile 'imp_fv_12dim.bad'
discardfile 'imp_fv_12dim.dis'
into table fv_varray_12
fields terminated by " "
( id,
  fv VARRAY COUNT(CONSTANT 12) (fv)
)
</code>```

then it works:

```<code>> sqlldr user/pass control=imp_fv_12dim.ctl

SQL*Loader: Release 11.2.0.4.0 - Production on Mon Dec 4 17:41:04 2017

Copyright (c) 1982, 2011, Oracle and/or its affiliates.  All rights reserved.

Commit point reached - logical record count 2
</code>```

And querying shows the data:

```<code>column fv format a80
select * from fv_varray_12;

        ID FV
---------- --------------------------------------------------------------------------------
         8 FV_INTEGER_VARRAY_12(18, 29, 38, 9, 16, 15, 14, 16, 18, 16, 13, 15)
         9 FV_INTEGER_VARRAY_12(22, 31, 32, 8, 13, 18, 10, 15, 18, 16, 13, 13)
</code>```

Body:
I am trying to import data into Oracle database using sqlldr.

I am using this documentation, but not successfully: sqlldr and sqlldr2

Decribing what I am doing:

create the varray type and the table:

CREATE OR REPLACE TYPE fv_integer_varray_12 AS VARRAY(12) OF INTEGER NOT NULL;

CREATE OR REPLACE TYPE VC_Array_MInteger_12 AS Object (
  fv_array fv_integer_varray_12,
  MEMBER FUNCTION   typeDimension   RETURN NUMBER ,
  MEMBER FUNCTION typeName RETURN VARCHAR2);
/

CREATE TABLE fv_varray_12 (
id NUMBER,
fv fv_integer_varray_12,
PRIMARY KEY (id)
);

Create the control file:

options (errors=9999999, rows=5)
load data
 characterset WE8MSWIN1252
 infile '<path>'
 badfile '<path>'
 discardfile '<path>'
 into table fv_varray_12
 fields terminated by " "
( id, fv VARRAY COUNT(12) (fv))

The data to be load is:

8 18 29 38 9 16 15 14 16 18 16 13 15
9 22 31 32 8 13 18 10 15 18 16 13 13

When I try to load it through the command:

sqlldr user/pass control=imp_fv_12dim.ctl

I get the error:

SQL*Loader-403: Referenced column  not present in table FV_VARRAY_12.

But it is not true as both the id and fv columns are there.

There must be something wrong in my control file. How can I fix it?

Body:
You are just missing the keyword CONSTANT:

fv VARRAY COUNT(CONSTANT 12) (fv)

That is missing from the example in the documentation (but then their data also look odd); but it is shown as required in the count_spec syntax diagram, which is linked to from the 12c documentaion on loading VARRAYs - but is also available in earlier versions of the documentation too..

With your sample data and just that modification to the control file:

options (errors=9999999, rows=5)
load data
characterset WE8MSWIN1252
infile 'imp_fv_12dim.dat'
badfile 'imp_fv_12dim.bad'
discardfile 'imp_fv_12dim.dis'
into table fv_varray_12
fields terminated by " "
( id,
  fv VARRAY COUNT(CONSTANT 12) (fv)
)

then it works:

> sqlldr user/pass control=imp_fv_12dim.ctl

SQL*Loader: Release 11.2.0.4.0 - Production on Mon Dec 4 17:41:04 2017

Copyright (c) 1982, 2011, Oracle and/or its affiliates.  All rights reserved.

Commit point reached - logical record count 2

And querying shows the data:

column fv format a80
select * from fv_varray_12;

        ID FV
---------- --------------------------------------------------------------------------------
         8 FV_INTEGER_VARRAY_12(18, 29, 38, 9, 16, 15, 14, 16, 18, 16, 13, 15)
         9 FV_INTEGER_VARRAY_12(22, 31, 32, 8, 13, 18, 10, 15, 18, 16, 13, 13)


问:
R - Create categorical variable based on increase or decrease in continuous variable
I'm trying to create a categorical variable from a continuous variable. I want to assign a 0 if the value decreased from the previous observation and a 1 if the variable increased from the previous observation.

This is in R

答:
You can use diff to take the difference between successive entries and then just test whether the difference is positive or negative.

```<code>## Sample data
Continuous = rnorm(20)

CAT = c(0, as.numeric(diff(Continuous) > 0))
</code>```

Body:
You can use diff to take the difference between successive entries and then just test whether the difference is positive or negative.

## Sample data
Continuous = rnorm(20)

CAT = c(0, as.numeric(diff(Continuous) > 0))


问:
How to access an array when it is within an arraylist?
The overall goal of what I'm trying to do is to compare a string to index 0 of an array (that is held within an arraylist), and if the strings are the same (ignoring case), call a method that matches the case of the string to the translated word (held at index 1 of the array inside an arraylist). When I run this code and I print out the contents of my translated arraylist, I get all "no match" characters. I'm assuming this is because I'm not accessing the index I want in the correct manner. Please help!

```<code>public static String translate(String word, ArrayList<String[]> wordList) {
    if (word == "." || word == "!" || word == ";" || word == ":") {
        return word;
    }
    for (int i = 0; i < wordList.size(); i++) {
            String origWord = wordList.get(i)[0];
            String transWord = wordList.get(i)[1];

            if (word.equalsIgnoreCase(origWord)) { //FIXME may need to change if you need to switch from translated to original
                String translated = matchCase(word, transWord);
                return translated;
            }
    }
    String noMatch = Character.toString(Config.LINE_CHAR);

    return noMatch;
}
</code>```

Sample Data and expected result

word = "hello"

wordList.get(i)[0] = "Hello"

wordList.get(i)[1] = "Hola"

(word and wordList.get(i)[0] match, so the next step is executed)

match case method is called and returns the translated word with the same case as the original word ->

translated = "hola"

returns the translated word.

(the for loop iterates through the entire wordList until it finds a match, then it calls the translate method)

**

Match Case's Code

```<code> public static String matchCase(String template, String original) {
    String matched = "";
    if (template.length() > original.length()) {

        for (int i = 1; i <= original.length(); i++) {
            if (template.charAt(i-1) >= 'a' &&  template.charAt(i-1) <= 'z') {

                if (i == original.length()) {

                matched +=  original.substring(original.length() - 1).toLowerCase();

                }
                else {

                    matched += original.substring((i-1), i).toLowerCase();
                }

            }
            else if (template.charAt(i-1) >= 'A' && template.charAt(i-1) <= 'Z') {
                if (i == original.length()) {

                    matched += original.substring(original.length() - 1).toUpperCase();

                }
                else {

                    matched +=  original.substring((i-1), i).toUpperCase();

                }
            }
        }
        return matched;
     }
     else if (template.length() < original.length()) {
         int o;
            original.toLowerCase();
            for (int i = 1; i <= template.length(); i++) {
                if (template.charAt(i-1) >= 'a' &&  template.charAt(i-1) <= 'z') {
                    if (i == template.length()) {
                        matched += original.substring(original.length() - 1).toLowerCase();
                    }
                    else {
                        matched += original.substring((i-1), i).toLowerCase();
                    }
                }
                else if (template.charAt(i-1) >= 'A' && template.charAt(i-1) <= 'Z') {
                    if (i == template.length()) {
                        matched += original.substring(original.length() - 1).toUpperCase();
                    }
                    else {
                        matched += original.substring((i-1), i).toUpperCase();
                    }
                }
                String newMatched = matched + original.substring(i, original.length() - 1);
                matched = newMatched;
                newMatched = "";
            }

            return matched;
     }

   return original;
}
</code>```

答:
I have tested your code and it works rather well with the example you have provided. I cannot help for your bug.

There are however some bugs to notify and improvement to suggest:

matchCase fails when template is shorter than the translated word.

Never compare strings with ==. Use the equals method and look why .

This is not really important but why is noMatch always computed. Why don't you declare it as a constant once?

public static final String NO_MATCH = String.valueOf(Config.LINE_CHAR);

More importantly I think that matchCase is not really pertinent by design and is over complicated. I think that You should just determine if the word to translate is all lower case or upper case or with the first letter in uppercase and the following letters in lower case. What you do (comparing the case letter by letter) is not really pertinent when the length is different.

When you consider a single character, use charAt instead of substringit is simpler and faster.

You also might have a look a regex to analyze your Strings.

Have you considered Maps for your translation lookup?

...

Body:
The overall goal of what I'm trying to do is to compare a string to index 0 of an array (that is held within an arraylist), and if the strings are the same (ignoring case), call a method that matches the case of the string to the translated word (held at index 1 of the array inside an arraylist). When I run this code and I print out the contents of my translated arraylist, I get all "no match" characters. I'm assuming this is because I'm not accessing the index I want in the correct manner. Please help!

public static String translate(String word, ArrayList<String[]> wordList) {
    if (word == "." || word == "!" || word == ";" || word == ":") {
        return word;
    }
    for (int i = 0; i < wordList.size(); i++) {
            String origWord = wordList.get(i)[0];
            String transWord = wordList.get(i)[1];

            if (word.equalsIgnoreCase(origWord)) { //FIXME may need to change if you need to switch from translated to original
                String translated = matchCase(word, transWord);
                return translated;
            }
    }
    String noMatch = Character.toString(Config.LINE_CHAR);

    return noMatch;
}

Sample Data and expected result

word = "hello"

wordList.get(i)[0] = "Hello"

wordList.get(i)[1] = "Hola"

(word and wordList.get(i)[0] match, so the next step is executed)

match case method is called and returns the translated word with the same case as the original word ->

translated = "hola"

returns the translated word.

(the for loop iterates through the entire wordList until it finds a match, then it calls the translate method)

**

Match Case's Code

 public static String matchCase(String template, String original) {
    String matched = "";
    if (template.length() > original.length()) {

        for (int i = 1; i <= original.length(); i++) {
            if (template.charAt(i-1) >= 'a' &&  template.charAt(i-1) <= 'z') {

                if (i == original.length()) {

                matched +=  original.substring(original.length() - 1).toLowerCase();

                }
                else {

                    matched += original.substring((i-1), i).toLowerCase();
                }

            }
            else if (template.charAt(i-1) >= 'A' && template.charAt(i-1) <= 'Z') {
                if (i == original.length()) {

                    matched += original.substring(original.length() - 1).toUpperCase();

                }
                else {

                    matched +=  original.substring((i-1), i).toUpperCase();

                }
            }
        }
        return matched;
     }
     else if (template.length() < original.length()) {
         int o;
            original.toLowerCase();
            for (int i = 1; i <= template.length(); i++) {
                if (template.charAt(i-1) >= 'a' &&  template.charAt(i-1) <= 'z') {
                    if (i == template.length()) {
                        matched += original.substring(original.length() - 1).toLowerCase();
                    }
                    else {
                        matched += original.substring((i-1), i).toLowerCase();
                    }
                }
                else if (template.charAt(i-1) >= 'A' && template.charAt(i-1) <= 'Z') {
                    if (i == template.length()) {
                        matched += original.substring(original.length() - 1).toUpperCase();
                    }
                    else {
                        matched += original.substring((i-1), i).toUpperCase();
                    }
                }
                String newMatched = matched + original.substring(i, original.length() - 1);
                matched = newMatched;
                newMatched = "";
            }

            return matched;
     }

   return original;
}


问:
How to loop over JSON objects in a ruby function
I want to loop over JSON objects and check for a condition in a ruby function.
I have 2 classes:

Class A

Class B

Class A has a function that reads the JSON file.
This function returns an array of hash objects representing the data:

```<code>def self.data
  path = 'data/songs.json'
  file = File.read(path)
  JSON.parse(file)
end
</code>```

I want to use this method in class B to access the songs.json objects and check if a certain condition is true.

Here is the code for class B:

```<code>def mention_count
  count = 0
  array= []
  array.push(Song.data)
  array.each do |i|
    if(@name === i[:name])
      count +=1;
    end
  end
end
</code>```

Th JSON file has a key called name, and I am checking if it is identical to the class B variable name. If true the count variable is increased and returned.

The JSON file is an array of JSON object and it looks like this

```<code>[
{
"Name": "Bad",
"Artist": "Michael Jackson",
"Record": 825,
},
{
"Name": "Thriller",
"Artist": "Michael Jackson",
"Record": 846,
}]
</code>```

I am not getting the expected result. The array.push(Song.data) is only adding the first object of the JSON file and not the whole JSON file.

How do I call the method Song.data in class B and loop over the JSON objects?

答:
Ruby has a lot of convenience methods that make this sort of thing really simple:

```<code>def mention_count
  Song.data.map do |song|
    song['Name']
  end.count(@name)
end
</code>```

Here the map method is used to extract the song name, then count looks for how many instances of that particular name there are. You can also do it this way:

```<code>def mention_count
  Song.data.count do |song|
    @name == song['Name']
  end
end
</code>```

Where that counts songs with matching names more directly.

Note that in your original code you're doing this:

```<code>array= []
array.push(Song.data)
</code>```

This creates a new array, then adds the array to it as an element. If you wanted to add the elements of Song.data to the end of the array you'd have to do this:

```<code>array += Song.data
</code>```

Which concatenates it. In any case this is irrelevant since you never modify array so you can just use Song.data directly.

Body:
I want to loop over JSON objects and check for a condition in a ruby function.
I have 2 classes:

Class A

Class B

Class A has a function that reads the JSON file.
This function returns an array of hash objects representing the data:

def self.data
  path = 'data/songs.json'
  file = File.read(path)
  JSON.parse(file)
end

I want to use this method in class B to access the songs.json objects and check if a certain condition is true.

Here is the code for class B:

def mention_count
  count = 0
  array= []
  array.push(Song.data)
  array.each do |i|
    if(@name === i[:name])
      count +=1;
    end
  end
end

Th JSON file has a key called name, and I am checking if it is identical to the class B variable name. If true the count variable is increased and returned.

The JSON file is an array of JSON object and it looks like this

[
{
"Name": "Bad",
"Artist": "Michael Jackson",
"Record": 825,
},
{
"Name": "Thriller",
"Artist": "Michael Jackson",
"Record": 846,
}]

I am not getting the expected result. The array.push(Song.data) is only adding the first object of the JSON file and not the whole JSON file.

How do I call the method Song.data in class B and loop over the JSON objects?

Body:
Ruby has a lot of convenience methods that make this sort of thing really simple:

def mention_count
  Song.data.map do |song|
    song['Name']
  end.count(@name)
end

Here the map method is used to extract the song name, then count looks for how many instances of that particular name there are. You can also do it this way:

def mention_count
  Song.data.count do |song|
    @name == song['Name']
  end
end

Where that counts songs with matching names more directly.

Note that in your original code you're doing this:

array= []
array.push(Song.data)

This creates a new array, then adds the array to it as an element. If you wanted to add the elements of Song.data to the end of the array you'd have to do this:

array += Song.data

Which concatenates it. In any case this is irrelevant since you never modify array so you can just use Song.data directly.


问:
java.util.zip.ZipException: duplicate entry?
I am new to Android development and am currently seeing below error when I try to generate signed apk. I don't understand what am I missing.

Here's what my app build gradle looks like in Android Studio

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

repositories {
    jcenter()
    maven {
        url 'http://maven.localytics.com/public'
    }
}

android {
    dexOptions {
        jumboMode true
        javaMaxHeapSize "4g"
        preDexLibraries = false
    }
    configurations {
        all*.exclude group: 'org.apache.commons'
        compile.exclude group: 'org.jetbrains', module: 'annotations'
    }
    compileSdkVersion 25
    buildToolsVersion '26.0.2'
    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 25
        vectorDrawables.useSupportLibrary = true
        multiDexEnabled = true
    }
}

dependencies {
    compile 'javax.xml.ws:jaxws-api:2.3.0'
    compile 'javax.xml.bind:jaxb-api:2.3.0'
    compile 'com.android.support:multidex:1.0.2'
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile fileTree(include: 'HockeySDK*.jar', dir: 'libs')
    compile fileTree(include: 'bolts-*.jar', dir: 'libs')
    compile 'com.parse:parse-android:1.10.3'
    compile "com.android.support:appcompat-v7:25.4.0"
    compile "com.android.support:design:25.4.0"
    compile "com.android.support:percent:25.4.0"
    compile "com.android.support:support-vector-drawable:25.4.0"
    compile "com.android.support:animated-vector-drawable:25.4.0"
    compile "com.android.support:transition:25.4.0"
    compile "com.android.support:support-annotations:${supportLibVersion}"
    compile "com.android.support:palette-v7:25.4.0"
    compile "com.android.support:recyclerview-v7:25.4.0"
    compile 'com.github.clans:fab:1.6.4'
    compile 'com.android.volley:volley:1.0.0'

    compile 'com.google.android.gms:play-services-analytics:11.6.2'
    compile 'com.google.android.gms:play-services-maps:11.6.2'
    compile 'com.google.android.gms:play-services-gcm:11.6.2'

    compile 'com.squareup.picasso:picasso:2.5.2'

    compile 'org.igniterealtime.smack:smack-android-extensions:4.2.0-rc3'
    compile 'org.igniterealtime.smack:smack-experimental:4.2.0-rc1'
    compile 'org.igniterealtime.smack:smack-tcp:4.2.0-rc1'
    compile 'org.igniterealtime.smack:smack-sasl-provided:4.2.0-rc3'
    compile 'org.apache.commons:commons-io:1.3.2'
    compile 'com.daimajia.swipelayout:library:1.2.0@aar'
    compile 'com.orhanobut:dialogplus:1.11@aar'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'

    compile 'com.amazonaws:aws-android-sdk-core:2.6.9'
    compile 'com.amazonaws:aws-android-sdk-s3:2.6.9'
    compile 'com.amazonaws:aws-android-sdk-cognito:2.6.9'
    compile 'com.amazonaws:aws-android-sdk-pinpoint:2.6.9'
    compile('com.amazonaws:aws-android-sdk-mobile-client:2.6.9@aar') { transitive = true; }
}
</code>```

I looked through my dependencies to see I have any duplicated entries, but couldn't find anything.

答:
Exclude that entry from the apk:</p>

```
<code>
    android {
        ...
        packagingOptions {
            exclude 'module-info.class'
        }
    }
</code>
```

Body:
I am new to Android development and am currently seeing below error when I try to generate signed apk. I don't understand what am I missing.

Here's what my app build gradle looks like in Android Studio

apply plugin: 'com.android.application'

repositories {
    jcenter()
    maven {
        url 'http://maven.localytics.com/public'
    }
}

android {
    dexOptions {
        jumboMode true
        javaMaxHeapSize "4g"
        preDexLibraries = false
    }
    configurations {
        all*.exclude group: 'org.apache.commons'
        compile.exclude group: 'org.jetbrains', module: 'annotations'
    }
    compileSdkVersion 25
    buildToolsVersion '26.0.2'
    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 25
        vectorDrawables.useSupportLibrary = true
        multiDexEnabled = true
    }
}

dependencies {
    compile 'javax.xml.ws:jaxws-api:2.3.0'
    compile 'javax.xml.bind:jaxb-api:2.3.0'
    compile 'com.android.support:multidex:1.0.2'
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile fileTree(include: 'HockeySDK*.jar', dir: 'libs')
    compile fileTree(include: 'bolts-*.jar', dir: 'libs')
    compile 'com.parse:parse-android:1.10.3'
    compile "com.android.support:appcompat-v7:25.4.0"
    compile "com.android.support:design:25.4.0"
    compile "com.android.support:percent:25.4.0"
    compile "com.android.support:support-vector-drawable:25.4.0"
    compile "com.android.support:animated-vector-drawable:25.4.0"
    compile "com.android.support:transition:25.4.0"
    compile "com.android.support:support-annotations:${supportLibVersion}"
    compile "com.android.support:palette-v7:25.4.0"
    compile "com.android.support:recyclerview-v7:25.4.0"
    compile 'com.github.clans:fab:1.6.4'
    compile 'com.android.volley:volley:1.0.0'

    compile 'com.google.android.gms:play-services-analytics:11.6.2'
    compile 'com.google.android.gms:play-services-maps:11.6.2'
    compile 'com.google.android.gms:play-services-gcm:11.6.2'

    compile 'com.squareup.picasso:picasso:2.5.2'

    compile 'org.igniterealtime.smack:smack-android-extensions:4.2.0-rc3'
    compile 'org.igniterealtime.smack:smack-experimental:4.2.0-rc1'
    compile 'org.igniterealtime.smack:smack-tcp:4.2.0-rc1'
    compile 'org.igniterealtime.smack:smack-sasl-provided:4.2.0-rc3'
    compile 'org.apache.commons:commons-io:1.3.2'
    compile 'com.daimajia.swipelayout:library:1.2.0@aar'
    compile 'com.orhanobut:dialogplus:1.11@aar'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'

    compile 'com.amazonaws:aws-android-sdk-core:2.6.9'
    compile 'com.amazonaws:aws-android-sdk-s3:2.6.9'
    compile 'com.amazonaws:aws-android-sdk-cognito:2.6.9'
    compile 'com.amazonaws:aws-android-sdk-pinpoint:2.6.9'
    compile('com.amazonaws:aws-android-sdk-mobile-client:2.6.9@aar') { transitive = true; }
}

I looked through my dependencies to see I have any duplicated entries, but couldn't find anything.

Body:
Exclude that entry from the apk:

    android {
        ...
        packagingOptions {
            exclude 'module-info.class'
        }
    }


问:
Android: GridLayout size and View.GONE behaviour
I want to make a GridLayout that when one of it's children's Visibility is set to GONE, it is replaced by the next child.

This is no assignment I drew that myself to better explain.

I can get the layout working as in number of columns and width and all. Just the default GONE behaviour of GridLayout makes the child just disappear instead of being replaced as if it wasn't there in the first place, like other layouts work.

I did try a lot of stuff, I tried searching SO and google, but I can't seem to work this out. And this would be the most convenient layout for the app I'm working on.Is there anyway to do this in layout without having to do this programmatically?Or maybe a combination of both?

答:
If you don't need turn the view visible again you can solve it removing the view from GridLayout. </p>

```<code>private void hideView(View view) {
    GridLayout gridLayout = (GridLayout) view.getParent();
    for (int i = 0; i <  gridLayout.getChildCount(); i++) {
        if (view == gridLayout.getChildAt(i)) {
            gridLayout.removeViewAt(i);
            break;
        }
    }
}
</code>```

Body:
If you don't need turn the view visible again you can solve it removing the view from GridLayout.

private void hideView(View view) {
    GridLayout gridLayout = (GridLayout) view.getParent();
    for (int i = 0; i <  gridLayout.getChildCount(); i++) {
        if (view == gridLayout.getChildAt(i)) {
            gridLayout.removeViewAt(i);
            break;
        }
    }
}


问:
JodaTime - Display time in its own timezone
My app is using JodaTime to manage date parsing and formatting.

I have this timestamp: 2018-07-24T15:30:00-07:00.
How can display it as 3:30pm, regardless of the user's whereabouts?

答:
Following code will print "3:30pm":

```<code>DateTimeFormatter iso = ISODateTimeFormat.dateTimeParser().withOffsetParsed();
DateTime tsp = iso.parseDateTime("2018-07-24T15:30:00-07:00");

DateTimeFormatter out = DateTimeFormat.forPattern("h:mma").withLocale(Locale.ENGLISH);

System.out.println(tsp); // 2018-07-24T15:30:00.000-07:00
System.out.println(out.print(tsp).toLowerCase()); // 3:30pm
</code>```

The main problem is just that the parser does not retain the parsed offset of -7:00 but shifts it to your system timezone unless you also call withOffsetParsed().

Body:
Following code will print "3:30pm":

DateTimeFormatter iso = ISODateTimeFormat.dateTimeParser().withOffsetParsed();
DateTime tsp = iso.parseDateTime("2018-07-24T15:30:00-07:00");

DateTimeFormatter out = DateTimeFormat.forPattern("h:mma").withLocale(Locale.ENGLISH);

System.out.println(tsp); // 2018-07-24T15:30:00.000-07:00
System.out.println(out.print(tsp).toLowerCase()); // 3:30pm

The main problem is just that the parser does not retain the parsed offset of -7:00 but shifts it to your system timezone unless you also call withOffsetParsed().


问:
Apache Redirect // to no //
An email went out with the wrong link (https://www.digitalmarketer.com/digital-marketing/content-marketing-strategy//) and we need to redirect the // to (https://www.digitalmarketer.com/digital-marketing/content-marketing-strategy/) but no matter what I try, the redirect isn't working.

They also want it to be redirected to always have https:///www at the beginning and to never have index.html at the end, so already in the .htaccess file I have:

```<code>RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteRule ^content\-marketing\-strategy/index\.html$ /digital-marketing/content-marketing-strategy/? [L,R=301]
</code>```

I've tried adding a new RewriteRule, but this won't work:

```<code>RewriteRule ^content\-marketing\-strategy//$ /digital-marketing/content-marketing-strategy/? [L,R=301]
</code>```

I'm very new to Apache and redirects so any help is much appreciated! Thank you!

Edit: Of note, this is in an .htaccess file inside of the digital-marketing folder (https://www.digitalmarketer.com/digital-marketing/.htaccess) which was done so all the above rules would only apply to the digital-marketing folder.

答:
I see nothing in the way that the rule is written that would make it not rewrite. However you have multiple rules with the L flag that might stop processing on the rewrite at an earlier point than you are looking for. From the documentation

The [L] flag causes mod_rewrite to stop processing the rule set. In most contexts, this means that if the rule matches, no further rules will be processed.
  (https://httpd.apache.org/docs/current/rewrite/flags.html).

You can try this page out http://htaccess.mwl.be/ to test all your rules together. You might have to rewrite them a bit to work with that page, it's not aware of the level your .htaccess file is at so you will have to rewrite all your rules to trigger from the root for example: RewriteRule ^digital\-marketing/content\-marketing\-strategy//$ /digital-marketing/content-marketing-strategy/? [L,R=301]

Title: Apache Redirect // to no //

Body:
An email went out with the wrong link (https://www.digitalmarketer.com/digital-marketing/content-marketing-strategy//) and we need to redirect the // to (https://www.digitalmarketer.com/digital-marketing/content-marketing-strategy/) but no matter what I try, the redirect isn't working.

They also want it to be redirected to always have https:///www at the beginning and to never have index.html at the end, so already in the .htaccess file I have:

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteRule ^content\-marketing\-strategy/index\.html$ /digital-marketing/content-marketing-strategy/? [L,R=301]

I've tried adding a new RewriteRule, but this won't work:

RewriteRule ^content\-marketing\-strategy//$ /digital-marketing/content-marketing-strategy/? [L,R=301]

I'm very new to Apache and redirects so any help is much appreciated! Thank you!

Edit: Of note, this is in an .htaccess file inside of the digital-marketing folder (https://www.digitalmarketer.com/digital-marketing/.htaccess) which was done so all the above rules would only apply to the digital-marketing folder.


问:
spark use hive custom serde for JSON but class not found
Following along with https://github.com/Esri/gis-tools-for-hadoop/wiki/Aggregating-CSV-Data-%28Spatial-Binning%29 but on spark the classes for the serde are not found.

```<code>ClassNotFoundException: Class com.esri.hadoop.hive.serde.JsonSerde not found
</code>```

My build definition looks like: https://github.com/geoHeil/spatial-heatmaps/blob/master/esri/build.sbt and includes:

```<code> "com.esri.hadoop" % "spatial-sdk-hive" % esriVersion,
 "com.esri.hadoop" % "spatial-sdk-json" % esriVersion,
</code>```

and the whole project can be found on GitHub:  https://github.com/geoHeil/spatial-heatmaps/tree/master/esri

App is executed by running sbt console and pasting the code (for now)

答:
The best approach would be to upgrade the GIS-Tools-for-Hadoop samples to Spatial-Framework-for-Hadoop v2 and Esri-Geometry-for-Java v2 - https://github.com/Esri/gis-tools-for-hadoop/issues/66.

Alternate workaround would be to downgrade to v1.2 of Spatial-Framework-for-Hadoop.

[disclosure: collaborator]

Body:
Following along with https://github.com/Esri/gis-tools-for-hadoop/wiki/Aggregating-CSV-Data-%28Spatial-Binning%29 but on spark the classes for the serde are not found.

ClassNotFoundException: Class com.esri.hadoop.hive.serde.JsonSerde not found

My build definition looks like: https://github.com/geoHeil/spatial-heatmaps/blob/master/esri/build.sbt and includes:

 "com.esri.hadoop" % "spatial-sdk-hive" % esriVersion,
 "com.esri.hadoop" % "spatial-sdk-json" % esriVersion,

and the whole project can be found on GitHub:  https://github.com/geoHeil/spatial-heatmaps/tree/master/esri

App is executed by running sbt console and pasting the code (for now)


问:
Call a function inside a switch inside a function
So, I'm having a function that returns random results and depending on that result, I want to call another function, but it doesn't work right now:

```<code>$(document).ready(function () {
   $('#classbutton').click(function () {
        $('#resultclass').text(classX());
 });
});

function subkrieger() {
    var subkriegerNumber = Math.floor((Math.random()*2)+1);
        switch (subkriegerNumber) {
            case 1:
                return "Berserkerin";
            case 2:
                return "Duellantin";
            }
}

function classX() {
    var classNumber = Math.floor((Math.random()*2)+1);
        switch (classNumber) {
            case 1:
                return "Kriegerin";
                return subkrieger();
            case 2:
                return "Mystikerin";
        }
}

    <button id="classbutton">Archetyp</button>
    <div id="resultclass" class="results"></div>
</code>```

So, the first function is for getting a sub-fantasyclass for the 2nd function, that randomly returns a fantasy rpg class. I tried to call the 1st function in case 1 of the 2nd function to try it out, but nothing is happening.
What am I doing wrong?

And there is probably a way to do this much more elegantly than having a bunch of switches?

答:
This is your problem:

```<code>return "Krieger";
return subkrieger();
break;
</code>```

You are returning a string, which ends the execution of that function, so you never get to the subkrieger() call.

If you remove the return "Krieger" line, that'll let it call. If you want both (like say something like Krieger Berserkerin, then you'll want to concatenate (add) them together:

```<code>return "Krieger " + subkrieger();
</code>```

or with ES6 style:

```<code>return `Krieger ${subkrieger()}`;
</code>```

Side note: having a break; after a return is redundant, because it'll never get to the break anyways, so just leave it off and do:

```<code>case:
    return "Krieger";
</code>```

Body:
So, I'm having a function that returns random results and depending on that result, I want to call another function, but it doesn't work right now:

$(document).ready(function () {
   $('#classbutton').click(function () {
        $('#resultclass').text(classX());
 });
});

function subkrieger() {
    var subkriegerNumber = Math.floor((Math.random()*2)+1);
        switch (subkriegerNumber) {
            case 1:
                return "Berserkerin";
            case 2:
                return "Duellantin";
            }
}

function classX() {
    var classNumber = Math.floor((Math.random()*2)+1);
        switch (classNumber) {
            case 1:
                return "Kriegerin";
                return subkrieger();
            case 2:
                return "Mystikerin";
        }
}

    <button id="classbutton">Archetyp</button>

So, the first function is for getting a sub-fantasyclass for the 2nd function, that randomly returns a fantasy rpg class. I tried to call the 1st function in case 1 of the 2nd function to try it out, but nothing is happening.
What am I doing wrong?

And there is probably a way to do this much more elegantly than having a bunch of switches?

Body:
This is your problem:

return "Krieger";
return subkrieger();
break;

You are returning a string, which ends the execution of that function, so you never get to the subkrieger() call.

If you remove the return "Krieger" line, that'll let it call. If you want both (like say something like Krieger Berserkerin, then you'll want to concatenate (add) them together:

return "Krieger " + subkrieger();

or with ES6 style:

return `Krieger ${subkrieger()}`;

Side note: having a break; after a return is redundant, because it'll never get to the break anyways, so just leave it off and do:

case:
    return "Krieger";


问:
Enumerating boolean template parameters in C++11
I'm trying to determine how to take in a boolean template parameter pack

```<code>template<bool...B> struct BoolPack{};
</code>```

and construct from it an integer parameter pack where the values indicate the enumeration of the true elements in BoolPack. The enumeration could be contained like this:

```<code>template<size_t...I> struct IntegerSequence{};
</code>```

The function should take in a BoolPack and return an IntegerSequence;

```<code>template<bool...B>
constexpr auto enumerate( const BoolPack<B...>& b ) {
  // Combination of cumulative sum and mask?
  return IntegerSequence<???>();
}
</code>```

For example, if the input would be

```<code>BoolPack<true,false,true,false,true> b;
</code>```

The function should return

```<code>IntegerSequence<1,0,2,0,3> e();
</code>```

My best guess on how to implement this would be to compute a partial sum
where the the kth template parameter is

```<code>K = K-1 + static_cast<size_t>(get<K>(make_tuple<B...>));
</code>```

I'm not sure if this is the way to do it. Is there not a more direct approach that doesn't require making tuples for example? Applying the recursion should result in

```<code>IntegerSequence<1,1,2,2,3> s();
</code>```

And then to multiply this componentwise with the elements of the original BoolPack. Is this the way to go, or can I do this without tuples?

Thanks!

答:
Another possible solution pass through the creation of a constexpr function

```<code>template <bool ... Bs>
constexpr std::size_t getNumTrue (BoolPack<Bs...> const &, std::size_t top)
 {
   using unused = int[];

   std::size_t  cnt = -1;
   std::size_t  ret { 0 };

   (void)unused { 0, (++cnt <= top ? ret += Bs : ret, 0)... };

   return ret;
 }
</code>```

that can be called to set the template values for IndexSequence; unfortunately the following example use std::make_index_sequence and std::index_sequence that are C++14 (starting from) features

```<code>template <bool ... Bs, std::size_t ... Is>
constexpr auto gisH (BoolPack<Bs...> const &,
                     std::index_sequence<Is...> const &)
   -> IndexSequence<(Bs ? getNumTrue(BoolPack<Bs...>{}, Is) : 0U)...>
 { return {}; }

template <bool ... Bs>
constexpr auto getIndexSequence (BoolPack<Bs...> const & bp)
 { return gisH(bp, std::make_index_sequence<sizeof...(Bs)>{}); }
</code>```

The following is a full compiling example

```<code>#include <utility>
#include <iostream>
#include <type_traits>

template <bool ... B>
struct BoolPack
 { };

template <std::size_t...I>
struct IndexSequence
 { };

template <bool ... Bs>
constexpr std::size_t getNumTrue (BoolPack<Bs...> const &, std::size_t top)
 {
   using unused = int[];

   std::size_t  cnt = -1;
   std::size_t  ret { 0 };

   (void)unused { 0, (++cnt <= top ? ret += Bs : ret, 0)... };

   return ret;
 }

template <bool ... Bs, std::size_t ... Is>
constexpr auto gisH (BoolPack<Bs...> const &,
                     std::index_sequence<Is...> const &)
   -> IndexSequence<(Bs ? getNumTrue(BoolPack<Bs...>{}, Is) : 0U)...>
 { return {}; }

template <bool ... Bs>
constexpr auto getIndexSequence (BoolPack<Bs...> const & bp)
 { return gisH(bp, std::make_index_sequence<sizeof...(Bs)>{}); }

int main()
 {
   using typeBP = BoolPack<true,false,true,false,true>;

   auto is = getIndexSequence(typeBP{});

   static_assert( std::is_same<decltype(is),
                               IndexSequence<1,0,2,0,3>>{}, "!" );
 }
</code>```

Body:
I'm trying to determine how to take in a boolean template parameter pack

template<bool...B> struct BoolPack{};

and construct from it an integer parameter pack where the values indicate the enumeration of the true elements in BoolPack. The enumeration could be contained like this:

template<size_t...I> struct IntegerSequence{};

The function should take in a BoolPack and return an IntegerSequence;

template<bool...B>
constexpr auto enumerate( const BoolPack& b ) {
  // Combination of cumulative sum and mask?
  return IntegerSequence<???>();
}

For example, if the input would be

BoolPack<true,false,true,false,true> b;

The function should return

IntegerSequence<1,0,2,0,3> e();

My best guess on how to implement this would be to compute a partial sum
where the the kth template parameter is

K = K-1 + static_cast<size_t>(get<K>(make_tuple));

I'm not sure if this is the way to do it. Is there not a more direct approach that doesn't require making tuples for example? Applying the recursion should result in

IntegerSequence<1,1,2,2,3> s();

And then to multiply this componentwise with the elements of the original BoolPack. Is this the way to go, or can I do this without tuples?

Thanks!

Body:
Another possible solution pass through the creation of a constexpr function

template <bool ... Bs>
constexpr std::size_t getNumTrue (BoolPack<Bs...> const &, std::size_t top)
 {
   using unused = int[];

   std::size_t  cnt = -1;
   std::size_t  ret { 0 };

   (void)unused { 0, (++cnt <= top ? ret += Bs : ret, 0)... };

   return ret;
 }

that can be called to set the template values for IndexSequence; unfortunately the following example use std::make_index_sequence and std::index_sequence that are C++14 (starting from) features

template <bool ... Bs, std::size_t ... Is>
constexpr auto gisH (BoolPack<Bs...> const &,
                     std::index_sequence<Is...> const &)
   -> IndexSequence<(Bs ? getNumTrue(BoolPack<Bs...>{}, Is) : 0U)...>
 { return {}; }

template <bool ... Bs>
constexpr auto getIndexSequence (BoolPack<Bs...> const & bp)
 { return gisH(bp, std::make_index_sequence<sizeof...(Bs)>{}); }

The following is a full compiling example

#include <utility>
#include <iostream>
#include <type_traits>

template <bool ... B>
struct BoolPack
 { };

template <std::size_t...I>
struct IndexSequence
 { };

template <bool ... Bs>
constexpr std::size_t getNumTrue (BoolPack<Bs...> const &, std::size_t top)
 {
   using unused = int[];

   std::size_t  cnt = -1;
   std::size_t  ret { 0 };

   (void)unused { 0, (++cnt <= top ? ret += Bs : ret, 0)... };

   return ret;
 }

template <bool ... Bs, std::size_t ... Is>
constexpr auto gisH (BoolPack<Bs...> const &,
                     std::index_sequence<Is...> const &)
   -> IndexSequence<(Bs ? getNumTrue(BoolPack<Bs...>{}, Is) : 0U)...>
 { return {}; }

template <bool ... Bs>
constexpr auto getIndexSequence (BoolPack<Bs...> const & bp)
 { return gisH(bp, std::make_index_sequence<sizeof...(Bs)>{}); }

int main()
 {
   using typeBP = BoolPack<true,false,true,false,true>;

   auto is = getIndexSequence(typeBP{});

   static_assert( std::is_same<decltype(is),
                               IndexSequence<1,0,2,0,3>>{}, "!" );
 }


问:
That A-Ha Moment for Understanding OO Design in C#
I've been studying C# for a couple of years, reading voraciously, even taking a few C# data access courses from Microsoft.  I've also been reading books on OOP.  I'm coding a web-based database application at work.  While my job title is not "programmer", I'm fortunate enough to be able to work on this as a side project.  I coded in Basic in the early 80's and was even good at utilizing pokes and peeks to manipulate the Apple ][ + and the TRS-80 to astound and amaze my friends.  But that was a very linear approach to coding.

All this being said, something is just not clicking with me.  I haven't had that a-ha moment with either C# or OOP that gives me the ability to sit down, open up VS2008, and start coding.  I have to study other people's code so much that it simply seems like I'm not doing anything on my own.  I'm getting discouraged.

It's not like I'm not capable of it.  I picked up t-sql really quickly.  Someone can tell me what information they want out of the database and I can code out the tsql in a matter of a few minutes to give them what they want.  SQL is something that I get.  This isn't happening for me with OOP or C#.  Granted, C# is inherently more complex, but at some point it has to click.  Right?

I read over stackoverflow and I'm overwhelmed at how infinitely smart you all are.

What was it for you that made it click?

Edited to add:
A lot of the answers here were outstanding.  However, one in particular seemed to have risen to the top and that's the one I marked as the "answer".  I also hate not marking my questions with the answer.

答:
The majority of posters on SO are not exceptionally intelligent.  There are a couple things that may skew you to think that is the case.  First, only people who happen to know or think they know an answer will bother to respond.  Second, incorrect/bad questions and answers are not visible.  Third, it's natural that collective knowledge will be much greater than individual knowledge.

The thing that you mistake for intelligence, is time spent in an arena.  The more time and effort you devote to learning the better and more knowledgeable you will become.  From what you are saying, you are not approaching things in an optimal way.  Understand that a specific language just provides the rules of syntax and grammar.  The key to becoming a good developer is to be being a good thinker.  Don't focus or get hung up on a language.

Craig Larman and Bruce Eckols and the Head Start books are a great fit for this model of learning.  However, I do have to warn you that reading the books and doing the exercises is not enough.  You've got to immerse yourself in discussion and feedback with other developers (unless of course, you are an exceptionally intelligent person - in which case you'll simply get it...).

You've demonstrated a trait that is more important than intelligence.  You've got humility.  If you have humility and perseverence, you'll be much more effective and  knowledgeable than the vast majority of the posters on SO.

Humility is also important because it will help you cope with the fact that no matter how hard you work and how much you study, you'll never know more than Jon Skeet.

OwnerDisplayName: GregD

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: GregD

OwnerDisplayName: mson


问:
python dictionaries - combine values
I have these dictionaries

```<code>{
    'id': 5,
    'quantity: 10
}

{
    'id': 5,
    'quantity: 15
}
</code>```

I want something like this

```<code>{
    'id': 5,
    'quantity': 25
}
</code>```

EDIT: Basically, I want to combine the quantity of similar ids
Sorry if I simplified my question way too much. Yes I have a list of these dicts

```<code>products = [{...}, {...}, {...}, ...]
</code>```

答:
this is a simple solution that uses a for loop to to iterate over each key in dic1</p>

```<code>dic1 = {'id': 5, 'quantity': 10}
dic2 = {'id': 5, 'quantity': 15}

for key in dic1:
    if key in dic2:
        dic1[key] += dic2[key]
</code>```

Title: python dictionaries - combine values

Body:
I have these dictionaries

{
    'id': 5,
    'quantity: 10
}

{
    'id': 5,
    'quantity: 15
}

I want something like this

{
    'id': 5,
    'quantity': 25
}

EDIT: Basically, I want to combine the quantity of similar ids
Sorry if I simplified my question way too much. Yes I have a list of these dicts

products = [{...}, {...}, {...}, ...]

Body:
this is a simple solution that uses a for loop to to iterate over each key in dic1

dic1 = {'id': 5, 'quantity': 10}
dic2 = {'id': 5, 'quantity': 15}

for key in dic1:
    if key in dic2:
        dic1[key] += dic2[key]