问:
Custom View inflating error
I have a simple custom View:

```<code>public class ScrollDisabledViewPager extends ViewPager {

    public ScrollDisabledViewPager(Context context) {
        super(context);
    }

    public ScrollDisabledViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        return false;
    }

}
</code>```

When I put this View in my XML layout, it doesn't inflate:

XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context="com.lol.firebase.ui.SignUpActivity">

    <com.lol.firebase.ui.SignUpActivity.ScrollDisabledViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.TabLayout
        android:id="@+id/tab_dots"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        app:tabGravity="center"
        app:tabIndicatorHeight="0dp"
        app:tabBackground="@drawable/tab_indicator_selector" />

    <Button
        android:id="@+id/btn_back"
        android:text="@string/back"
        android:textColor="@color/colorPrimaryLight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:drawableLeft="@drawable/ic_back"
        style="@style/Widget.AppCompat.Button.Borderless"
        android:visibility="gone" />

    <Button
        android:id="@+id/btn_next_or_finish"
        android:text="@string/next"
        android:textColor="@color/colorPrimaryLight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:drawableRight="@drawable/ic_next"
        style="@style/Base.Widget.AppCompat.Button.Borderless" />

</RelativeLayout>
</code>```

Stacktrace:

```<code> java.lang.RuntimeException: Unable to start activity ComponentInfo{com.lol.firebase/com.lol.firebase.ui.SignUpActivity}: android.view.InflateException: Binary XML file line #9: Error inflating class com.lol.firebase.ui.SignUpActivity.ScrollDisabledViewPager
                                                                          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2660)
                                                                          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2730)
                                                                          at android.app.ActivityThread.access$800(ActivityThread.java:185)
                                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1567)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:111)
                                                                          at android.os.Looper.loop(Looper.java:194)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:5847)
                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                          at java.lang.reflect.Method.invoke(Method.java:372)
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1010)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
                                                                       Caused by: android.view.InflateException: Binary XML file line #9: Error inflating class com.lol.firebase.ui.SignUpActivity.ScrollDisabledViewPager
                                                                          at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:763)
                                                                          at android.view.LayoutInflater.rInflate(LayoutInflater.java:812)
                                                                          at android.view.LayoutInflater.inflate(LayoutInflater.java:510)
                                                                          at android.view.LayoutInflater.inflate(LayoutInflater.java:420)
                                                                          at android.view.LayoutInflater.inflate(LayoutInflater.java:371)
                                                                          at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
                                                                          at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                                          at com.lol.firebase.ui.SignUpActivity.onCreate(SignUpActivity.java:29)
                                                                          at android.app.Activity.performCreate(Activity.java:6117)
                                                                          at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123)
                                                                          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2613)
                                                                          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2730)
                                                                          at android.app.ActivityThread.access$800(ActivityThread.java:185)
                                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1567)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:111)
                                                                          at android.os.Looper.loop(Looper.java:194)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:5847)
                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                          at java.lang.reflect.Method.invoke(Method.java:372)
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1010)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
                                                                       Caused by: java.lang.ClassNotFoundException: Didn't find class "com.lol.firebase.ui.SignUpActivity.ScrollDisabledViewPager" on path: DexPathList[[zip file "/data/app/com.lol.firebase-1/base.apk", zip file "/data/app/com.lol.firebase-1/split_lib_dependencies_apk.apk", zip file "/data/app/com.lol.firebase-1/split_lib_slice_0_apk.apk", zip file "/data/app/com.lol.firebase-1/split_lib_slice_1_apk.apk", zip file "/data/app/com.lol.firebase-1/split_lib_slice_2_apk.apk", zip file "/data/app/com.lol.firebase-1/split_lib_slice_3_apk.apk", zip file "/data/app/com.lol.firebase-1/split_lib_slice_4_apk.apk", zip file "/data/app/com.lol.firebase-1/split_lib_slice_5_apk.apk", zip file "/data/app/com.lol.firebase-1/split_lib_slice_6_apk.apk", zip file "/data/app/com.lol.firebase-1/split_lib_slice_7_apk.apk", zip file "/data/app/com.lol.firebase-1/split_lib_slice_8_apk.apk", zip file "/data/app/com.lol.firebase-1/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/com.lol.firebase-1/lib/arm64, /vendor/lib64, /system/lib64]]
                                                                          at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
                                                                          at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
                                                                          at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
                                                                          at android.view.LayoutInflater.createView(LayoutInflater.java:577)
                                                                          at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:749)
                                                                          at android.view.LayoutInflater.rInflate(LayoutInflater.java:812)
                                                                          at android.view.LayoutInflater.inflate(LayoutInflater.java:510)
                                                                          at android.view.LayoutInflater.inflate(LayoutInflater.java:420)
                                                                          at android.view.LayoutInflater.inflate(LayoutInflater.java:371)
                                                                          at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
                                                                          at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                                          at com.lol.firebase.ui.SignUpActivity.onCreate(SignUpActivity.java:29)
                                                                          at android.app.Activity.performCreate(Activity.java:6117)
                                                                          at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123)
                                                                          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2613)
                                                                          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2730)
                                                                          at android.app.ActivityThread.access$800(ActivityThread.java:185)
                                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1567)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:111)
                                                                          at android.os.Looper.loop(Looper.java:194)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:5847)
                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                          at java.lang.reflect.Method.invoke(Method.java:372)
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1010)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
                                                                        Suppressed: java.lang.ClassNotFoundException: com.lol.firebase.ui.SignUpActivity.ScrollDisabledViewPager
                                                                          at java.lang.Class.classForName(Native Method)
                                                                          at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
                                                                          at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
                                                                          at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
                                                                                ... 23 more
                                                                       Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available
</code>```

The Stacktrace shows a ClassNotFound Exception, but I don't understand why: the class is public, and I have both constructors.

答:
here is relevance error message:

java.lang.ClassNotFoundException: Didn't find class "com.lol.firebase.ui.SignUpActivity.ScrollDisabledViewPager"

please make sure the class ScrollDisabledViewPager is inside package com.lol.firebase.ui.SignUpActivity

but, I guess your class is inside com.lol.firebase.ui instead of com.lol.firebase.ui.SignUpActivity, if my guess is right than you should define com.lol.firebase.ui.ScrollDisabledViewPager in your xml layout

```<code>...other xml layout

<com.lol.firebase.ui.ScrollDisabledViewPager
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

...other xml layout
</code>```

Title: Custom View inflating error

Body:
I have a simple custom View:

public class ScrollDisabledViewPager extends ViewPager {

    public ScrollDisabledViewPager(Context context) {
        super(context);
    }

    public ScrollDisabledViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        return false;
    }

}

When I put this View in my XML layout, it doesn't inflate:

XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context="com.lol.firebase.ui.SignUpActivity">

    <com.lol.firebase.ui.SignUpActivity.ScrollDisabledViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.TabLayout
        android:id="@+id/tab_dots"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        app:tabGravity="center"
        app:tabIndicatorHeight="0dp"
        app:tabBackground="@drawable/tab_indicator_selector" />

    <Button
        android:id="@+id/btn_back"
        android:text="@string/back"
        android:textColor="@color/colorPrimaryLight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:drawableLeft="@drawable/ic_back"
        style="@style/Widget.AppCompat.Button.Borderless"
        android:visibility="gone" />

    <Button
        android:id="@+id/btn_next_or_finish"
        android:text="@string/next"
        android:textColor="@color/colorPrimaryLight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:drawableRight="@drawable/ic_next"
        style="@style/Base.Widget.AppCompat.Button.Borderless" />

</RelativeLayout>

Stacktrace:

 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.lol.firebase/com.lol.firebase.ui.SignUpActivity}: android.view.InflateException: Binary XML file line #9: Error inflating class com.lol.firebase.ui.SignUpActivity.ScrollDisabledViewPager
                                                                          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2660)
                                                                          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2730)
                                                                          at android.app.ActivityThread.access$800(ActivityThread.java:185)
                                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1567)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:111)
                                                                          at android.os.Looper.loop(Looper.java:194)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:5847)
                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                          at java.lang.reflect.Method.invoke(Method.java:372)
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1010)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
                                                                       Caused by: android.view.InflateException: Binary XML file line #9: Error inflating class com.lol.firebase.ui.SignUpActivity.ScrollDisabledViewPager
                                                                          at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:763)
                                                                          at android.view.LayoutInflater.rInflate(LayoutInflater.java:812)
                                                                          at android.view.LayoutInflater.inflate(LayoutInflater.java:510)
                                                                          at android.view.LayoutInflater.inflate(LayoutInflater.java:420)
                                                                          at android.view.LayoutInflater.inflate(LayoutInflater.java:371)
                                                                          at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
                                                                          at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                                          at com.lol.firebase.ui.SignUpActivity.onCreate(SignUpActivity.java:29)
                                                                          at android.app.Activity.performCreate(Activity.java:6117)
                                                                          at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123)
                                                                          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2613)
                                                                          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2730)
                                                                          at android.app.ActivityThread.access$800(ActivityThread.java:185)
                                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1567)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:111)
                                                                          at android.os.Looper.loop(Looper.java:194)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:5847)
                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                          at java.lang.reflect.Method.invoke(Method.java:372)
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1010)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
                                                                       Caused by: java.lang.ClassNotFoundException: Didn't find class "com.lol.firebase.ui.SignUpActivity.ScrollDisabledViewPager" on path: DexPathList[[zip file "/data/app/com.lol.firebase-1/base.apk", zip file "/data/app/com.lol.firebase-1/split_lib_dependencies_apk.apk", zip file "/data/app/com.lol.firebase-1/split_lib_slice_0_apk.apk", zip file "/data/app/com.lol.firebase-1/split_lib_slice_1_apk.apk", zip file "/data/app/com.lol.firebase-1/split_lib_slice_2_apk.apk", zip file "/data/app/com.lol.firebase-1/split_lib_slice_3_apk.apk", zip file "/data/app/com.lol.firebase-1/split_lib_slice_4_apk.apk", zip file "/data/app/com.lol.firebase-1/split_lib_slice_5_apk.apk", zip file "/data/app/com.lol.firebase-1/split_lib_slice_6_apk.apk", zip file "/data/app/com.lol.firebase-1/split_lib_slice_7_apk.apk", zip file "/data/app/com.lol.firebase-1/split_lib_slice_8_apk.apk", zip file "/data/app/com.lol.firebase-1/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/com.lol.firebase-1/lib/arm64, /vendor/lib64, /system/lib64]]
                                                                          at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
                                                                          at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
                                                                          at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
                                                                          at android.view.LayoutInflater.createView(LayoutInflater.java:577)
                                                                          at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:749)
                                                                          at android.view.LayoutInflater.rInflate(LayoutInflater.java:812)
                                                                          at android.view.LayoutInflater.inflate(LayoutInflater.java:510)
                                                                          at android.view.LayoutInflater.inflate(LayoutInflater.java:420)
                                                                          at android.view.LayoutInflater.inflate(LayoutInflater.java:371)
                                                                          at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
                                                                          at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                                          at com.lol.firebase.ui.SignUpActivity.onCreate(SignUpActivity.java:29)
                                                                          at android.app.Activity.performCreate(Activity.java:6117)
                                                                          at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123)
                                                                          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2613)
                                                                          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2730)
                                                                          at android.app.ActivityThread.access$800(ActivityThread.java:185)
                                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1567)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:111)
                                                                          at android.os.Looper.loop(Looper.java:194)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:5847)
                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                          at java.lang.reflect.Method.invoke(Method.java:372)
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1010)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
                                                                        Suppressed: java.lang.ClassNotFoundException: com.lol.firebase.ui.SignUpActivity.ScrollDisabledViewPager
                                                                          at java.lang.Class.classForName(Native Method)
                                                                          at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
                                                                          at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
                                                                          at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
                                                                                ... 23 more
                                                                       Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available

The Stacktrace shows a ClassNotFound Exception, but I don't understand why: the class is public, and I have both constructors.

Body:
here is relevance error message:

java.lang.ClassNotFoundException: Didn't find class "com.lol.firebase.ui.SignUpActivity.ScrollDisabledViewPager"

please make sure the class ScrollDisabledViewPager is inside package com.lol.firebase.ui.SignUpActivity

but, I guess your class is inside com.lol.firebase.ui instead of com.lol.firebase.ui.SignUpActivity, if my guess is right than you should define com.lol.firebase.ui.ScrollDisabledViewPager in your xml layout

...other xml layout

<com.lol.firebase.ui.ScrollDisabledViewPager
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

...other xml layout


来源: stackexchange

问:
SearchView is null android
Hello I am trying to implement a SearchView just like we have in Gmail .

```<code>@Override
public boolean onCreateOptionsMenu(Menu menu) {
    if (!mNavigationDrawerFragment.isDrawerOpen()) {
        getMenuInflater().inflate(R.menu.main, menu);

        searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

        restoreActionBar();
        return true;
    }

    return super.onCreateOptionsMenu(menu);
}
</code>```

searchView object is null

Manifest:

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

    <uses-sdk
        android:minSdkVersion="18"
        android:targetSdkVersion="21" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/logo"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <meta-data
            android:name="android.app.default_searchable"
            android:value=".GameSearchActivity" />

        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".GameInfoActivity"
            android:label="@string/title_activity_game_info" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".MainActivity" />
        </activity>
        <activity
            android:name=".SettingsActivity"
            android:label="@string/title_activity_settings" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".MainActivity" />
        </activity>
        <activity
            android:name=".GameSearchActivity"
            android:label="@string/title_activity_game_search" >
            <intent-filter>
                <action android:name="android.intent.action.SEARCH" />
            </intent-filter>

            <meta-data
                android:name="android.app.searchable"
                android:value="@xml/searchable" />
        </activity>
    </application>

</manifest>
</code>```

Searchable.xml

```<code><searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/app_name"
    android:hint="@string/search_hint" />
</code>```

menu layout:

```<code><menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.dgp.MainActivity" >

<item
    android:id="@+id/action_search"
    android:icon="@drawable/ic_action_search"
    app:showAsAction="collapseActionView|always"
    android:title="@string/action_search"
    android:actionViewClass="android.support.v7.widget.SearchView"/>

<item
    android:id="@+id/action_settings"
    android:orderInCategory="100"
    android:title="@string/action_settings"
    app:showAsAction="never"/></menu>
</code>```

Can anyone help to understand why is this object getting null?
Thank you!!!!

答:
To support Search view you need to use

app:actionViewClass="android.support.v7.widget.SearchView"  ----in the menu xml file

And  will have to import

android.support.v7.widget.SearchView  in the java file

please look carefully imported class have to be android.support.v7.widget.SearchView . when this two parts are not same then null pointer exception may happen.

ContentLicense: CC BY-SA 3.0

Title: SearchView is null android

Body:
Hello I am trying to implement a SearchView just like we have in Gmail .

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    if (!mNavigationDrawerFragment.isDrawerOpen()) {
        getMenuInflater().inflate(R.menu.main, menu);

        searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

        restoreActionBar();
        return true;
    }

    return super.onCreateOptionsMenu(menu);
}

searchView object is null

Manifest:

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

    <uses-sdk
        android:minSdkVersion="18"
        android:targetSdkVersion="21" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/logo"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <meta-data
            android:name="android.app.default_searchable"
            android:value=".GameSearchActivity" />

        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".GameInfoActivity"
            android:label="@string/title_activity_game_info" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".MainActivity" />
        </activity>
        <activity
            android:name=".SettingsActivity"
            android:label="@string/title_activity_settings" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".MainActivity" />
        </activity>
        <activity
            android:name=".GameSearchActivity"
            android:label="@string/title_activity_game_search" >
            <intent-filter>
                <action android:name="android.intent.action.SEARCH" />
            </intent-filter>

            <meta-data
                android:name="android.app.searchable"
                android:value="@xml/searchable" />
        </activity>
    </application>

</manifest>

Searchable.xml

<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/app_name"
    android:hint="@string/search_hint" />

menu layout:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.dgp.MainActivity" >

<item
    android:id="@+id/action_search"
    android:icon="@drawable/ic_action_search"
    app:showAsAction="collapseActionView|always"
    android:title="@string/action_search"
    android:actionViewClass="android.support.v7.widget.SearchView"/>

<item
    android:id="@+id/action_settings"
    android:orderInCategory="100"
    android:title="@string/action_settings"
    app:showAsAction="never"/></menu>

Can anyone help to understand why is this object getting null?
Thank you!!!!

ContentLicense: CC BY-SA 4.0


问:
How to dynamically create an image with a specified number on it?
I have  a place holder image saying something like:

```<code>Your rating is:
   [rating here]
</code>```

My PHP code is supposed to dynamically insert the rating number where there is a blank space left out for it on the placeholder image. How can I do that?

答:
Here's a an example how you could do it - use gd function calls to make your image, but play nice and cache the images. This sample plays even nicer by ensuring that if the browser already has the required image, it returns a 304...

```<code>#here's where we'll store the cached images
$cachedir=$_SERVER['DOCUMENT_ROOT'].'/imgcache/'

#get the score and sanitize it
$score=$_GET['score'];
if (preg_match('/^[0-9]\.[0-9]{1,2}$/', $score)
{
    #figure out filename of cached file
    $file=$cachedir.'score'.$score.'gif';

    #regenerate cached image
    if (!file_exists($file))
    {
        #generate image - this is lifted straight from the php
        #manual, you'll need to work out how to make your
        #image, but this will get you started

        #load a background image
        $im     = imagecreatefrompng("images/button1.png");

        #allocate color for the text
        $orange = imagecolorallocate($im, 220, 210, 60);

        #attempt to centralise the text
        $px     = (imagesx($im) - 7.5 * strlen($score)) / 2;
        imagestring($im, 3, $px, 9, $score, $orange);

        #save to cache
        imagegif($im, $file);
        imagedestroy($im);
    }

    #return image to browser, but return a 304 if they already have it
    $mtime=filemtime($file);

    $headers = apache_request_headers();
    if (isset($headers['If-Modified-Since']) &&
        (strtotime($headers['If-Modified-Since']) >= $mtime))
    {
        // Client's cache IS current, so we just respond '304 Not Modified'.
        header('Last-Modified: '.gmdate('D, d M Y H:i:s', $mtime).' GMT', true, 304);
        exit;
    }

    header('Content-Type:image/gif');
    header('Content-Length: '.filesize($file));
    header('Last-Modified: '.gmdate('D, d M Y H:i:s', $mtime).' GMT');
    readfile($file);

}
else
{
    header("HTTP/1.0 401 Invalid score requested");
}
</code>```

If you put this in image.php, you would use as follows in an image tag

```<code><img src="image.php?score=5.5" alt="5.5" />
</code>```

OwnerDisplayName: Click Upvote

ContentLicense: CC BY-SA 2.5

Body:
I have  a place holder image saying something like:

Your rating is:
   [rating here]

My PHP code is supposed to dynamically insert the rating number where there is a blank space left out for it on the placeholder image. How can I do that?

Body:
Here's a an example how you could do it - use gd function calls to make your image, but play nice and cache the images. This sample plays even nicer by ensuring that if the browser already has the required image, it returns a 304...

#here's where we'll store the cached images
$cachedir=$_SERVER['DOCUMENT_ROOT'].'/imgcache/'

#get the score and sanitize it
$score=$_GET['score'];
if (preg_match('/^[0-9]\.[0-9]{1,2}$/', $score)
{
    #figure out filename of cached file
    $file=$cachedir.'score'.$score.'gif';

    #regenerate cached image
    if (!file_exists($file))
    {
        #generate image - this is lifted straight from the php
        #manual, you'll need to work out how to make your
        #image, but this will get you started

        #load a background image
        $im     = imagecreatefrompng("images/button1.png");

        #allocate color for the text
        $orange = imagecolorallocate($im, 220, 210, 60);

        #attempt to centralise the text
        $px     = (imagesx($im) - 7.5 * strlen($score)) / 2;
        imagestring($im, 3, $px, 9, $score, $orange);

        #save to cache
        imagegif($im, $file);
        imagedestroy($im);
    }

    #return image to browser, but return a 304 if they already have it
    $mtime=filemtime($file);

    $headers = apache_request_headers();
    if (isset($headers['If-Modified-Since']) &&
        (strtotime($headers['If-Modified-Since']) >= $mtime))
    {
        // Client's cache IS current, so we just respond '304 Not Modified'.
        header('Last-Modified: '.gmdate('D, d M Y H:i:s', $mtime).' GMT', true, 304);
        exit;
    }

    header('Content-Type:image/gif');
    header('Content-Length: '.filesize($file));
    header('Last-Modified: '.gmdate('D, d M Y H:i:s', $mtime).' GMT');
    readfile($file);

}
else
{
    header("HTTP/1.0 401 Invalid score requested");
}

If you put this in image.php, you would use as follows in an image tag

<img src="image.php?score=5.5" alt="5.5" />

OwnerDisplayName: Paul Dixon

LastEditorDisplayName: Paul Dixon


问:
ASM: Stateful Transformation
I want to write a MethodVisitor that transforms LDC instructions that are for multiplication.

Example bytecode:

```<code>ldc #26
imul
</code>```

This basically pushes a constant and then multiplies it.

It has to be a stateful transformation because I first have to check that it is for multiply and, if it is, I need to go back to the ldc instruction and modify the constant. I'm not entirely sure how I would go about this, and I don't know how to modify the constant (when I tried to pass a different value, the old value still remained in the constant pool).

Edit:

```<code>public class AdditionTransformer extends MethodAdapter {
    boolean replace = false;
    int operand = 0;

    AdditionTransformer(MethodVisitor mv) {
        super(mv);
    }

    @Override
    public void visitInsn(int opcode) {
        if (opcode == IMUL && replace) {
            operand *= 2;
            visitLdcInsn(operand);
            replace = false;
        }
        mv.visitInsn(opcode);
    }

    @Override
    public void visitLdcInsn(Object cst) {
        if (cst instanceof Integer && !replace) {
            operand = (Integer) cst;
            replace = true;
        } else {
            mv.visitLdcInsn(cst);
        }
    }
}
</code>```

This is what I have, but it doesn't remove the old value in the constant pool, and it may have bugs.

答:
What you've got is just about right, but doesn't cater for other types of opcodes being called after the ldc, so you'll cause some breakage there, since they'll be looking for something on the stack that isn't there (since you didn't visit the ldc). I'm not so sure about removing the existing constant, but you can replace the constant like so:

```<code>@Override
public void visitInsn(int opcode) {
    if (opcode == IMUL && replace) {
        operand *= 2;
        mv.visitInsn(POP);
        mv.visitLdcInsn(operand);
        replace = false;
    }
    mv.visitInsn(opcode);
}

@Override
public void visitLdcInsn(Object cst) {
    if (cst instanceof Integer && !replace) {
        operand = (Integer) cst;
        replace = true;
    }
    mv.visitLdcInsn(cst);
}
</code>```

In other words, always visit the "ldc". If you then see an IMUL proceeding it, pop the stack, insert a new constant, and then visit the IMUL opcode. You'd need to do a bit of work to make this completely safe, in case some other method is visited after visiting ldc and before IMUL. To be paranoid, you could override all visitor methods, and if it's not visitInsn or not IMUL, you would visit the ldc and set replace = false.

Completely replacing the constant is a bit more tricky. You'd need to remember which constants have been seen by all methods visited in the class so far. If you haven't seen that constant so far, you can just replace the value when you visit the ldc.

Title: ASM: Stateful Transformation

Body:
I want to write a MethodVisitor that transforms LDC instructions that are for multiplication.

Example bytecode:

ldc #26
imul

This basically pushes a constant and then multiplies it.

It has to be a stateful transformation because I first have to check that it is for multiply and, if it is, I need to go back to the ldc instruction and modify the constant. I'm not entirely sure how I would go about this, and I don't know how to modify the constant (when I tried to pass a different value, the old value still remained in the constant pool).

Edit:

public class AdditionTransformer extends MethodAdapter {
    boolean replace = false;
    int operand = 0;

    AdditionTransformer(MethodVisitor mv) {
        super(mv);
    }

    @Override
    public void visitInsn(int opcode) {
        if (opcode == IMUL && replace) {
            operand *= 2;
            visitLdcInsn(operand);
            replace = false;
        }
        mv.visitInsn(opcode);
    }

    @Override
    public void visitLdcInsn(Object cst) {
        if (cst instanceof Integer && !replace) {
            operand = (Integer) cst;
            replace = true;
        } else {
            mv.visitLdcInsn(cst);
        }
    }
}

This is what I have, but it doesn't remove the old value in the constant pool, and it may have bugs.

Body:
What you've got is just about right, but doesn't cater for other types of opcodes being called after the ldc, so you'll cause some breakage there, since they'll be looking for something on the stack that isn't there (since you didn't visit the ldc). I'm not so sure about removing the existing constant, but you can replace the constant like so:

@Override
public void visitInsn(int opcode) {
    if (opcode == IMUL && replace) {
        operand *= 2;
        mv.visitInsn(POP);
        mv.visitLdcInsn(operand);
        replace = false;
    }
    mv.visitInsn(opcode);
}

@Override
public void visitLdcInsn(Object cst) {
    if (cst instanceof Integer && !replace) {
        operand = (Integer) cst;
        replace = true;
    }
    mv.visitLdcInsn(cst);
}

In other words, always visit the "ldc". If you then see an IMUL proceeding it, pop the stack, insert a new constant, and then visit the IMUL opcode. You'd need to do a bit of work to make this completely safe, in case some other method is visited after visiting ldc and before IMUL. To be paranoid, you could override all visitor methods, and if it's not visitInsn or not IMUL, you would visit the ldc and set replace = false.

Completely replacing the constant is a bit more tricky. You'd need to remember which constants have been seen by all methods visited in the class so far. If you haven't seen that constant so far, you can just replace the value when you visit the ldc.


问:
Android ADB Shell Input - emulate multiple touches
I'm using adb Shell input to emulating touchscreen interaction,

Working on Windows 8 with adb command line service.

For one long touch (not tap!) I'm using this command:

adb shell input swipe x1 y1 x1 y1 t

How can I emulate simultaneous 2 long taps  from command line?

Thanks!

答:
I've searched a bit and seems that the easiest way is not to find the proper commands (you've to emulate a real set of N events moving the 2 fingers around the screen to pinch), but you can instead try this: save a gesture (with X fingers) and then play it back from adb.

For details see this question, already well replied in the Saurabh Meshram answer:

Fire a pinch in/out command to Android phone using adb

EDIT:

you can try to understand what the events means (quite obscure at first glimpse), see:
http://ktnr74.blogspot.pt/2013/06/emulating-touchscreen-interaction-with.html


问:
Command Window Output with MATLAB GUI
I am pretty new to MATLAB GUI. I've attempted to teach it to myself the last few weeks so I can understand and improve some code that is being developed where I work. GUI is still a fairly new concept to me.

I am wondering: I need the command window to output the mean of a set of data according to a function that is called by pressing a button on the GUI. Where would I include this code and how should I go about it?

Thanks

答: You can debug the code by using 'disp' or 'fprintf' functions. Notice that converts your content to compatible with the function.                            </p>

Title: Command Window Output with MATLAB GUI


问:
Sum of cost IF checkbox is true
I'm making a spreadsheet in Numbers to calculate how much deposit each tenant of a house should get based on who is responsible for particular damages; below is the sheet so far.

In the "Total Bill" column I would like to have a sum of the charges, divided by the number of people involved, for all damages. Formulae I have tried previously are,

```<code>SUMIF(C2:C20,TRUE,B2:B20÷K2:K20)
SUMIF(person, true, cost/split)
</code>```

This does not work however. What should I use instead?

答:
Try this Array formula for Total Bill of Person1 then autofill (or copy/paste) under each person:

```<code>=SUM(IFERROR(C$2:C$20*B$2:B$20/K$2:K$20,0))
</code>```

CTRLSHIFTENTER

Title: Sum of cost IF checkbox is true

Body:
I'm making a spreadsheet in Numbers to calculate how much deposit each tenant of a house should get based on who is responsible for particular damages; below is the sheet so far.

In the "Total Bill" column I would like to have a sum of the charges, divided by the number of people involved, for all damages. Formulae I have tried previously are,

SUMIF(C2:C20,TRUE,B2:B20÷K2:K20)
SUMIF(person, true, cost/split)

This does not work however. What should I use instead?

Body:
Try this Array formula for Total Bill of Person1 then autofill (or copy/paste) under each person:

=SUM(IFERROR(C$2:C$20*B$2:B$20/K$2:K$20,0))

CTRLSHIFTENTER


问:
Alexnet val_acc is 0 and val_loss is 0 after Epochs
I am trying to train the Alexnet upon the data that i collected.
It contains the images converted to grayscale and the associated key.
This is a program to simulate a self driving car.

The keys are :

```<code>w = [1,0,0]
a = [0,1,0]
d = [0,0,1]
</code>```

This is my code

```<code>import numpy as np
from alexnet import alexnet

WIDTH = 100
HEIGHT = 80
LR = 1e-3
EPOCHS = 8
MODEL_NAME = 'Udacity Model Car NN'

model = alexnet(WIDTH,HEIGHT,LR)

train_data = np.load('data.npy',encoding="bytes")
train = train_data[:-200]
test = train_data[-200:]

X = np.array([i[0] for i in train]).reshape(-1,WIDTH,HEIGHT,1)
Y = [i[1] for i in train]

test_X = np.array([i[0] for i in test]).reshape(-1,WIDTH,HEIGHT,1)
test_Y = [i[1] for i in test]

model.fit({'input':X},{'targets':Y},n_epoch=EPOCHS,validation_set=({'input':test_X},{'targets:test_y'}),snapshot_step=500,show_metric=True,run_id=MODEL_NAME)

model.save(MODEL_NAME)
</code>```

But after every Epoch the validation accuracy remains 0 as well as the validation loss remains 0 as well.

```<code>Training Step: 104  | total loss: 1.31713 | time: 119.279s| Momentum |epoch: 008 | loss: 1.31713 - acc: 0.3878 | val_loss: 0.00000 - val_acc: 0.0000 -- iter: 801/801
</code>```

答:
This is probably a typo, look what you are passing as validation:

```<code>{'input':test_X},{'targets:test_y'}
\______________/ \_______________/
correct dict      this is a set with a string!
</code>```

while it should be

```<code>{'input':test_X},{'targets':test_Y}
</code>```

Body:
I am trying to train the Alexnet upon the data that i collected.
It contains the images converted to grayscale and the associated key.
This is a program to simulate a self driving car.

The keys are :

w = [1,0,0]
a = [0,1,0]
d = [0,0,1]

This is my code

import numpy as np
from alexnet import alexnet

WIDTH = 100
HEIGHT = 80
LR = 1e-3
EPOCHS = 8
MODEL_NAME = 'Udacity Model Car NN'

model = alexnet(WIDTH,HEIGHT,LR)

train_data = np.load('data.npy',encoding="bytes")
train = train_data[:-200]
test = train_data[-200:]

X = np.array([i[0] for i in train]).reshape(-1,WIDTH,HEIGHT,1)
Y = [i[1] for i in train]

test_X = np.array([i[0] for i in test]).reshape(-1,WIDTH,HEIGHT,1)
test_Y = [i[1] for i in test]

model.fit({'input':X},{'targets':Y},n_epoch=EPOCHS,validation_set=({'input':test_X},{'targets:test_y'}),snapshot_step=500,show_metric=True,run_id=MODEL_NAME)

model.save(MODEL_NAME)

But after every Epoch the validation accuracy remains 0 as well as the validation loss remains 0 as well.

Training Step: 104  | total loss: 1.31713 | time: 119.279s| Momentum |epoch: 008 | loss: 1.31713 - acc: 0.3878 | val_loss: 0.00000 - val_acc: 0.0000 -- iter: 801/801

Body:
This is probably a typo, look what you are passing as validation:

{'input':test_X},{'targets:test_y'}
\______________/ \_______________/
correct dict      this is a set with a string!

while it should be

{'input':test_X},{'targets':test_Y}


问:
Click one div in order to open only it's children and not other with same class
So I tried obviously using $('this .classname') but it toggle closes the whole div.
I'm trying to have each div (image is placed) be clicked and only it's ul be opened.

HTML

```<code><div class="col-md-12 col-xs-12">

    <div class="recipePicContainer">
        <div id="checkBoxes">
                <li class="recipe" id="recipe01"><label>Cocktail</label></li>
                       <ul class="recipes">
                           <li class="ingredient"><input type="checkbox"> ingredient 1</li>
                           <li class="ingredient"><input type="checkbox"> ingredient 2</li>
                           <li class="ingredient"><input type="checkbox"> ingredient 3</li>
                           <li class="ingredient"><input type="checkbox"> ingredient 4</li>
                            <li class="instructions">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</li>
                       </ul>
                </div>
            </div>

        <div class="recipePicContainer">
            <div class="checkBoxes">
                <li class="recipe" id="recipe02"><label>Main Dish</label></li>
                       <ul class="recipes">
                           <li class="ingredient"><input type="checkbox"> ingredient 1</li>
                           <li class="ingredient"><input type="checkbox"> ingredient 2</li>
                           <li class="ingredient"><input type="checkbox"> ingredient 3</li>
                           <li class="ingredient"><input type="checkbox"> ingredient 4</li>
                            <li class="instructions">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</li>
                       </ul>
                </div>
            </div>

        <div class="recipePicContainer">
            <div class="checkBoxes">
                <li class="recipe" id="recipe03"><label>Dessert</label></li>
                       <ul class="recipes">
                           <li class="ingredient"><input type="checkbox"> ingredient 1</li>
                           <li class="ingredient"><input type="checkbox"> ingredient 2</li>
                           <li class="ingredient"><input type="checkbox"> ingredient 3</li>
                           <li class="ingredient"><input type="checkbox"> ingredient 4</li>
                            <li class="instructions">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</li>
                       </ul>
                </div>
            </div>

</div>
</code>```

JS

```<code>var main = function() {
    $(document).ready(function () {
        $('ul').hide();
        $('.recipe').click(function () {
            $('.recipes').toggle("slow").toggleClass('selected');
        });
    });
};
$(document).ready(main);
</code>```

答:
1st use $(this).next('.recipes') since they are at the same level. So you could target the recipes next to recipe you clicked.

2nd use CSS to initially hide all recipes, because CSS is loaded much faster than script so you won't see that hidden drop-down flashing for 0.5 sec.

```<code>.recipes {
  display: none;
}
</code>```

3rd li must have a parent of ul or ol or menu so do it this like:

```<code>  <ul class="recipe" id="recipe01">
    <li>Cocktail</li>
  </ul>
</code>```

with css:

```<code>.recipe {
  margin: 0;
  padding-left: 25px;
}
</code>```

$(document).ready(function() {
  $('.recipe').click(function() {
    $(this).next('.recipes').toggle("slow").toggleClass('selected');
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.recipes {
  display: none;
}

.recipe {
  margin: 0;
  padding-left: 25px;
}</code>```

Cocktail

          <input type="checkbox"> ingredient 1

          <input type="checkbox"> ingredient 2

          <input type="checkbox"> ingredient 3

          <input type="checkbox"> ingredient 4

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Main Dish

          <input type="checkbox"> ingredient 1

          <input type="checkbox"> ingredient 2

          <input type="checkbox"> ingredient 3

          <input type="checkbox"> ingredient 4

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Dessert

          <input type="checkbox"> ingredient 1

          <input type="checkbox"> ingredient 2

          <input type="checkbox"> ingredient 3

          <input type="checkbox"> ingredient 4

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

```

Body:
So I tried obviously using $('this .classname') but it toggle closes the whole div.
I'm trying to have each div (image is placed) be clicked and only it's ul be opened.

HTML

Cocktail

<input type="checkbox"> ingredient 1

<input type="checkbox"> ingredient 2

<input type="checkbox"> ingredient 3

<input type="checkbox"> ingredient 4

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Main Dish

<input type="checkbox"> ingredient 1

<input type="checkbox"> ingredient 2

<input type="checkbox"> ingredient 3

<input type="checkbox"> ingredient 4

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Dessert

<input type="checkbox"> ingredient 1

<input type="checkbox"> ingredient 2

<input type="checkbox"> ingredient 3

<input type="checkbox"> ingredient 4

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

JS

var main = function() {
    $(document).ready(function () {
        $('ul').hide();
        $('.recipe').click(function () {
            $('.recipes').toggle("slow").toggleClass('selected');
        });
    });
};
$(document).ready(main);

Body:
1st use $(this).next('.recipes') since they are at the same level. So you could target the recipes next to recipe you clicked.

2nd use CSS to initially hide all recipes, because CSS is loaded much faster than script so you won't see that hidden drop-down flashing for 0.5 sec.

.recipes {
  display: none;
}

3rd li must have a parent of ul or ol or menu so do it this like:

  <ul class="recipe" id="recipe01">
    <li>Cocktail</li>
  </ul>

with css:

.recipe {
  margin: 0;
  padding-left: 25px;
}

$(document).ready(function() {
  $('.recipe').click(function() {
    $(this).next('.recipes').toggle("slow").toggleClass('selected');
  });
});

.recipes {
  display: none;
}

.recipe {
  margin: 0;
  padding-left: 25px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-12 col-xs-12">

  <div class="recipePicContainer">
    <div id="checkBoxes">
      <ul class="recipe" id="recipe01">
        <li>Cocktail</li>
      </ul>
      <ul class="recipes">
        <li class="ingredient">
          <input type="checkbox"> ingredient 1</li>
        <li class="ingredient">
          <input type="checkbox"> ingredient 2</li>
        <li class="ingredient">
          <input type="checkbox"> ingredient 3</li>
        <li class="ingredient">
          <input type="checkbox"> ingredient 4</li>
        <li class="instructions">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</li>
      </ul>
    </div>
  </div>

  <div class="recipePicContainer">
    <div class="checkBoxes">
      <ul class="recipe" id="recipe02">
        <li>Main Dish</li>
      </ul>
      <ul class="recipes">
        <li class="ingredient">
          <input type="checkbox"> ingredient 1</li>
        <li class="ingredient">
          <input type="checkbox"> ingredient 2</li>
        <li class="ingredient">
          <input type="checkbox"> ingredient 3</li>
        <li class="ingredient">
          <input type="checkbox"> ingredient 4</li>
        <li class="instructions">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</li>
      </ul>
    </div>
  </div>

  <div class="recipePicContainer">
    <div class="checkBoxes">
      <ul class="recipe" id="recipe03">
        <li>Dessert</li>
      </ul>
      <ul class="recipes">
        <li class="ingredient">
          <input type="checkbox"> ingredient 1</li>
        <li class="ingredient">
          <input type="checkbox"> ingredient 2</li>
        <li class="ingredient">
          <input type="checkbox"> ingredient 3</li>
        <li class="ingredient">
          <input type="checkbox"> ingredient 4</li>
        <li class="instructions">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</li>
      </ul>
    </div>
  </div>

</div>


问:
How to Unset Request Data in CakePHP 3.4
I've tried to search this but I found no luck.

It says that $request->data will be deprecated in 4.0 and suggesting to use $request->getData() instead.

How do I unset request data when we don't have the option to unset it?

This is useful when logging in or registering with password. When they failed the validation, they have to retype the password.

答:
There's a simple way to do that without even touching the request object, and that is by passing an empty string to the controls value option, that way the field will always be empty when it's being rendered:

```<code>$this->Form->control('password', ['value' => ''])
</code>```

That being said, if there really is the need to unset POST data on the request object (which often times indicates that there's something wrong with what you're doing), you can use withParsedBody() to either empty everything:

```<code>$this->request = $this->request->withParsedBody([]);
</code>```

or write back a partial array:

```<code>$data = $this->request->getData();
unset($data['password']);
$this->request = $this->request->withParsedBody($data);
</code>```

This may look a little weird, but as already mentioned, the need to unset data on a request object often times indicates a flaw in your application logic.

Body:
There's a simple way to do that without even touching the request object, and that is by passing an empty string to the controls value option, that way the field will always be empty when it's being rendered:

$this->Form->control('password', ['value' => ''])

That being said, if there really is the need to unset POST data on the request object (which often times indicates that there's something wrong with what you're doing), you can use withParsedBody() to either empty everything:

$this->request = $this->request->withParsedBody([]);

or write back a partial array:

$data = $this->request->getData();
unset($data['password']);
$this->request = $this->request->withParsedBody($data);

This may look a little weird, but as already mentioned, the need to unset data on a request object often times indicates a flaw in your application logic.


问:
Pandas enlargement of multidimensional objects
I want to add row to a multidimensional pd.Series.

```<code>b = pd.Series([1,1,2,3], index = [["digit", "digit", "digit", "digit"], ["one", "one", "two", "three"]])

b
Out[30]:
digit  one      1
       one      1
       two      2
       three    3
dtype: int64
</code>```

Now, when I do

```<code>b.loc["digit"].loc["four"] = 4
</code>```

Nothing happens. There are no errors, but b remains the same.
Though this approach works with single-dimensional Series

答:
You need sort_index because:

PerformanceWarning: indexing past lexsort depth may impact performance.

and then tuple with loc:

```<code>b = b.sort_index()
b.loc[("digit", "four")] = 4
print (b)
digit  one      1
       one      1
       three    3
       two      2
       four     4
dtype: int64
</code>```

Another solution with concat:

```<code>c = pd.Series([4], index=pd.MultiIndex.from_arrays([['digit'],['four']]))
b = pd.concat([b, c])
print (b)
digit  one      1
       one      1
       two      2
       three    3
       four     4
dtype: int64
</code>```

Body:
I want to add row to a multidimensional pd.Series.

b = pd.Series([1,1,2,3], index = [["digit", "digit", "digit", "digit"], ["one", "one", "two", "three"]])

b
Out[30]:
digit  one      1
       one      1
       two      2
       three    3
dtype: int64

Now, when I do

b.loc["digit"].loc["four"] = 4

Nothing happens. There are no errors, but b remains the same.
Though this approach works with single-dimensional Series

Body:
You need sort_index because:

PerformanceWarning: indexing past lexsort depth may impact performance.

and then tuple with loc:

b = b.sort_index()
b.loc[("digit", "four")] = 4
print (b)
digit  one      1
       one      1
       three    3
       two      2
       four     4
dtype: int64

Another solution with concat:

c = pd.Series([4], index=pd.MultiIndex.from_arrays([['digit'],['four']]))
b = pd.concat([b, c])
print (b)
digit  one      1
       one      1
       two      2
       three    3
       four     4
dtype: int64


问:
Slack API: Can't send attachments
I'm trying to send an attachment using Slack's Python Client but whenever I do I fail. I tried sending it with the Tester too but it still didn't work. Either I get {"ok": false,"error": "no_text"} or if I have the text property only the text is going to be sent. This is how I do it. I searched too but didn't found anything.

```<code>       attachment = json.dumps([{"attachments": [{"fallback": "Reddit Message","color": "#448aff","pretext":"You've got a new Message!","author_name": "Reddit","author_link": "https://reddit.com","author_icon": "imageurl","title": "Reddit Message","title_link": "https://reddit.com/message/inbox","text": "This is what I know about it.","fields": [{"title": "Author:","value": str(item.author),"short": "true"},{"title": "Subject: ","value": str(item.subject),"short": "true"},{"title": "Message:","value": str(item.body),"short": "false"}],"footer": "Reddit API","footer_icon": "anotherimageurl"}]})

sc.api_call("chat.postMessage",channel="U64KWRJAU",attachments=attachment,as_user=True)
</code>```

Help would be appreciated. This should make sense but I don't get it why it doesn't work

答:
From your reference, you need to pass attachment as a list. You won't need to have the attachments key in a dict containing the list.

```<code>attachment = json.dumps([
    {
        "fallback": "Reddit Message",
        "color": "#448aff",
        "pretext":"You've got a new Message!",
        "author_name": "Reddit",
        "author_link": "https://reddit.com",
        ....
    }
])

sc.api_call(
    "chat.postMessage", channel="U64KWRJAU",
    attachments=attachment, as_user=True)
</code>```

Title: Slack API: Can't send attachments

Body:
I'm trying to send an attachment using Slack's Python Client but whenever I do I fail. I tried sending it with the Tester too but it still didn't work. Either I get {"ok": false,"error": "no_text"} or if I have the text property only the text is going to be sent. This is how I do it. I searched too but didn't found anything.

       attachment = json.dumps([{"attachments": [{"fallback": "Reddit Message","color": "#448aff","pretext":"You've got a new Message!","author_name": "Reddit","author_link": "https://reddit.com","author_icon": "imageurl","title": "Reddit Message","title_link": "https://reddit.com/message/inbox","text": "This is what I know about it.","fields": [{"title": "Author:","value": str(item.author),"short": "true"},{"title": "Subject: ","value": str(item.subject),"short": "true"},{"title": "Message:","value": str(item.body),"short": "false"}],"footer": "Reddit API","footer_icon": "anotherimageurl"}]})

sc.api_call("chat.postMessage",channel="U64KWRJAU",attachments=attachment,as_user=True)

Help would be appreciated. This should make sense but I don't get it why it doesn't work

Body:
From your reference, you need to pass attachment as a list. You won't need to have the attachments key in a dict containing the list.

attachment = json.dumps([
    {
        "fallback": "Reddit Message",
        "color": "#448aff",
        "pretext":"You've got a new Message!",
        "author_name": "Reddit",
        "author_link": "https://reddit.com",
        ....
    }
])

sc.api_call(
    "chat.postMessage", channel="U64KWRJAU",
    attachments=attachment, as_user=True)


问:
mysql: most efficient method to store parameters with unknown type (string/int) to the db
I have a messaging system that contains default templates. for example:

you won X coins

friend X wants to share the url Y with you

so the number of parameters varies in each message/template type.

I thought of 4 types of solutions to resolve the issue:

creating a parameters table and represent each parameter type as a string.
the problem here that user_ids will be represented as strings so probably joins will be slower. e

creating a parameters table that each row contains the following a boolean that tells if the parameter is an int or a string, and 2 other columns one type text and the other type INT. so here we're kind of wasting space because whenever we use an int parameter the row contains an unused string cell.

not to create a parameters table at all, each notification contains a parameters string that contains each needed parameter with a seperator ;. this one may be the slowest solution.

creating two different tables for each time of parameters: notification_param_int and notification_param_string and a table that contains each parameter in the notification to the relevant table. this solution may be slower then solution 2 because i need to check from which table to fetch the information first.

are there any other options I did not think about ?
if I don't care about space, only about speed, which method should I take ?

I'm not a MySQL expert so the conclusion of each method may be wrong.

Any information would be greatly appreciated.

thanks you!

答:
Often, when having a open-ended property table as you describe, you'll discover that some of the properties are more important (either they need to always be there, or they need to be fast).  In that case, promote those to fields in the main record.

I could imagine UID being that.  It would be a problem later if you needed to have a list of UID (friends), but then you could also promote friends to its own table.

In your case, I'd just opt for #1 or #2 and think about promoting important properties if the need arises.


问:
Angular 2 - Router reloading component
I am having problems with what looks to be the Angular router reloading the component in <router-outlet></router-outlet> and causing undesired results. Does anyone have any ideas on how to fix this?

Plunker link: https://plnkr.co/edit/yRCzbsxE0ftzqrDeRT69?p=preview

Edit: How can I change it so the variable isn't reinitialized when alternating between link 'one' and 'two'

答:
this result is the correct according to your code.

at the first load

```<code>constructor() {
   this.fromParent = 'default'
}
</code>```

the fromParent is set to default and the cousin component is initialized.

```<code>Click1

Click2
</code>```

lets follow this scenario and see how does angular react to it:

click1 => angular route to /one, but parent component is already there, so no need to reloaded again, so it act normally at the first click.

click2 => angular route to /two, the route changed so angular reload the parent component, so its reload all your application and reset all variable to default

when routing to some component, angular initialize this component, and in your case, your parent component is reInitialized again, which means reInitialize the cousin component.

Title: Angular 2 - Router reloading component

Body:
this result is the correct according to your code.

at the first load

constructor() {
   this.fromParent = 'default'
}

the fromParent is set to default and the cousin component is initialized.

Click1

Click2

lets follow this scenario and see how does angular react to it:

click1 => angular route to /one, but parent component is already there, so no need to reloaded again, so it act normally at the first click.

click2 => angular route to /two, the route changed so angular reload the parent component, so its reload all your application and reset all variable to default

when routing to some component, angular initialize this component, and in your case, your parent component is reInitialized again, which means reInitialize the cousin component.


问:
IDE show classes independently
So I'm fairly new in the coding world and I'm currently using PyCharm in developing a personal project.

This project has started to be somewhat "large" with many classes and I thought about splitting them up into module files like having MyClass in MyClass.py and use "from MyClass import *" in my main .py-file.

But I rather quickly realized that circular importing was a pain in the ass and that it was not really helping me in making the code more structured. I also found I could hide/collapse classes in my main file with the [-] which basically solved the bulk of my initial problem.

However, it got me thinking. I still liked the idea of visually having the classes in separate windows so I wondered if there's any IDE that actually do or allow this.

TL;DR: Is there an IDE which visually allow me to visually separate parts of code, like classes, in separate windows/pages, but still have them in the same py-file "physically"? Naturally with fully functional refactoring and code completion maintained.

答:
You can split PyCharm's window and open the same file in several tabs, viewing the part of the file you want in each.
Open the file once, right click on the tab's title, then click Split Vertically / Horizontally.</p>

Title: IDE show classes independently


问:
Formatting Numbers without locale
The user can specify a file output format at the GUI. Especially he can define a number format. The first idea was to let him specify a format which can be used with DecimalFormat, but DecimalFormat has at least two main disadvantages for my usecase:

It uses the locale of the user, so ##.## converts the '.' to ',' in germany.

There is no difference between before comma and after comma numbers, so you cannot format 12.50 to 1250. Also required in my usecase.

StringFormat cannot do this either. So my question is if you know any library which already handles this problem, or do i have to program a simple formatter myself.

答:
```<code>DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.ENGLISH);
DecimalFormat decimalFormat = new DecimalFormat("##.##");
decimalFormat.setDecimalFormatSymbols(otherSymbols);
</code>```

Title: Formatting Numbers without locale


问:
How Do I disable a clicked button in AngularJS?

//here we crate the module for the CRUD application here
var app= angular.module("shoppingApp", []);
    app.controller("UserController",  ['$rootScope',    '$scope','$filter','$window',
  function($scope,$rootScope, $filter, $window) {

  /**
  * @Summary:addProductInCart , to get the wishList of the userSection.
  * @param:   pname,bname
  * @return:  count $scope.pricerange =" 0 - 5000"
  * @Description:
  */
  $scope.prouctInCartList     = [];
  $scope.item                 = {};
  $scope.prouctInCartList     = [];
  $scope.totalAmountDisplay   = 0;
  $scope.countProducts        = 0;
  $scope.isDisabled  = false;

  $scope.addProductInCart = function(index, item) {
   $scope.isDisabled = true;
   var data = {
   index :index,
   cart : item
   }

    $rootScope.prouctInCartList.push(data);
    localStorage.setItem('productObject',                   JSON.stringify($rootScope.prouctInCartList));

    for(index in $scope.prouctInCartList) {
      var orderDto = $scope.prouctInCartList[index];
      var totalAmount = 0;
      if(orderDto != undefined && orderDto != null) {
          totalAmount = totalAmount + orderDto.cart.range *    orderDto.cart.quantity;
   }
  }

  $scope.totalAmountDisplay  = $scope.totalAmountDisplay + totalAmount;
   $scope.countProducts ++;
  }}
 ]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html ng-app="shoppingApp">
<title>W3.CSS Template</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="app/controller.js"></script>
<script data-require="jquery@*" data-semver="2.0.3" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>

<link rel="stylesheet" href="https://www.w3schools.com/lib/w3.css">
<link rel="stylesheet" href="my.css">
<link rel="stylesheet" href="cmn.css">
<div w3-include-html="myFilter.html"></div>
<div w3-include-html="shoppinCart.html"></div>
<div w3-include-html="signup.html"></div>
<body class="topShop" ng-controller="UserController">

 <div class="marginSet w3-row">
      <div id="hideSlowProduct" class="productInfo  w3-col m3  w3-card-4 w3-margin-left"
   ng-repeat="list in filtered = (show | filter: product)filter:brandFilter
| filter :colorFilter">
           <span ng-click="removeItem($event,list)" title="Remove product">
                <i class="fa fa-close" style="font-size:20px; float:right">                </i>
            </span>
          <div class="w3-container">
            <div calss="hover-effect">
              <div class="hover-div">
                 <img class="imageSet" src="{{list.img}}"
     onclick="document.getElementById('openProduct').style.display='block'"
                ng-click="currentImage($index)">
              </div>
            </div>
              <div id="openProduct" class="w3-modal" onclick="this.style.display='none'">
                  <div class="openModal w3-modal-content w3-animate-zoom">
                     <div class="minSet w3-container w3-twothird">
                       <img class="modelOpenImg"  src="{{imageOpen.img}}">
                    </div>
                    <div class=" w3-container w3-third">
                      <table class="w3-table-all w3-hoverable">
                        <thead>
                          <tr class="w3-red">
                            <th>Pname</th>
                            <th>Brand</th>
                            <th>range</th>
                            <th>color</th>
                          </tr>
                        </thead>
                        <tr>
                          <td>{{imageOpen.pname}}</td>
                          <td>{{imageOpen.brand}}</td>
                          <td>{{imageOpen.range}}</td>
                          <td> {{imageOpen.color}}</td>
                        </tr>
                      </table>
                  </div>
                </div>
            </div>
              <div class="container">
                  <div class="fa fa-heart" ng       model="removedInWishList[$index]"
                      ng-show="addedInWishList[$index]"
                      ng-click= "removeInWishList($index, list)">
                  </div>
                  <div class="fa fa-heart-o" ng-model="addedInWishList[$index]"
                       ng-show="!addedInWishList[$index]"
                       ng-click= "addInWishList($index, list)">
                   </div>
                   Add To Cart

                     <span type="radio" class="colorCode w3-right" style="background-color:{{list.colorCode}};"></span>
                    <b>₹{{list.range}}</b>
                                    </p>
              </div>
           </div>
     </div>
  </div>
 </body>
</html>
  </code>```

I have create a shopping website in which user click on the addToCart button product is add into the cart and i have to disabled a clicked button but in my case all the button is disabled how to fix this issue?

  /**
  * @Summary:addProductInCart , to get the addProduct in cart
  * @param:   index,item
  * @return:  NA
  * @Description:
  */
  $scope.item                 = {};
  $scope.prouctInCartList     = [];
  $scope.totalAmountDisplay   = 0;
  $scope.countProducts        = 0;
 $scope.isDisabled = false;

  $scope.addProductInCart = function(index, item) {
   $scope.isDisabled = true;
   var data = {
   index :index,
   cart : item
   }

   $rootScope.prouctInCartList.push(data);
   //Here we will store product array into the localStorage for use another page
 localStorage.setItem('productObject',JSON.stringify($rootScope.prouctInCartList));
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    Add To Cart
    </code>```

答:
You have one variable, $scope.isDisabled for all of your buttons. So, when you set your $scope.isDisabled to true, all of your buttons will have disabled attribute. I made some changes on your code. See it below

  /**
  * @Summary:addProductInCart , to get the addProduct in cart
  * @param:   index,item
  * @return:  NA
  * @Description:
  */
  $scope.item                 = {};
  $scope.prouctInCartList     = [];
  $scope.totalAmountDisplay   = 0;
  $scope.countProducts        = 0;
 $scope.isDisabled = false;

  $scope.addProductInCart = function(index, item) {
   //$scope.isDisabled = true;
                item.isDisabled = true; // since you are passing your item here, you can make it disabled.
   var data = {
   index :index,
   cart : item
   }

   $rootScope.prouctInCartList.push(data);
   //Here we will store product array into the localStorage for use another page
 localStorage.setItem('productObject',JSON.stringify($rootScope.prouctInCartList));
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    Add To Cart
    </code>```

Body:
//here we crate the module for the CRUD application here
var app= angular.module("shoppingApp", []);
    app.controller("UserController",  ['$rootScope',    '$scope','$filter','$window',
  function($scope,$rootScope, $filter, $window) {

  /**
  * @Summary:addProductInCart , to get the wishList of the userSection.
  * @param:   pname,bname
  * @return:  count $scope.pricerange =" 0 - 5000"
  * @Description:
  */
  $scope.prouctInCartList     = [];
  $scope.item                 = {};
  $scope.prouctInCartList     = [];
  $scope.totalAmountDisplay   = 0;
  $scope.countProducts        = 0;
  $scope.isDisabled  = false;

  $scope.addProductInCart = function(index, item) {
   $scope.isDisabled = true;
   var data = {
   index :index,
   cart : item
   }

    $rootScope.prouctInCartList.push(data);
    localStorage.setItem('productObject',                   JSON.stringify($rootScope.prouctInCartList));

    for(index in $scope.prouctInCartList) {
      var orderDto = $scope.prouctInCartList[index];
      var totalAmount = 0;
      if(orderDto != undefined && orderDto != null) {
          totalAmount = totalAmount + orderDto.cart.range *    orderDto.cart.quantity;
   }
  }

  $scope.totalAmountDisplay  = $scope.totalAmountDisplay + totalAmount;
   $scope.countProducts ++;
  }}
 ]);

<!DOCTYPE html>

<title>W3.CSS Template</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" href="https://www.w3schools.com/lib/w3.css">
<link rel="stylesheet" href="my.css">
<link rel="stylesheet" href="cmn.css">

                            Pname
                            Brand
                            range
                            color

                          {{imageOpen.pname}}
                          {{imageOpen.brand}}
                          {{imageOpen.range}}
                           {{imageOpen.color}}

                   Add To Cart

                    ₹{{list.range}}

I have create a shopping website in which user click on the addToCart button product is add into the cart and i have to disabled a clicked button but in my case all the button is disabled how to fix this issue?

  /**
  * @Summary:addProductInCart , to get the addProduct in cart
  * @param:   index,item
  * @return:  NA
  * @Description:
  */
  $scope.item                 = {};
  $scope.prouctInCartList     = [];
  $scope.totalAmountDisplay   = 0;
  $scope.countProducts        = 0;
 $scope.isDisabled = false;

  $scope.addProductInCart = function(index, item) {
   $scope.isDisabled = true;
   var data = {
   index :index,
   cart : item
   }

   $rootScope.prouctInCartList.push(data);
   //Here we will store product array into the localStorage for use another page
 localStorage.setItem('productObject',JSON.stringify($rootScope.prouctInCartList));
    }

    Add To Cart

Body:
You have one variable, $scope.isDisabled for all of your buttons. So, when you set your $scope.isDisabled to true, all of your buttons will have disabled attribute. I made some changes on your code. See it below

  /**
  * @Summary:addProductInCart , to get the addProduct in cart
  * @param:   index,item
  * @return:  NA
  * @Description:
  */
  $scope.item                 = {};
  $scope.prouctInCartList     = [];
  $scope.totalAmountDisplay   = 0;
  $scope.countProducts        = 0;
 $scope.isDisabled = false;

  $scope.addProductInCart = function(index, item) {
   //$scope.isDisabled = true;
                item.isDisabled = true; // since you are passing your item here, you can make it disabled.
   var data = {
   index :index,
   cart : item
   }

   $rootScope.prouctInCartList.push(data);
   //Here we will store product array into the localStorage for use another page
 localStorage.setItem('productObject',JSON.stringify($rootScope.prouctInCartList));
    }

    <a class="w3-btn w3-red" ng-model="item.cart"
        ng-click="item.isDisabled || addProductInCart($index,item)"
        ng-disabled="item.isDisabled">Add To Cart
    </a>


问:
How Can I Split Decimal Value from Integer Value?
Assume i have 4.9 value.

I would like to split 4 and .9 ... How can i do it?

I could isolate 4 by using FLOOR(). What about the .9? How can i isolate it?

I'm using t-sql sql server 2005/2008

答:
```<code>Declare @money money

Set @money = 418.75

Select  convert(int,@money - (@money % 1))  as 'LeftPortion'
       ,convert(int, (@money % 1) * 100)    as 'RightPortion'
</code>```


问:
Capture between round brackets and square brackets
I have a text similar to this:

```<code>[text]
(more text)
(text...)
[text!]
(last text)
</code>```

I need to match the text between () and [].

The output should be something like this:

```<code>[
  "text",
  "more text",
  "text...",
  "text!",
  "last text"
]
</code>```

I already tried /[\[\(](.*?)[\]\)]/ but it didn't work in PHP.

Here is the code if you need it:

```<code> preg_match_all('/[\[\(](.*?)[\]\)]/', $text, $matches, PREG_SET_ORDER, 0);
 var_dump($matches);
</code>```

How do I achieve this using regex in PHP?

Thanks in advance,

Skayo

答:
I would suggest a regex based on a branch reset feature:

```<code>$re = '/(?|\[([^]]*)]|\(([^)]*)\))/';
$str = '[text]
(more text)
(text...)
[text!]
(last text)';

preg_match_all($re, $str, $matches);
</code>```

See the PHP demo

See the regex demo

(?| - start of the branch reset

\[ - a [

([^]]*) - any 0+ chars other than ]

]  - a literal ]

| - or

\( - a literal (

([^)]*) - any 0+ chars other than )

\) - a literal )

) - end of the branch reset group.

Body:
I have a text similar to this:

[text]
(more text)
(text...)
[text!]
(last text)

I need to match the text between () and [].

The output should be something like this:

[
  "text",
  "more text",
  "text...",
  "text!",
  "last text"
]

I already tried /[\[\(](.*?)[\]\)]/ but it didn't work in PHP.

Here is the code if you need it:

 preg_match_all('/[\[\(](.*?)[\]\)]/', $text, $matches, PREG_SET_ORDER, 0);
 var_dump($matches);

How do I achieve this using regex in PHP?

Thanks in advance,

Skayo

Body:
I would suggest a regex based on a branch reset feature:

$re = '/(?|\[([^]]*)]|\(([^)]*)\))/';
$str = '[text]
(more text)
(text...)
[text!]
(last text)';

preg_match_all($re, $str, $matches);

See the PHP demo

See the regex demo

(?| - start of the branch reset

\[ - a [

([^]]*) - any 0+ chars other than ]

]  - a literal ]

| - or

\( - a literal (

([^)]*) - any 0+ chars other than )

\) - a literal )

) - end of the branch reset group.


问:
How to prevent EasyPHP DevServer 16 to add prefix 'edsa' for alias
I'm coming from EasyPHP DevServer 14, with a lot of websites developed for many customers, and I used to have a custom alias 'workspace', but now, in EasyPHP 16, they made obligatory the use of a prefix 'edsa' in every defined alias, breaking my WordPress installations. How could I solve that?</p>

答:
It seems to be hardcoded in a code (...), but fortunately the code is in php, so you can just edit it out and be OK (until the update I guess).
Go to the eds-dashboard subdirectory and edit the index.php file.

In the current version (17), the code is on the line 95:

```<code>$new_alias[0]['alias_name'] = 'edsa-' . $_POST['alias_name'];
</code>```

Just remove the silly part from it

```<code>$new_alias[0]['alias_name'] = $_POST['alias_name'];
</code>```

save the file and you should be done.

Tested on windows

Body:
It seems to be hardcoded in a code (...), but fortunately the code is in php, so you can just edit it out and be OK (until the update I guess).
Go to the eds-dashboard subdirectory and edit the index.php file.

In the current version (17), the code is on the line 95:

$new_alias[0]['alias_name'] = 'edsa-' . $_POST['alias_name'];

Just remove the silly part from it

$new_alias[0]['alias_name'] = $_POST['alias_name'];

save the file and you should be done.

Tested on windows


问:
Building Darwin 16.6 from source?
Put succinctly I need a base for my system, since it was built on macOS Darwin seems like the logical choice as it will require the least porting effort. I know you can download up to Darwin 8.0.1 from Apple, and the full source tree is available for up to 10.0, however v8 is too old and lacks many standard modern features (i.e. a password system that doesn't restrict the root user to 10 characters, or support for the case-sensitive version of HFS+). I've tried building Darwin 9/10/11/12 from source using darwinbuild, but it always fails for various server-side reasons.

There has to be some way to create the equivalent of a vanilla Darwin 16 image. Perhaps taking an existing copy of macOS and stripping away all the closed-source stuff? Building the source that Apple provides at Apple Open Source Repository and substituting the rest of the packages required for the OS to function with source from another BSD distro? Taking an existing copy of FreeBSD and substituting the kernel with XNU? There has to be some way. Any ideas or thoughts on the ideas I suggested are welcome. Thanks.

答:
The last xnu build instructions are for El Capitan (Darwin 15) but you might be able to follow them for Sierra (Darwin 16). The latest source available at time of writing is for 10.12.4, which isn't overly out of date.

This gets you most of the kernel of shipping macOS. It doesn't get you the driver stack - especially the SATA/AHCI stack is not open source, which could be a problem. (One of these days I'll get around to publishing our full virtio driver stack including virtio-blk and virtio-scsi drivers, with which you should be able to run without SATA in Qemu/KVM at least.)

I have no idea about getting a useful userland going - macOS/OSX uses launchd as its "init" process, and the last published source code for that is some years old. I don't know if it will need some tweaking to get it working on newer kernels.

Title: Building Darwin 16.6 from source?


问:
jQuery: Selecting by class and input type
I would like to select a set of elements that are both of a certain input type (say, a checkbox) and have a certain class using jQuery.  However, when I try the following:

```<code> $("input:checkbox .myClass")
</code>```

I don't get any items returned.  How can I accomplish this in jQuery?

答:
Just in case any dummies like me tried the suggestions here with a button and found nothing worked, you probably want this:</p>

```<code>$(':button.myclass')
</code>```

Body:
I would like to select a set of elements that are both of a certain input type (say, a checkbox) and have a certain class using jQuery.  However, when I try the following:

 $("input:checkbox .myClass")

I don't get any items returned.  How can I accomplish this in jQuery?

Body:
Just in case any dummies like me tried the suggestions here with a button and found nothing worked, you probably want this:

$(':button.myclass')


问:
Domain object validation vs view model validation
I am using ASP.NET MVC 3 and I am using FluentValidation to validate my view models.  I am just a little concerned that I might not be on the correct track.  As far as what I know, model validation should be done on the domain object.  Now with MVC you might have multiple view models that are similar that needs validation.  What happens if a property from a domain object occurs in more than one view model?  Now you are validating the same property twice, and they might not even be in sync.  So if I have a User domain object then I would like to do validation on this object.  Now what happens if I have UserAViewModel and UserBViewModel, so now it is multiple validations that needs to be done.

In my News class I have a property called Title, which is a required field. On my view model I also have a Title property, I use AutoMapper to map the News and NewsViewModel. So this validation is happening twice. When does domain model validation occur and when does view model validation occur?

The scenario above is just an example, so please don't critise on it.

答:
What happens if a property from a
  domain object occurs in more than one
  view model?

This shouldn't happen.  View models should be totally divorced from your domain.

Does this answer your question?


问:
Jquery document.ready is not responding
The document.ready function is not responding while my page load.
And also i am facing problem with .submit function. Please help.
Please help me to rewrite this code.
I just want to design a form in php to check whether the given email id is already present in the database or not using jquery ajax
Please help .... ! I am getting late in my school project.

```<code> $(document).ready(function(){
                alert("Working..");
                $("#userSubmit").submit(function(){
                    alert("Working ..");
                    var email=document.getElementById("userEamil").value;
                    $.ajax({
                        type:'POST',
                        data:"SELECT * FROM user WHERE userEmail='"+email+"'",
                        url:'common1.php',
                        success:function(data)
                        {
                            $result=$.parseJSON($data);
                            alert($result);
                            return false;
                        },
                        error:function(data)
                        {
                            alert(data);
                            return false;
                        }
                    });
                });
            });
</code>```

答:
Here you go with the solution https://jsfiddle.net/1uor0gxf/1/

$(document).ready(function(){
    $("#userSubmit").click(function(){
        var email = $("userEamil").val();
        $.ajax({
            type:'POST',
            data:`SELECT * FROM user WHERE userEmail='${email}'`,
            url:'common1.php',
            success:function(data)
            {
                $result=$.parseJSON($data);
                alert($result);
                return false;
            },
            error:function(data)
            {
                alert(data);
                return false;
            }
        });
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="">
  <input type="text" id="userEamil" />
  <input type="button" id="userSubmit" value="Submit" />
</form></code>```

Title: Jquery document.ready is not responding

Body:
The document.ready function is not responding while my page load.
And also i am facing problem with .submit function. Please help.
Please help me to rewrite this code.
I just want to design a form in php to check whether the given email id is already present in the database or not using jquery ajax
Please help .... ! I am getting late in my school project.

 $(document).ready(function(){
                alert("Working..");
                $("#userSubmit").submit(function(){
                    alert("Working ..");
                    var email=document.getElementById("userEamil").value;
                    $.ajax({
                        type:'POST',
                        data:"SELECT * FROM user WHERE userEmail='"+email+"'",
                        url:'common1.php',
                        success:function(data)
                        {
                            $result=$.parseJSON($data);
                            alert($result);
                            return false;
                        },
                        error:function(data)
                        {
                            alert(data);
                            return false;
                        }
                    });
                });
            });

Body:
Here you go with the solution https://jsfiddle.net/1uor0gxf/1/

$(document).ready(function(){
    $("#userSubmit").click(function(){
        var email = $("userEamil").val();
        $.ajax({
            type:'POST',
            data:`SELECT * FROM user WHERE userEmail='${email}'`,
            url:'common1.php',
            success:function(data)
            {
                $result=$.parseJSON($data);
                alert($result);
                return false;
            },
            error:function(data)
            {
                alert(data);
                return false;
            }
        });
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="">
  <input type="text" id="userEamil" />
  <input type="button" id="userSubmit" value="Submit" />
</form>


问:
Prism VM binding with View within Page code behind
Using Xamarin Forms & PCL

I saw a lot of examples and snippets About binding VM with View in the Page.Xaml

using this block

```<code>xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
      prism:ViewModelLocator.AutowireViewModel="True"
</code>```

And what if I want to bind the view model within the page code behind (Page.cs).

答:
You just can new the viewmodel and set it to the BindingContext.

```<code>public Page()
{
    InitializeComponent();
    this.BindingContext = new MyViewModel();
}
</code>```

==== EDITED ====

If your viewmodel is with parameter that need to dependency inject and you want to resolve it correctly.

App.xaml.cs

```<code>protected override void OnInitialized()
{
    ...
    Microsoft.Practices.Unity.UnityContainerExtensions.RegisterType<IMyViewModel, MyViewModel);
    ...
}
</code>```

Page.xaml.cs

```<code>public Page()
{
    InitializeComponent();
    var viewModel = Microsoft.Practices.Unity.UnityContainerExtensions.Resolve<IMyViewModel>(((App)Application.Current).Container);
    this.BindingContext = viewModel;
}
</code>```

Body:
Using Xamarin Forms & PCL

I saw a lot of examples and snippets About binding VM with View in the Page.Xaml

using this block

xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
      prism:ViewModelLocator.AutowireViewModel="True"

And what if I want to bind the view model within the page code behind (Page.cs).

Body:
You just can new the viewmodel and set it to the BindingContext.

public Page()
{
    InitializeComponent();
    this.BindingContext = new MyViewModel();
}

==== EDITED ====

If your viewmodel is with parameter that need to dependency inject and you want to resolve it correctly.

App.xaml.cs

protected override void OnInitialized()
{
    ...
    Microsoft.Practices.Unity.UnityContainerExtensions.RegisterType<IMyViewModel, MyViewModel);
    ...
}

Page.xaml.cs

public Page()
{
    InitializeComponent();
    var viewModel = Microsoft.Practices.Unity.UnityContainerExtensions.Resolve<IMyViewModel>(((App)Application.Current).Container);
    this.BindingContext = viewModel;
}