问:
Applying keras CNN to new dataset
Complete Keras/ML beginner here!

Given a successfully trained NN (CNN or otherwise) resulting in my_model.h5, I can load the model as

```<code>from keras import load_model
model = load_model("my_model.h5")
</code>```

Loading a new dataset on which I simply want to apply my NN (not train or validate), how do I do that? As far as I understand, for each sample I feed in, I should be able to get out a score between 0 and 1 quantifying the NN's confidence in that sample being signal-like. How do I get those numbers, e.g. in the form {sample1: score, sample2: score,...}?

Any help much appreciated!

答:
This is it:

```<code>results = model.predict(inputData)
</code>```

The inputData must have the same number of dimensions that you training data had, and the shapes must be compatible.

As it's standard, the samples are in the first dimension.

```<code>for res in results:
    #res is the score for a sample
</code>```

Title: Applying keras CNN to new dataset

Body:
Complete Keras/ML beginner here!

Given a successfully trained NN (CNN or otherwise) resulting in my_model.h5, I can load the model as

from keras import load_model
model = load_model("my_model.h5")

Loading a new dataset on which I simply want to apply my NN (not train or validate), how do I do that? As far as I understand, for each sample I feed in, I should be able to get out a score between 0 and 1 quantifying the NN's confidence in that sample being signal-like. How do I get those numbers, e.g. in the form {sample1: score, sample2: score,...}?

Any help much appreciated!

Body:
This is it:

results = model.predict(inputData)

The inputData must have the same number of dimensions that you training data had, and the shapes must be compatible.

As it's standard, the samples are in the first dimension.

for res in results:
    #res is the score for a sample


来源: stackexchange

问:
creating pagination for Magento CMS pages
On the Magento Content Management Services CMS.
How can i create a simple pagination for the pages that i have? Whether it's Previous/Next or just numbering

I was able to do it with this

        3
        3

        empty6
        one_column5
        two_columns_left4
        two_columns_right4
        three_columns3
        product_list_toolbar

getting

But i don't want it for products, i want it for regular text, like blog.

Thanks in advance

答:
not sure what you want to achieve.
In pure theory you can use pager block on any collection

(untested)

```<code>$collection = Mage::getModel('cms/page')->getCollection();

$pager = $this->getLayout()->createBlock('page/html_pager', 'cms.page.pager')
            ->setCollection($collection);
$this->setChild('pager', $pager);

$collection->load();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
not sure what you want to achieve.
In pure theory you can use pager block on any collection

(untested)

$collection = Mage::getModel('cms/page')->getCollection();

$pager = $this->getLayout()->createBlock('page/html_pager', 'cms.page.pager')
            ->setCollection($collection);
$this->setChild('pager', $pager);

$collection->load();


问:
Shared Preferences Not Applying Changes
I have an activity (A) that checks my server for APK updates. When this function is called, whether there is or is not an update, I need the shared preferences to be edited so the application knows to skip or run the actual update activity (B). Question 1 is, why are the shared preferences not being edited by activity (A)? Question 2 is, if they are being edited, why isn't activity (B) reading them?

Thank You in advance!

Shared preferences should be edited here (Activity (A)):

```<code>    private void parseJson(String result) {
    try {

        JSONObject obj = new JSONObject(result);
        String updateMessage = obj.getString(Constants.APK_UPDATE_CONTENT);
        String apkUrl = obj.getString(Constants.APK_DOWNLOAD_URL);
        int apkCode = obj.getInt(Constants.APK_VERSION_CODE);

        int versionCode = AppUtils.getVersionCode(mContext);

        if (apkCode > versionCode) {
            if (mType == Constants.TYPE_NOTIFICATION) {
                showNotification(mContext, updateMessage, apkUrl);
            } else if (mType == Constants.TYPE_DIALOG) {
                SharedPreferences pref = mContext.getSharedPreferences("ActivityUpdatePREF", Context.MODE_PRIVATE);
                SharedPreferences.Editor ed = pref.edit();
                ed.putBoolean("activity_update", true);
                ed.apply();
                showDialog(mContext, updateMessage, apkUrl);
            }
        } else if (mShowProgressDialog) {
            SharedPreferences pref = mContext.getSharedPreferences("ActivityUpdatePREF", Context.MODE_PRIVATE);
            SharedPreferences.Editor ed = pref.edit();
            ed.putBoolean("activity_update", false);
            ed.apply();
            Toast.makeText(mContext, mContext.getString(R.string.android_auto_update_toast_no_new_update), Toast.LENGTH_SHORT).show();
        }

    } catch (JSONException e) {
        Log.e(Constants.TAG, "parse json error");
    }
}
</code>```

Activity (B):

```<code>        SharedPreferences pref = getSharedPreferences("ActivityUpdatePREF", Context.MODE_PRIVATE);
    if(pref.getBoolean("activity_update", false)){
        Intent intent = new Intent(this, Main.class);
        deleteCache(getApplicationContext());
        startActivity(intent);
        finish();
    } else {
        functionUp();
    }
</code>```

答: Use ed.commit() instead of ed.apply()</p>

Title: Shared Preferences Not Applying Changes

Body:
I have an activity (A) that checks my server for APK updates. When this function is called, whether there is or is not an update, I need the shared preferences to be edited so the application knows to skip or run the actual update activity (B). Question 1 is, why are the shared preferences not being edited by activity (A)? Question 2 is, if they are being edited, why isn't activity (B) reading them?

Thank You in advance!

Shared preferences should be edited here (Activity (A)):

    private void parseJson(String result) {
    try {

        JSONObject obj = new JSONObject(result);
        String updateMessage = obj.getString(Constants.APK_UPDATE_CONTENT);
        String apkUrl = obj.getString(Constants.APK_DOWNLOAD_URL);
        int apkCode = obj.getInt(Constants.APK_VERSION_CODE);

        int versionCode = AppUtils.getVersionCode(mContext);

        if (apkCode > versionCode) {
            if (mType == Constants.TYPE_NOTIFICATION) {
                showNotification(mContext, updateMessage, apkUrl);
            } else if (mType == Constants.TYPE_DIALOG) {
                SharedPreferences pref = mContext.getSharedPreferences("ActivityUpdatePREF", Context.MODE_PRIVATE);
                SharedPreferences.Editor ed = pref.edit();
                ed.putBoolean("activity_update", true);
                ed.apply();
                showDialog(mContext, updateMessage, apkUrl);
            }
        } else if (mShowProgressDialog) {
            SharedPreferences pref = mContext.getSharedPreferences("ActivityUpdatePREF", Context.MODE_PRIVATE);
            SharedPreferences.Editor ed = pref.edit();
            ed.putBoolean("activity_update", false);
            ed.apply();
            Toast.makeText(mContext, mContext.getString(R.string.android_auto_update_toast_no_new_update), Toast.LENGTH_SHORT).show();
        }

    } catch (JSONException e) {
        Log.e(Constants.TAG, "parse json error");
    }
}

Activity (B):

        SharedPreferences pref = getSharedPreferences("ActivityUpdatePREF", Context.MODE_PRIVATE);
    if(pref.getBoolean("activity_update", false)){
        Intent intent = new Intent(this, Main.class);
        deleteCache(getApplicationContext());
        startActivity(intent);
        finish();
    } else {
        functionUp();
    }

Body: Use ed.commit() instead of ed.apply()


问:
Copy files from a directory which name changes everyday
There's a directory on my nas with this path: \nasname\Software\Build1.0\
In this directory you'll find the software components.

The name of the directory changes everyday, for example it's 6.95a build xxxx now. I want to copy the content of the directory while running my script to a test set up. If it would have the same name everyday, It would be:

```<code>Copy-Item \\nasname\Software\Build1.0\file1.exe \\pc1\DATA\destinationfolder
Copy-Item \\nasname\Software\Build1.0\file2.exe \\pc1\DATA\destinationfolder
Copy-Item \\nasname\Software\Build1.0\file3.exe \\pc1\DATA\destinationfolder
Copy-Item \\nasname\Software\Build1.0\file4.exe \\pc1\DATA\destinationfolder
</code>```

The Build1.0 part changes a lot, so I would like to have that bit wildcarded.
In \\nasname\Software are 2 directories, build1.0 and Old.

So it should be \\nasname\software\***\file1.exe etc, but it must not choose the OLD directory!

I also tried creating something like choose directory which is not "old" or only copy files -notin "old" but it can't seem to get it working.

答:
You can use wildcards in the path like so:

```<code>Copy-Item \\nasname\Software\Build*\file1.exe \\pc1\DATA\destinationfolder
Copy-Item \\nasname\Software\Build*\file2.exe \\pc1\DATA\destinationfolder
Copy-Item \\nasname\Software\Build*\file3.exe \\pc1\DATA\destinationfolder
Copy-Item \\nasname\Software\Build*\file4.exe \\pc1\DATA\destinationfolder
</code>```

Or if there's only the four files you want to copy you can wildcard the file names too and use a one liner:

```<code>Copy-Item \\nasname\Software\Build*\file*.exe \\pc1\DATA\destinationfolder
</code>```

Body:
There's a directory on my nas with this path: \nasname\Software\Build1.0\
In this directory you'll find the software components.

The name of the directory changes everyday, for example it's 6.95a build xxxx now. I want to copy the content of the directory while running my script to a test set up. If it would have the same name everyday, It would be:

Copy-Item \\nasname\Software\Build1.0\file1.exe \\pc1\DATA\destinationfolder
Copy-Item \\nasname\Software\Build1.0\file2.exe \\pc1\DATA\destinationfolder
Copy-Item \\nasname\Software\Build1.0\file3.exe \\pc1\DATA\destinationfolder
Copy-Item \\nasname\Software\Build1.0\file4.exe \\pc1\DATA\destinationfolder

The Build1.0 part changes a lot, so I would like to have that bit wildcarded.
In \\nasname\Software are 2 directories, build1.0 and Old.

So it should be \\nasname\software\***\file1.exe etc, but it must not choose the OLD directory!

I also tried creating something like choose directory which is not "old" or only copy files -notin "old" but it can't seem to get it working.

Body:
You can use wildcards in the path like so:

Copy-Item \\nasname\Software\Build*\file1.exe \\pc1\DATA\destinationfolder
Copy-Item \\nasname\Software\Build*\file2.exe \\pc1\DATA\destinationfolder
Copy-Item \\nasname\Software\Build*\file3.exe \\pc1\DATA\destinationfolder
Copy-Item \\nasname\Software\Build*\file4.exe \\pc1\DATA\destinationfolder

Or if there's only the four files you want to copy you can wildcard the file names too and use a one liner:

Copy-Item \\nasname\Software\Build*\file*.exe \\pc1\DATA\destinationfolder


问:
rxjs: how to evenly space rendering of responses via Observables

I'm working on a turn-based game in Angular that communicates to a backend via a socket.io implementation. In my component, I am listening for several types of communication from the server, each communication gives information on how to update my view to reflect the current state of the data in the server.

Right now, updates are immediately applied to the component's data. However I'd prefer to render each update with some delay in-between, so that the user has time to see the effect of each update.

(See my image at top for essentially what I'm trying to do)

I believe that I would achieve this via the subscribeOn operator, but unsure of how to specify my 'interval' n.

```<code>const example = Rx.Observable
  .create(observer => {
    observer.next(0);
    observer.next(1);
    observer.next(2);
    setTimeout(() => {
      observer.next(3);
      observer.next(4);
      observer.complete();
    }, 2500);
  });

const source = example
  .subscribeOn(Scheduler.timeout);

source.subscribe(console.log);
</code>```

答:
Use the concatMap operator as follows:

const nInterval = 500;

const example$ = Rx.Observable.from([0, 1, 2])
  .concat(Rx.Observable.from([3,4]).delay(2500));

const source$ = example$
  .concatMap(item =>
    Rx.Observable.of(item)
      .concat(
         Rx.Observable.of('ignored')
           .delay(nInterval)
           .ignoreElements()
      )
  );

source$.subscribe(console.log);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.2/Rx.min.js"></script></code>```

Body:
I'm working on a turn-based game in Angular that communicates to a backend via a socket.io implementation. In my component, I am listening for several types of communication from the server, each communication gives information on how to update my view to reflect the current state of the data in the server.

Right now, updates are immediately applied to the component's data. However I'd prefer to render each update with some delay in-between, so that the user has time to see the effect of each update.

(See my image at top for essentially what I'm trying to do)

I believe that I would achieve this via the subscribeOn operator, but unsure of how to specify my 'interval' n.

const example = Rx.Observable
  .create(observer => {
    observer.next(0);
    observer.next(1);
    observer.next(2);
    setTimeout(() => {
      observer.next(3);
      observer.next(4);
      observer.complete();
    }, 2500);
  });

const source = example
  .subscribeOn(Scheduler.timeout);

source.subscribe(console.log);

Body:
Use the concatMap operator as follows:

const nInterval = 500;

const example$ = Rx.Observable.from([0, 1, 2])
  .concat(Rx.Observable.from([3,4]).delay(2500));

const source$ = example$
  .concatMap(item =>
    Rx.Observable.of(item)
      .concat(
         Rx.Observable.of('ignored')
           .delay(nInterval)
           .ignoreElements()
      )
  );

source$.subscribe(console.log);

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.2/Rx.min.js"></script>


问:
Angular 2 animations style function in state vs transition vs animate
I'm very confused. What is the difference between the style() function inside a state()

```<code>state('inactive', style({
   backgroundColor: '#eee',
   transform: 'scale(1)'
 })),
</code>```

and a style() function inside transition()

```<code> transition('inactive => *', [
    style({ transform: 'scale3d(.3, .3, .3)' }),
    animate(100)
 ]),
</code>```

and a style() function inside animation()

```<code> animate(100, style({ transform: 'scale3d(.0, .0, .0)' }))
</code>```

答:
This is what the Angular Animations documentation says about it :

1. style() inside state()

These state definitions specify the end styles of each state. They are
  applied to the element once it has transitioned to that state, and
  stay as long as it remains in that state. In effect, you're defining
  what styles the element has in different states.

So these styles defined inside a state are the ones before and after the animation, at some given state.

2. style() inside transition()

You can also apply a style during an animation but not keep it around
  after the animation finishes. You can define such styles inline, in
  the transition.

These styles are applied only during the animation time.

3. style() inside animate()

animate specifies an animation step that will apply the provided
  styles data for a given amount of time based on the provided timing
  expression value.

The styles given inside animate will take some specific time to get applied during the animation

Body:
I'm very confused. What is the difference between the style() function inside a state()

state('inactive', style({
   backgroundColor: '#eee',
   transform: 'scale(1)'
 })),

and a style() function inside transition()

 transition('inactive => *', [
    style({ transform: 'scale3d(.3, .3, .3)' }),
    animate(100)
 ]),

and a style() function inside animation()

 animate(100, style({ transform: 'scale3d(.0, .0, .0)' }))


问:
Setting a timer with different values
I currently am using a single timer. This timer is set so every two seconds it will switch to the next case in the case switch. However I now want to be able to set the timer to a different amount of seconds. I would like to have three or four more different values.
I know I can create new timers and then from that get the event handler for each one however I don't want to do that here.
Is there a way that I can set a single timer to different values?
The code I currently have is listed below: </p>

```<code>Clock = new Timer(2000);
           Clock.Elapsed += Clock_Elapsed;
            Clock.Enabled = true;
            Clock.Start();

 private void Clock_Elapsed(object sender, ElapsedEventArgs e)
        {
            switch (CurrentDevice)
            {
                case (Devices.WSS):
                    if (OurWSS.CurrentComponent != null)
                    {
                        OurRobot.LoadComponent(OurComponent);
                        OurWSS.UnLoad();
                    }
                    CurrentDevice = Devices.Robot
                    break;
                case (Devices.Robot):
                    if (OurRobot.CurrentComponent != null)
                    {
                        OurMachine.LoadComponent(OurComponent);
                        OurRobot.UnLoad();
                    }
                    CurrentDevice = Devices.Machine;
                    break;
                case (Devices.Machine):
                    if (OurMachine.CurrentComponent != null)
                    {
                        OurRobot.LoadComponent(OurComponent);
                        //OurComponent.GetCurrentOperation();
                        OurMachine.UnLoad();
                    }
                    CurrentDevice = Devices.RobotOut;
                    break;
                case (Devices.RobotOut):
                    if (OurRobot.CurrentComponent != null)
                    {
                        OurWSS.LoadComponent(OurComponent);
                        OurRobot.UnLoad();
                    }
                    CurrentDevice = Devices.WSS;
                    break;
            }
        }
</code>```

答:
You can't set a single timer to return multiple intervals, but if the intervals you want are multiples of some single value it would be easy enough to ignore the ticks until the desired interval occurs.

There are many possible ways to do this. Here's an example I've used in Unity game programming: imagine you want to respond on 1-second, 5-second, and 10-second intervals. First, initialize a 3-slot array containing the current time plus 1, 5, and 10 seconds, and set the timer to 1-second intervals. On each timer-tick test whether the current time is equal to or greater than each slot, and if true, execute the corresponding action and update the array slot to the next target time for that slot's interval.

The updated target time could be relative to the real current time or relative to the time stored in the slot, depending on whether it's more important to get as close as possible to fixed or relative intervals.

This is also easily abstracted into a class if you'll be doing a lot of this.

Title: Setting a timer with different values

Body:
I currently am using a single timer. This timer is set so every two seconds it will switch to the next case in the case switch. However I now want to be able to set the timer to a different amount of seconds. I would like to have three or four more different values.
I know I can create new timers and then from that get the event handler for each one however I don't want to do that here.
Is there a way that I can set a single timer to different values?
The code I currently have is listed below:

Clock = new Timer(2000);
           Clock.Elapsed += Clock_Elapsed;
            Clock.Enabled = true;
            Clock.Start();

 private void Clock_Elapsed(object sender, ElapsedEventArgs e)
        {
            switch (CurrentDevice)
            {
                case (Devices.WSS):
                    if (OurWSS.CurrentComponent != null)
                    {
                        OurRobot.LoadComponent(OurComponent);
                        OurWSS.UnLoad();
                    }
                    CurrentDevice = Devices.Robot
                    break;
                case (Devices.Robot):
                    if (OurRobot.CurrentComponent != null)
                    {
                        OurMachine.LoadComponent(OurComponent);
                        OurRobot.UnLoad();
                    }
                    CurrentDevice = Devices.Machine;
                    break;
                case (Devices.Machine):
                    if (OurMachine.CurrentComponent != null)
                    {
                        OurRobot.LoadComponent(OurComponent);
                        //OurComponent.GetCurrentOperation();
                        OurMachine.UnLoad();
                    }
                    CurrentDevice = Devices.RobotOut;
                    break;
                case (Devices.RobotOut):
                    if (OurRobot.CurrentComponent != null)
                    {
                        OurWSS.LoadComponent(OurComponent);
                        OurRobot.UnLoad();
                    }
                    CurrentDevice = Devices.WSS;
                    break;
            }
        }


问:
getting exception "IllegalStateException: Can not perform this action after onSaveInstanceState"
I have a Live Android application, and from market i have received following stack trace and i have no idea why its happening as its not happening in application code but its getting caused by some or the other event from the application (assumption)

I am not using Fragments, still there is a reference of FragmentManager.
If any body can throw some light on some hidden facts to avoid this type of issue:

```<code>java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1109)
at android.app.FragmentManagerImpl.popBackStackImmediate(FragmentManager.java:399)
at android.app.Activity.onBackPressed(Activity.java:2066)
at android.app.Activity.onKeyDown(Activity.java:1962)
at android.view.KeyEvent.dispatch(KeyEvent.java:2482)
at android.app.Activity.dispatchKeyEvent(Activity.java:2274)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1668)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112)
at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchKeyEvent(PhoneWindow.java:1720)
at com.android.internal.policy.impl.PhoneWindow.superDispatchKeyEvent(PhoneWindow.java:1258)
at android.app.Activity.dispatchKeyEvent(Activity.java:2269)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1668)
at android.view.ViewRoot.deliverKeyEventPostIme(ViewRoot.java:2851)
at android.view.ViewRoot.handleFinishedEvent(ViewRoot.java:2824)
at android.view.ViewRoot.handleMessage(ViewRoot.java:2011)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:132)
at android.app.ActivityThread.main(ActivityThread.java:4025)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:491)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
at dalvik.system.NativeStart.main(Native Method)
</code>```

答: I noticed something very interesting. I have in my app the option to open the phone's gallery and the device asks what app to use, there I click on the gray area away from the dialog and saw this issue. I noticed how my activity goes from onPause, onSaveInstanceState back to onResume, it doesn't happen to visit onCreateView. I am doing transactions at onResume. So what I ended up doing is setting a flag being negated onPause, but being true onCreateView. if the flag is true onResume then do onCommit, otherwise commitAllowingStateLoss. I could go on and waste so much time but I wanted to check the lifecycle. I have a device which is sdkversion 23, and I don't get this issue, but I have another one which is 21, and there I see it.</p>

Body:
I have a Live Android application, and from market i have received following stack trace and i have no idea why its happening as its not happening in application code but its getting caused by some or the other event from the application (assumption)

I am not using Fragments, still there is a reference of FragmentManager.
If any body can throw some light on some hidden facts to avoid this type of issue:

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1109)
at android.app.FragmentManagerImpl.popBackStackImmediate(FragmentManager.java:399)
at android.app.Activity.onBackPressed(Activity.java:2066)
at android.app.Activity.onKeyDown(Activity.java:1962)
at android.view.KeyEvent.dispatch(KeyEvent.java:2482)
at android.app.Activity.dispatchKeyEvent(Activity.java:2274)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1668)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112)
at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchKeyEvent(PhoneWindow.java:1720)
at com.android.internal.policy.impl.PhoneWindow.superDispatchKeyEvent(PhoneWindow.java:1258)
at android.app.Activity.dispatchKeyEvent(Activity.java:2269)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1668)
at android.view.ViewRoot.deliverKeyEventPostIme(ViewRoot.java:2851)
at android.view.ViewRoot.handleFinishedEvent(ViewRoot.java:2824)
at android.view.ViewRoot.handleMessage(ViewRoot.java:2011)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:132)
at android.app.ActivityThread.main(ActivityThread.java:4025)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:491)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
at dalvik.system.NativeStart.main(Native Method)


问:
Build a list of filenames in Dropzone.js to pass in form submit
I have been working to build a list of file names that are queued for upload in the Dropzone.js. I have been searching the forums for weeks looking for an answer. https://github.com/enyo/dropzone/issues/1652

I started here:
https://github.com/enyo/dropzone/wiki/Upload-all-files-with-a-button.

In this section of the code is where I am working:

```<code>    this.on("addedfile", function() {
      console.log(this.getAcceptedFiles(file));
    });
</code>```

This function returns an array of information about the queued files to be uploaded on click. The array looks like this:

```<code>[File(75099)]
   0: File(75099)
     accepted: true
     lastModified: 1508061061300
     lastModifiedDate: Sun Oct 15 2017 05:51:01 GMT-0400 (Eastern Daylight  Time) {}
     name: "ITI-TV-REPAIR-FORM.pdf"
     previewElement: div.dz-preview.dz-file-preview
     previewTemplate: div.dz-preview.dz-file-preview
     size: 75099
     status: "queued"
     type: "application/pdf"
     upload: {progress: 0, total: 75099, bytesSent: 0}
     webkitRelativePath: ""
     _removeLink: a.dz-remove
     __proto__: File
     length: 1
     __proto__: Array(0)
</code>```

I know that if I use this.getAcceptedFiles().length. It will return 1. As it should since length is in the "root" of the array. But trying to access the name is where I am stumped. The hard part is that the [File(75099)] at the head of the array will always change but the key name will always be in the same place.

I'm thinking out loud while I type this up. The thing I just thought of is if I can do a key value search of the array since I know the key that I am looking for is name:.

I have tried accessing the name value with

```<code>this.getAcceptedFiles().name
</code>```

Of course, that did not work. So my ending question would be what is the best way to access the key value in this array to get the name of the file?

UPDATE: Figure it out!!!

```<code>            this.on("addedfile", function(file) {
                //returns file names that are in the queue
                console.log(file.name);

            });
</code>```

Full code here: https://github.com/enyo/dropzone/issues/1652

答:
The addedfile event is called whenever a file is added to the list of uploaded files, also you can get the added file as parameter in the event callback:

```<code>this.on("addedfile", function(file) {
    console.log(file.name)
});
</code>```

Here is a working example:

Dropzone.options.myDropzone = {

  // Prevents Dropzone from uploading dropped files immediately
  autoProcessQueue: false,

  acceptedFiles: 'image/*',

  init: function() {
    var submitButton = document.querySelector("#submit-all");
    myDropzone = this;

    submitButton.addEventListener("click", function() {
      myDropzone.processQueue(); // Tell Dropzone to process all queued files.
    });

    // You might want to show the submit button only when
    // files are dropped here:
    this.on("addedfile", function(file) {
      console.log(file.name)
    });

  }
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>

<script src="https://rawgit.com/enyo/dropzone/master/dist/dropzone.js"></script>
<link rel="stylesheet" href="https://rawgit.com/enyo/dropzone/master/dist/dropzone.css">

<!-- Change /upload-target to your upload address -->
<form action="/upload-target" class="dropzone" id="my-dropzone"></form>
<br>
<button id="submit-all">Submit all files</button></code>```

Hope this helps

Body:
I have been working to build a list of file names that are queued for upload in the Dropzone.js. I have been searching the forums for weeks looking for an answer. https://github.com/enyo/dropzone/issues/1652

I started here:
https://github.com/enyo/dropzone/wiki/Upload-all-files-with-a-button.

In this section of the code is where I am working:

    this.on("addedfile", function() {
      console.log(this.getAcceptedFiles(file));
    });

This function returns an array of information about the queued files to be uploaded on click. The array looks like this:

[File(75099)]
   0: File(75099)
     accepted: true
     lastModified: 1508061061300
     lastModifiedDate: Sun Oct 15 2017 05:51:01 GMT-0400 (Eastern Daylight  Time) {}
     name: "ITI-TV-REPAIR-FORM.pdf"
     previewElement: div.dz-preview.dz-file-preview
     previewTemplate: div.dz-preview.dz-file-preview
     size: 75099
     status: "queued"
     type: "application/pdf"
     upload: {progress: 0, total: 75099, bytesSent: 0}
     webkitRelativePath: ""
     _removeLink: a.dz-remove
     __proto__: File
     length: 1
     __proto__: Array(0)

I know that if I use this.getAcceptedFiles().length. It will return 1. As it should since length is in the "root" of the array. But trying to access the name is where I am stumped. The hard part is that the [File(75099)] at the head of the array will always change but the key name will always be in the same place.

I'm thinking out loud while I type this up. The thing I just thought of is if I can do a key value search of the array since I know the key that I am looking for is name:.

I have tried accessing the name value with

this.getAcceptedFiles().name

Of course, that did not work. So my ending question would be what is the best way to access the key value in this array to get the name of the file?

UPDATE: Figure it out!!!

            this.on("addedfile", function(file) {
                //returns file names that are in the queue
                console.log(file.name);

            });

Full code here: https://github.com/enyo/dropzone/issues/1652

Body:
The addedfile event is called whenever a file is added to the list of uploaded files, also you can get the added file as parameter in the event callback:

this.on("addedfile", function(file) {
    console.log(file.name)
});

Here is a working example:

Dropzone.options.myDropzone = {

  // Prevents Dropzone from uploading dropped files immediately
  autoProcessQueue: false,

  acceptedFiles: 'image/*',

  init: function() {
    var submitButton = document.querySelector("#submit-all");
    myDropzone = this;

    submitButton.addEventListener("click", function() {
      myDropzone.processQueue(); // Tell Dropzone to process all queued files.
    });

    // You might want to show the submit button only when
    // files are dropped here:
    this.on("addedfile", function(file) {
      console.log(file.name)
    });

  }
};

<!DOCTYPE html>

<script src="https://rawgit.com/enyo/dropzone/master/dist/dropzone.js"></script>
<link rel="stylesheet" href="https://rawgit.com/enyo/dropzone/master/dist/dropzone.css">

<!-- Change /upload-target to your upload address -->
<form action="/upload-target" class="dropzone" id="my-dropzone"></form>
<br>
<button id="submit-all">Submit all files</button>

Hope this helps


问:
Image getting rotated automatically on upload
I'm trying to upload a base64 encoded image and save after decoding it. Image is getting uploaded and saved, and I can access it using a URL and everything..but the image gets rotated by 90 degrees anti-clockwise and I have no idea WHY!!

The place where I get the encoded data is fine, as putting it in  works fine!

```<code>function saveImageData($base64Data) {
    $base64_decoded = base64_decode($base64Data);
    $im = imagecreatefromstring($base64_decoded);
    if ($im !== false) {
        $imagepath = '/public/uploads/' . time() . '.jpg';
        imagejpeg($im, $imagepath);
        chmod($imagepath, 0755);
        imagedestroy($im);
    } else {
        return false;
    }
    return $imagepath;
}
</code>```

I'm not using any rotation functions, but still its getting rotated. I can use a PHP GD function like imagerotate, but don't want to for reasons like black backgrounds etc.

If you can help..you r the awesomest person!!

答:
```<code><?php
if (isset($_POST['submit'])) {
    $filename = $_FILES['file']['name'];
    $filePath = $_FILES['file']['tmp_name'];
    $exif = exif_read_data($_FILES['file']['tmp_name']);
    echo "```";
    print_r($exif);
    echo "```";
    if (!empty($exif['Orientation'])) {
        $imageResource = imagecreatefromjpeg($filePath);
        switch ($exif['Orientation']) {
            case 3:
                $image = imagerotate($imageResource, 180, 0);
                break;
            case 6:
                $image = imagerotate($imageResource, -90, 0);
                break;
            case 8:
                $image = imagerotate($imageResource, 90, 0);
                break;
            default:
                $image = $imageResource;
        }
        imagejpeg($image, $filename, 90);
    }
}
?>
<form class="form-horizontal" method="post" enctype="multipart/form-data">
    <div class="form-group">
        <div class="col-md-9">
            <div class="input-group">
                <span class="input-group-btn">
                    <span class="btn btn-default btn-file">
                        Choose img<input type="file" name="file" id="imgInp">
                    </span>
                </span>

            </div>
        </div>
    </div>
    <button name="submit" type="submit">Send</button>
</form>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to upload a base64 encoded image and save after decoding it. Image is getting uploaded and saved, and I can access it using a URL and everything..but the image gets rotated by 90 degrees anti-clockwise and I have no idea WHY!!

The place where I get the encoded data is fine, as putting it in  works fine!

function saveImageData($base64Data) {
    $base64_decoded = base64_decode($base64Data);
    $im = imagecreatefromstring($base64_decoded);
    if ($im !== false) {
        $imagepath = '/public/uploads/' . time() . '.jpg';
        imagejpeg($im, $imagepath);
        chmod($imagepath, 0755);
        imagedestroy($im);
    } else {
        return false;
    }
    return $imagepath;
}

I'm not using any rotation functions, but still its getting rotated. I can use a PHP GD function like imagerotate, but don't want to for reasons like black backgrounds etc.

If you can help..you r the awesomest person!!

Body:
<?php
if (isset($_POST['submit'])) {
    $filename = $_FILES['file']['name'];
    $filePath = $_FILES['file']['tmp_name'];
    $exif = exif_read_data($_FILES['file']['tmp_name']);
    echo "<pre>";
    print_r($exif);
    echo "</pre>";
    if (!empty($exif['Orientation'])) {
        $imageResource = imagecreatefromjpeg($filePath);
        switch ($exif['Orientation']) {
            case 3:
                $image = imagerotate($imageResource, 180, 0);
                break;
            case 6:
                $image = imagerotate($imageResource, -90, 0);
                break;
            case 8:
                $image = imagerotate($imageResource, 90, 0);
                break;
            default:
                $image = $imageResource;
        }
        imagejpeg($image, $filename, 90);
    }
}
?>
<form class="form-horizontal" method="post" enctype="multipart/form-data">
    <div class="form-group">
        <div class="col-md-9">
            <div class="input-group">
                <span class="input-group-btn">
                    <span class="btn btn-default btn-file">
                        Choose img<input type="file" name="file" id="imgInp">
                    </span>
                </span>

            </div>
        </div>
    </div>
    <button name="submit" type="submit">Send</button>
</form>


答:
If the directories are being created by the build process, you can leverage directory's last write timestamp. Like so,</p>

```<code>$buildPath = '\\nas\my\build'
# Get a list of directories, sort descending by write time and pick the first one
$mostRecentDir = gci $buildPath |? { $_.psIscontainer } | sort -Property LastWriteTime -Descending | select -first 1

# Get the full path to the most recent directory
$mostRecentDir.FullName
</code>```

Title: Copy files from a directory which name changes everyday

Body:
If the directories are being created by the build process, you can leverage directory's last write timestamp. Like so,

$buildPath = '\\nas\my\build'
# Get a list of directories, sort descending by write time and pick the first one
$mostRecentDir = gci $buildPath |? { $_.psIscontainer } | sort -Property LastWriteTime -Descending | select -first 1

# Get the full path to the most recent directory
$mostRecentDir.FullName


问:
Hibernate Tools - "version" column
I am trying to generate the entites from my table using Hibernate Tools. I can do this successfully with one small gotcha.

Each of the tables (100+) have a column called "version" which is a timestamp. When I generate the entites I have get an attribute in the class called version (with accessor and mutator methods) which is good. However there is no annotation on the attribute such as
@Column(name="version"). I can script this into each of the java files but was wondering if there is a way to configure the tool to support this?

Anybody any ideas?

Thanks...

答: @Column(name="version") is not necessary in this case because hibernate assumes that your column is named as it's field when no @Column annotation is present.

Title: Hibernate Tools - "version" column


问:
Cannot post to a server in express
I have an express app that takes basic user input data. All of my get routes work fine but when submit a post request to the server I get a 404 on the url I'm posting to even though I have this page in my views folder.

app.js:

```<code>var express = require('express');
var path = require('path');
var consolidate = require('consolidate');
var bodyParser = require('body-parser');
var database = require('./database/database');
var Patient = require('./models/models').Patient;
var morgan = require('morgan');
var routes = require('./routes');
var app = express();

app.engine('html', consolidate.nunjucks);

app.set('view engine', 'html');
app.set('views', './views');

app.use(morgan('dev'));
//app.use(app.router);
app.use(routes);

app.use(bodyParser.urlencoded({ extended: false }));

app.listen(3055);

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

routes/index.js:

```<code>const express = require('express');
var bodyParser = require('body-parser');
var Patient = require('../models/models').Patient;
const router = express.Router();

router.get('/', function(req, res, next){
    res.render('index.html');
});

router.post('/addsubject', function(req, res, next){
    Patient.create(req.body).then(function(patient){
        res.redirect('/profile');
    }).catch(function(err){
        if(error.name === "SequelizeValidationError"){
       } else {
       return next(err);
       }
   }).catch(function(error){
      res.send(500, error);
   });
});

router.get('/profile', function(req, res, next){
    res.render('./profile.html');
});

router.get('/addsubject', function(req, res, next){
    // .... do something here ..
});

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

I have the <form action="/addsubject" method="post"> in my index.html file.

index.html:

```<code><!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>dabl Demographic</title>
  <body>
    <h2>Add Subject</h2>
      <form action="/addsubject" method="post">
        <label for="fname">First Name: </label>
        <input type="text" name="fname" id="fname">
        <br>
        <label for="sname">Second Name: </label>
        <input type="text" name="sname" id="sname">
        <br>
        <label for="dob">dob: </label>
        <input type="text" name="dob" id="dob">
        <br>
        <label for="laterality">Laterality: </label>
        <input type="text" name="laterality" id="laterality">
        <br>
        <button>Submit</button>
      </form>
  </body>
</html>
</code>```

答:
Problem solved: </p>

```<code>}).catch(function(err){
        if(error.name === "SequelizeValidationError"){
          next(err); //next(err); called inide this block no more 404 error
       }
</code>```

<p>User input is now succesfully passed through the body-parser. </p>

Title: Cannot post to a server in express

Body:
I have an express app that takes basic user input data. All of my get routes work fine but when submit a post request to the server I get a 404 on the url I'm posting to even though I have this page in my views folder.

app.js:

var express = require('express');
var path = require('path');
var consolidate = require('consolidate');
var bodyParser = require('body-parser');
var database = require('./database/database');
var Patient = require('./models/models').Patient;
var morgan = require('morgan');
var routes = require('./routes');
var app = express();

app.engine('html', consolidate.nunjucks);

app.set('view engine', 'html');
app.set('views', './views');

app.use(morgan('dev'));
//app.use(app.router);
app.use(routes);

app.use(bodyParser.urlencoded({ extended: false }));

app.listen(3055);

module.exports = app;

routes/index.js:

const express = require('express');
var bodyParser = require('body-parser');
var Patient = require('../models/models').Patient;
const router = express.Router();

router.get('/', function(req, res, next){
    res.render('index.html');
});

router.post('/addsubject', function(req, res, next){
    Patient.create(req.body).then(function(patient){
        res.redirect('/profile');
    }).catch(function(err){
        if(error.name === "SequelizeValidationError"){
       } else {
       return next(err);
       }
   }).catch(function(error){
      res.send(500, error);
   });
});

router.get('/profile', function(req, res, next){
    res.render('./profile.html');
});

router.get('/addsubject', function(req, res, next){
    // .... do something here ..
});

module.exports = router;

I have the <form action="/addsubject" method="post"> in my index.html file.

index.html:

<!doctype html>

    <meta charset="utf-8">
    <title>dabl Demographic</title>

Add Subject

      <form action="/addsubject" method="post">
        First Name:
        <input type="text" name="fname" id="fname">

        Second Name:
        <input type="text" name="sname" id="sname">

        dob:
        <input type="text" name="dob" id="dob">

        Laterality:
        <input type="text" name="laterality" id="laterality">

        <button>Submit</button>
      </form>

Body:
Problem solved:

}).catch(function(err){
        if(error.name === "SequelizeValidationError"){
          next(err); //next(err); called inide this block no more 404 error
       }

User input is now succesfully passed through the body-parser.


问:
How to write "transparent" HTTP proxy?
Inspired by this article http://www.catonmat.net/http-proxy-in-nodejs

Any idea, how to convert this proxy to acts as transparent proxy?

PS: I know how to set up my firewall, etc... Just trying to run this toy instead of transparent squid.

答:
In general, the difference between transparent and explicit proxy is that the full URL is not sent in the HTTP command in transparent mode.
The proxy would use the Host header to determine the upstream server instead of extracting it from the URL: otherwise the processing is the same. Note that this works for HTTP only, and transparent HTTPS proxy is much harder.

I'm not familiar with node.js: my guess is that the Host header will be available in the request.headers field, and then it's a matter of fixing the proxy_request object to have the proper full upstream URL.

Title: How to write "transparent" HTTP proxy?


问:
Creating a function to be used in multiple pages
Basically, I am trying to create a function that will be called each time a button is clicked. I am developing a questionnaire application with 20 questions, each question has 4 possible answers. I want to create a function that takes the value of the answer when the button is clicked and stores it, this function will be basically the same for each of the 20 pages. I tried creating a function.ts file with an exported Function class but it doesn't seem to work. Any idea how to approach this? </p>

答:
You could create a Provider/Service for this.

But if you just want to use a simple function in different components, you could try this:

functions.ts

```<code>export function myFunction(input) {
    // do something magic
};
</code>```

Then import myFunction in your components

```<code>import { myFunction } from './functions';

// use it anywhere
myFunction(data);
</code>```

Body:
You could create a Provider/Service for this.

But if you just want to use a simple function in different components, you could try this:

functions.ts

export function myFunction(input) {
    // do something magic
};

Then import myFunction in your components

import { myFunction } from './functions';

// use it anywhere
myFunction(data);


问:
want to create excel file using python by preserving all the rows and columns in text format
I'm trying to create an excel file using pandas, but the cells remains in general format, whereas I want all the data to be in formatted text.</p>

```<code>df1 = pd.read_csv(file1, sep='|', dtype=str,  encoding='utf-8')

writer = pd.ExcelWriter(refile1, engine='xlsxwriter', options={'encoding':'utf-8'})
df1.to_excel(writer, sheet_name='Attendee List', startrow=3, startcol=1, index=False, header=True, encoding='utf-8',)
workbook  = writer.book
</code>```

答:
I found this site on adding formatting to excel columns:
http://xlsxwriter.readthedocs.io/example_pandas_column_formats.html

Basically, you need to define some formats like so:

```<code>format1 = workbook.add_format({'num_format': '#,##0.00'})
format2 = workbook.add_format({'num_format': '0%'})
</code>```

and then assign the formats to certain columns like so:

```<code>worksheet.set_column('B:B', 18, format1)
worksheet.set_column('C:C', None, format2)
</code>```

Body:
I'm trying to create an excel file using pandas, but the cells remains in general format, whereas I want all the data to be in formatted text.

df1 = pd.read_csv(file1, sep='|', dtype=str,  encoding='utf-8')

writer = pd.ExcelWriter(refile1, engine='xlsxwriter', options={'encoding':'utf-8'})
df1.to_excel(writer, sheet_name='Attendee List', startrow=3, startcol=1, index=False, header=True, encoding='utf-8',)
workbook  = writer.book

Body:
I found this site on adding formatting to excel columns:
http://xlsxwriter.readthedocs.io/example_pandas_column_formats.html

Basically, you need to define some formats like so:

format1 = workbook.add_format({'num_format': '#,##0.00'})
format2 = workbook.add_format({'num_format': '0%'})

and then assign the formats to certain columns like so:

worksheet.set_column('B:B', 18, format1)
worksheet.set_column('C:C', None, format2)


问:
How to exclude imports from automodapi output?
I am trying to use automodapi to generate documentation for my Django project. When I call automodapi like this:

```<code>.. automodapi:: mypackage.mymodule
</code>```

the output includes all imported classes and functions, e.g, the Django Model class, in the index of Functions and Classes. I would like to exclude the imports and only list those classes and functions declared in the module I specified.

I couldn't see anything about this in the documentation.

Is there a way to do this, preferably without modifying modules?

UPDATE: @saimn has provided a working solution using __all__ but my project doesn't use __all__. It would be nice if there was a solution that didn't involve modifying the modules.

答: You can use the __all__ variable (this should probably be stated more clearly in the documentation).

Body:
I am trying to use automodapi to generate documentation for my Django project. When I call automodapi like this:

.. automodapi:: mypackage.mymodule

the output includes all imported classes and functions, e.g, the Django Model class, in the index of Functions and Classes. I would like to exclude the imports and only list those classes and functions declared in the module I specified.

I couldn't see anything about this in the documentation.

Is there a way to do this, preferably without modifying modules?

UPDATE: @saimn has provided a working solution using __all__ but my project doesn't use __all__. It would be nice if there was a solution that didn't involve modifying the modules.


问:
Dojo addOnLoad, but is Dojo loaded?
I've encountered what seems like a chicken & egg problem, and have what I think is a logical solution.  However, it occurred to me that others must have encountered something similar, so I figured I'd float it out there for the masses.

The situation is that I want to use dojo's addOnLoad function to queue up a number of callbacks which should be executed after the DOM has completed rendering on the client side.  So what I'm doing is as follows:

```<code><html>
    <head>
        <script type="text/javascript" src="dojo.xd.js"></script>
        ...
    </head>
    <body>
        ...
        <script type="text/javascript">
            dojo.addOnLoad( ... );
            dojo.addOnLoad( ... );
            ...
        </script>
    </body>
</html>
</code>```

Now, the issue is that I seem to be calling dojo.addOnLoad before the entire Dojo library has been downloaded the browser.  This makes sense in a way, because the inline SCRIPT contents should be executed before the entire DOM is loaded (and the normal body onload callback is triggered).

My question is this - is my approach sound, or would it make more sense to register a normal/standard body onload JavaScript callback to call a function, which does the same work that each of the dojo.addOnLoads is doing in the SCRIPT block.  Of course, this begs the question, why would you ever then use dojo.addOnLoad if you're not guaranteed that the Dojo library will be loaded prior to using the library?

Hopefully this situation makes sense to someone other than me.  Seems like someone else may have encountered this situation.

Thoughts?

Best Regards,
Adam Rice

答:
You're doing it correctly. External Javascript files are loaded and executed synchronously in order, so by the time it reaches your dojo.addOnLoad( ... ); Dojo has loaded. Use dojo.addOnLoad instead of window.onload for two reasons:

it fires earlier, because it utilizes DOMContentLoaded

it handles asynchronous loading of dojo.require by postponing the execution until all required scripts have been read

Explained in DojoCampus as (dojo.addOnLoad):

dojo.addOnLoad is a fundamental aspect
  of using Dojo. Passing addOnLoad a
  function will register the function to
  run when the Dom is ready. This
  differs slightly from document.ready
  and body.onload in that addOnLoad
  waits until all dojo.require() (and
  their recursive dependencies) have
  loaded before firing.

Title: Dojo addOnLoad, but is Dojo loaded?

Body:
I've encountered what seems like a chicken & egg problem, and have what I think is a logical solution.  However, it occurred to me that others must have encountered something similar, so I figured I'd float it out there for the masses.

The situation is that I want to use dojo's addOnLoad function to queue up a number of callbacks which should be executed after the DOM has completed rendering on the client side.  So what I'm doing is as follows:

        ...

        ...

Now, the issue is that I seem to be calling dojo.addOnLoad before the entire Dojo library has been downloaded the browser.  This makes sense in a way, because the inline SCRIPT contents should be executed before the entire DOM is loaded (and the normal body onload callback is triggered).

My question is this - is my approach sound, or would it make more sense to register a normal/standard body onload JavaScript callback to call a function, which does the same work that each of the dojo.addOnLoads is doing in the SCRIPT block.  Of course, this begs the question, why would you ever then use dojo.addOnLoad if you're not guaranteed that the Dojo library will be loaded prior to using the library?

Hopefully this situation makes sense to someone other than me.  Seems like someone else may have encountered this situation.

Thoughts?

Best Regards,
Adam Rice

OwnerDisplayName: Maine


问:
Placeholder text in chosen plugin for multiple select not working
I'm working with a chosen multiple select. I'm trying to add a placeholder text for the select with data-placeholder attribute, but it doesn't fully work.

The placeholder appears only after a click is performed on the select input and then out of it.

I tried to put an empty option in the select as suggested for single selects in this post, but it didn't work.

Does anybody have a solution?

Here is my code

```<code><select id="mySelect" data-placeholder="Choose an option ..." class="chosen-select allow_additem item_to_upper" multiple tabindex="4">
</select>
</code>```

The select is filled with javascript.

答:
This is a chosen project bug. When you instantiate an element chosen, this creates an structure in your DOM like this:

```<code><div class="chosen-container chosen-container-multi" style="width: 100%;" title="" id="mySelect_chosen">
  <ul class="chosen-choices">
    <li class="search-field">
      <input type="text" value="Choose an option ..." class="default" autocomplete="off" style="width: 90px;" tabindex="-1">
    </li>
  </ul>
  <div class="chosen-drop">
    <ul class="chosen-results"></ul>
  </div>
</div>
</code>```

the placeholder was put into input value, with fixed width 90px. To work around this problem I suggest you to put this into your css assets:

```<code>li.search-field input.default {
  width: 100% !important;
}
</code>```

Body:
I'm working with a chosen multiple select. I'm trying to add a placeholder text for the select with data-placeholder attribute, but it doesn't fully work.

The placeholder appears only after a click is performed on the select input and then out of it.

I tried to put an empty option in the select as suggested for single selects in this post, but it didn't work.

Does anybody have a solution?

Here is my code

<select id="mySelect" data-placeholder="Choose an option ..." class="chosen-select allow_additem item_to_upper" multiple tabindex="4">
</select>

The select is filled with javascript.

Body:
This is a chosen project bug. When you instantiate an element chosen, this creates an structure in your DOM like this:

<div class="chosen-container chosen-container-multi" style="width: 100%;" title="" id="mySelect_chosen">
  <ul class="chosen-choices">
    <li class="search-field">
      <input type="text" value="Choose an option ..." class="default" autocomplete="off" style="width: 90px;" tabindex="-1">
    </li>
  </ul>
  <div class="chosen-drop">
    <ul class="chosen-results"></ul>
  </div>
</div>

the placeholder was put into input value, with fixed width 90px. To work around this problem I suggest you to put this into your css assets:

li.search-field input.default {
  width: 100% !important;
}


问:
Call any Wordpress PHP function via AJAX
It's very difficult for me to learn the basics of AJAX since I was managed to find only complicated examples. In fact, I want to do an apparently simple thing, but I wasn't able to find any easy solution. There are numerous instructions how to use AJAX to check various forms, etc. But there is few data how this technology work in WordPress.

The official instruction was useless to me as well:
https://codex.wordpress.org/AJAX_in_Plugins

What exactly I need?

For example, I have some function in functions.php. Let it be a just simple string:

```<code><?php

function do_echo() {

echo "Hello";

}
</code>```

Now, I want to create a button inside my post and call do_echo() using AJAX.

```<code><button class="my_button" type="button" role="button">Click Me</button>
</code>```

So, the first and foremost thing I want to do is just push on the button and get "Hello, world!" displayed.

Of course, in fact, I need to execute the more complicated function. But, first of all, I need to do these simple things.

I realize that I need to do something like this using jQuery

```<code>$.ajax({
url: '/path/to/file',
type: 'default GET (Other values: POST)',
dataType: 'default: Intelligent Guess (Other values: xml, json, script,
or html)',
data: {param1: 'value1'},
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
</code>```

I understand that I need to do something like this in PHP

```<code>add_action('wp_ajax_(action)', 'my_action_callback');
add_action('wp_ajax_nopriv_(action)', 'my_action_callback');
</code>```

But I can't understand what exact steps I need to do to attach these things to WordPress.

Can anyone assist me with the simple instruction how to call any PHP function from functions.php in WordPress using AJAX when the button was clicked?

Thank you in advance.

答:
Okay, let's write simplified example for this.

Here is a sample for functions.php:

```<code>add_action('wp_ajax_nopriv_sayhello', 'say_hello_function');
add_action('wp_ajax_sayhello', 'say_hello_function');
function say_hello_function(){
echo 'hello';
exit();
}
</code>```

And this is front-end part:

```<code><button class="my_button" type="button" role="button">Click Me</button>

<script>
jQuery(".my_button").click(function(){

jQuery.get(ajaxurl,{'action': 'sayhello'},
function (msg) { alert(msg);});

});

</script>
</code>```

UPD:

To display returned data in your website content:

```<code>   <script>
    jQuery(".my_button").click(function(){
    jQuery.get(ajaxurl,{'action': 'sayhello'},
    function (msg) { jQuery(".result_area").html(msg);});
    });
   </script>
</code>```

To get above code working you need to have a div with "result_area" class.

```<code><div class="result_area"></div>
</code>```

Body:
It's very difficult for me to learn the basics of AJAX since I was managed to find only complicated examples. In fact, I want to do an apparently simple thing, but I wasn't able to find any easy solution. There are numerous instructions how to use AJAX to check various forms, etc. But there is few data how this technology work in WordPress.

The official instruction was useless to me as well:
https://codex.wordpress.org/AJAX_in_Plugins

What exactly I need?

For example, I have some function in functions.php. Let it be a just simple string:

<?php

function do_echo() {

echo "Hello";

}

Now, I want to create a button inside my post and call do_echo() using AJAX.

<button class="my_button" type="button" role="button">Click Me</button>

So, the first and foremost thing I want to do is just push on the button and get "Hello, world!" displayed.

Of course, in fact, I need to execute the more complicated function. But, first of all, I need to do these simple things.

I realize that I need to do something like this using jQuery

$.ajax({
url: '/path/to/file',
type: 'default GET (Other values: POST)',
dataType: 'default: Intelligent Guess (Other values: xml, json, script,
or html)',
data: {param1: 'value1'},
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});

I understand that I need to do something like this in PHP

add_action('wp_ajax_(action)', 'my_action_callback');
add_action('wp_ajax_nopriv_(action)', 'my_action_callback');

But I can't understand what exact steps I need to do to attach these things to WordPress.

Can anyone assist me with the simple instruction how to call any PHP function from functions.php in WordPress using AJAX when the button was clicked?

Thank you in advance.

Body:
Okay, let's write simplified example for this.

Here is a sample for functions.php:

add_action('wp_ajax_nopriv_sayhello', 'say_hello_function');
add_action('wp_ajax_sayhello', 'say_hello_function');
function say_hello_function(){
echo 'hello';
exit();
}

And this is front-end part:

<button class="my_button" type="button" role="button">Click Me</button>

<script>
jQuery(".my_button").click(function(){

jQuery.get(ajaxurl,{'action': 'sayhello'},
function (msg) { alert(msg);});

});

</script>

UPD:

To display returned data in your website content:

   <script>
    jQuery(".my_button").click(function(){
    jQuery.get(ajaxurl,{'action': 'sayhello'},
    function (msg) { jQuery(".result_area").html(msg);});
    });
   </script>

To get above code working you need to have a div with "result_area" class.

<div class="result_area"></div>


问:
Excel Formatting Numbers in Cell
I have a column of data in Excel;

```<code>07902555018
07902556019
07902557020
07902558021
07902559022
...
</code>```

The values change but the placement of three zeros is constant. I am trying to remove the First Zero, Second Zero and the Zero in the 3rd to last position.

```<code>792555518
792555619
792555720
...
</code>```

After the values are changed I am trying to add two hyphens

```<code>79-25555-18
79-25556-19
19-25557-20
</code>```

I tried using: =TEXT(--SUBSTITUTE(--E2,"0","",2),"00-00000-00")
However a problem occurs:

079020638020 becomes 792-06380-20
However 79-20638-20 is the value I want returned in instances like these.

答:
Probably:

079020638020 (Cell E2) is formatted as number.
Which means its actually: 79020638020

Your formula removes the second occurence:
79020638020

So you have 2 possibilities to get it working, either format the cell as text (So the leading 0 will not get deleted) or change the formula to:

```<code>=TEXT(--SUBSTITUTE(--E2,"0","", 1),"00-000000-00")
</code>```

Result would be: 79-206380-20

Title: Excel Formatting Numbers in Cell

Body:
I have a column of data in Excel;

07902555018
07902556019
07902557020
07902558021
07902559022
...

The values change but the placement of three zeros is constant. I am trying to remove the First Zero, Second Zero and the Zero in the 3rd to last position.

792555518
792555619
792555720
...

After the values are changed I am trying to add two hyphens

79-25555-18
79-25556-19
19-25557-20

I tried using: =TEXT(--SUBSTITUTE(--E2,"0","",2),"00-00000-00")
However a problem occurs:

079020638020 becomes 792-06380-20
However 79-20638-20 is the value I want returned in instances like these.

Body:
Probably:

079020638020 (Cell E2) is formatted as number.
Which means its actually: 79020638020

Your formula removes the second occurence:
79020638020

So you have 2 possibilities to get it working, either format the cell as text (So the leading 0 will not get deleted) or change the formula to:

=TEXT(--SUBSTITUTE(--E2,"0","", 1),"00-000000-00")

Result would be: 79-206380-20


问:
How to have a div container width increase to the right from the left
I have a container that holds some buttons to the extreme top right of a page.

I have set its position to fixed and given it a specific width and height which is needed.

The problem is when the text on the buttons increases it goes off the page. I can set overflow to hidden which will prevent it from moving off my button but then the text will get cut off.

The question I pose is, how can I move my div to the left of the page when the text grows but the position of the container to the left must remain the same?

css

```<code>#Container {
    z-index: 9000;
    height: 300px;
    width: 260px;       // im guessing this 3 height,width,and position is the problem but they can not be changed.They are needed.so is there a way i can do this maybe in jquery?
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    background-color: #1a1a1a;
    display: inline-block;
    float: right;
   direction:rtl  // i tried adding this but my container doesnt move the text cuts off to the left.
}
</code>```

attempted

```<code>function TextGrow() {
            var right = $('#Container').offset().right;
            $("#Container").css({ right: right }).animate({ "right": "0px" }, "slow");
        }// didnt do anything
</code>```

答:
Try to add these css commands:

```<code>min-height: 100px;
max-height: 100px;
width: auto;
float: right;
</code>```

Make sure parent container does not go outside the screen.

Body:
I have a container that holds some buttons to the extreme top right of a page.

I have set its position to fixed and given it a specific width and height which is needed.

The problem is when the text on the buttons increases it goes off the page. I can set overflow to hidden which will prevent it from moving off my button but then the text will get cut off.

The question I pose is, how can I move my div to the left of the page when the text grows but the position of the container to the left must remain the same?

css

#Container {
    z-index: 9000;
    height: 300px;
    width: 260px;       // im guessing this 3 height,width,and position is the problem but they can not be changed.They are needed.so is there a way i can do this maybe in jquery?
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    background-color: #1a1a1a;
    display: inline-block;
    float: right;
   direction:rtl  // i tried adding this but my container doesnt move the text cuts off to the left.
}

attempted

function TextGrow() {
            var right = $('#Container').offset().right;
            $("#Container").css({ right: right }).animate({ "right": "0px" }, "slow");
        }// didnt do anything

Body:
Try to add these css commands:

min-height: 100px;
max-height: 100px;
width: auto;
float: right;

Make sure parent container does not go outside the screen.


答:
Are you looking for something like this?

If your container has to have a miminum set width but must grow when its contents exceed that minimum width then use min-width.

The example below adds content to the top-right container by clicking the body. Its initial size is larger than its contents, but as the content grows, so does the container.

var text = "Click body "
$("body").click(function(){
  text += "Click ";
 $("div").html(text);
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div{
  position: fixed;
  top: 0px;
  right: 0px;
  background-color: black ;
  color:red;
  padding: 20px;
  min-width: 150px;
  text-align: right;
}</code>```

Click body

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi eius molestias accusantium quo consectetur laudantium consequatur, iusto suscipit soluta expedita reiciendis numquam fugiat cum laborum, culpa voluptatem ipsam pariatur minus.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptas dicta inventore fugit modi voluptatum dolorem dolor at tempore? Voluptatum cupiditate consequuntur, est corrupti. Non dolore sunt facere mollitia excepturi, obcaecati.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Est dolor consequuntur officia. Numquam mollitia neque qui consequatur aliquid culpa consectetur sint, rerum facilis alias, quo voluptatem omnis incidunt ratione odit!

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequatur asperiores ex aperiam, eos modi assumenda, accusantium architecto sit. Sequi id ipsam, a earum quibusdam esse harum, atque provident repellendus accusantium!

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequatur asperiores ex aperiam, eos modi assumenda, accusantium architecto sit. Sequi id ipsam, a earum quibusdam esse harum, atque provident repellendus accusantium!

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequatur asperiores ex aperiam, eos modi assumenda, accusantium architecto sit. Sequi id ipsam, a earum quibusdam esse harum, atque provident repellendus accusantium!

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequatur asperiores ex aperiam, eos modi assumenda, accusantium architecto sit. Sequi id ipsam, a earum quibusdam esse harum, atque provident repellendus accusantium!
```

Title: How to have a div container width increase to the right from the left

Body:
Are you looking for something like this?

If your container has to have a miminum set width but must grow when its contents exceed that minimum width then use min-width.

The example below adds content to the top-right container by clicking the body. Its initial size is larger than its contents, but as the content grows, so does the container.

var text = "Click body "
$("body").click(function(){
  text += "Click ";
 $("div").html(text);
})

div{
  position: fixed;
  top: 0px;
  right: 0px;
  background-color: black ;
  color:red;
  padding: 20px;
  min-width: 150px;
  text-align: right;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Click body</div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi eius molestias accusantium quo consectetur laudantium consequatur, iusto suscipit soluta expedita reiciendis numquam fugiat cum laborum, culpa voluptatem ipsam pariatur minus.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptas dicta inventore fugit modi voluptatum dolorem dolor at tempore? Voluptatum cupiditate consequuntur, est corrupti. Non dolore sunt facere mollitia excepturi, obcaecati.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Est dolor consequuntur officia. Numquam mollitia neque qui consequatur aliquid culpa consectetur sint, rerum facilis alias, quo voluptatem omnis incidunt ratione odit!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequatur asperiores ex aperiam, eos modi assumenda, accusantium architecto sit. Sequi id ipsam, a earum quibusdam esse harum, atque provident repellendus accusantium!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequatur asperiores ex aperiam, eos modi assumenda, accusantium architecto sit. Sequi id ipsam, a earum quibusdam esse harum, atque provident repellendus accusantium!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequatur asperiores ex aperiam, eos modi assumenda, accusantium architecto sit. Sequi id ipsam, a earum quibusdam esse harum, atque provident repellendus accusantium!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequatur asperiores ex aperiam, eos modi assumenda, accusantium architecto sit. Sequi id ipsam, a earum quibusdam esse harum, atque provident repellendus accusantium!</p>


问:
Verify the existence of an array of root nodes with JSONpath
From the below JSON response, I can verify that a root node exists the in JSONpath using this method from hamcrest library:

```<code>assertThat(json, hasJsonPath("$.tool"));
</code>```

This checks that the root node called 'tool' exists.

```<code>{
    "tool":
    {
        "jsonpath":
        {
            "creator":
            {
                "name": "Jayway Inc.",
                "location":
                [
                    "Malmo",
                    "San Francisco",
                    "Helsingborg"
                ]
            }
        }
    },

    "book":
    [
        {
            "title": "Beginning JSON",
            "price": 49.99
        },

        {
            "title": "JSON at Work",
            "price": 29.99
        }
    ]
}
</code>```

If I want to check the existence of the two root nodes (tool and book)using an array stored in a variable, how can this be achieved? I am not concerned about their values or the values of the sub nodes. I just want to verify that those 2 root nodes exist in the response and are valid paths.

After stringing my API response in a 'json' variable I tried something like this:

```<code>JsonPath jp = new JsonPath(json);

String[] rootNodes = {"tool", "book"};
assertThat(json, hasJsonPath(json.getString(rootNodes)));
</code>```

But compiler was unhappy with the getString method.

Is there a way to resolve this issue?

答:
The root node operator is $ so you can just read $ into a map and that map will be keyed on your root node names.

For example:

```<code>// Approach 1
Map<String, Object> read = JsonPath.read(json, "$");

assertThat(read.size(), is(2));

assertThat(read.keySet(), hasItem("tool"));
assertThat(read.keySet(), hasItem("book"));

// Approach 2: if you want a String[] then ...
String[] rootNodeNames = read.keySet().toArray(new String[read.size()]);
assertThat(rootNodeNames, Matchers.both(arrayWithSize(2)).and(arrayContainingInAnyOrder("book", "tool")));

// Approach 3: if you want to hide it all behind the hasJsonPath() matcher
// note: each of these assertion will cause your JSON string to be parsed
// so it's more efficient to do that once and assert against the
// resulting map as I did above
assertThat(json, hasJsonPath("$", Matchers.hasKey("tool")));
assertThat(json, hasJsonPath("$", Matchers.hasKey("book")));
</code>```

Body:
From the below JSON response, I can verify that a root node exists the in JSONpath using this method from hamcrest library:

assertThat(json, hasJsonPath("$.tool"));

This checks that the root node called 'tool' exists.

{
    "tool":
    {
        "jsonpath":
        {
            "creator":
            {
                "name": "Jayway Inc.",
                "location":
                [
                    "Malmo",
                    "San Francisco",
                    "Helsingborg"
                ]
            }
        }
    },

    "book":
    [
        {
            "title": "Beginning JSON",
            "price": 49.99
        },

        {
            "title": "JSON at Work",
            "price": 29.99
        }
    ]
}

If I want to check the existence of the two root nodes (tool and book)using an array stored in a variable, how can this be achieved? I am not concerned about their values or the values of the sub nodes. I just want to verify that those 2 root nodes exist in the response and are valid paths.

After stringing my API response in a 'json' variable I tried something like this:

JsonPath jp = new JsonPath(json);

String[] rootNodes = {"tool", "book"};
assertThat(json, hasJsonPath(json.getString(rootNodes)));

But compiler was unhappy with the getString method.

Is there a way to resolve this issue?

Body:
The root node operator is $ so you can just read $ into a map and that map will be keyed on your root node names.

For example:

// Approach 1
Map<String, Object> read = JsonPath.read(json, "$");

assertThat(read.size(), is(2));

assertThat(read.keySet(), hasItem("tool"));
assertThat(read.keySet(), hasItem("book"));

// Approach 2: if you want a String[] then ...
String[] rootNodeNames = read.keySet().toArray(new String[read.size()]);
assertThat(rootNodeNames, Matchers.both(arrayWithSize(2)).and(arrayContainingInAnyOrder("book", "tool")));

// Approach 3: if you want to hide it all behind the hasJsonPath() matcher
// note: each of these assertion will cause your JSON string to be parsed
// so it's more efficient to do that once and assert against the
// resulting map as I did above
assertThat(json, hasJsonPath("$", Matchers.hasKey("tool")));
assertThat(json, hasJsonPath("$", Matchers.hasKey("book")));


问:
.NET reflection - check 2 classes are added as members of each other
How can I check 2 classes are added as members of each other.

```<code>class Team
{
   Driver driver{ get; set;}
   Driver codriver{ get; set;}
}

class Driver
{
   Team parentTeam{ get; set;}
}
</code>```

I have used the following way to get the properties:-

```<code>PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
   ////if (!isParent) //need to find this.
   //{
   object propertyValue = property.GetValue(obj);
   if (propertyValue != null)
   {
      // Get the deep clone of the field in the original object and assign the clone to the field in the new object.
      property.SetValue(copiedObject, CloneProcedure(propertyValue));
   }
   //}
}
</code>```

I want to skip through the first class which is a property in second when iterating through 2nd one.
Note: Some of you may feel my classes are declared incorrectly but this is a legacy system and there is no chance of me restructuring the classes.

I have tried DeclaringType and I get property.DeclaringType but obj.GetType().DeclaringType is null.

答:
I am posting my final Deep copy utility if this will benefit anyone

```<code> public static class DeepCloneHelper
{
    private static string[] _excludedPropertyNames = null;

    /// <summary>
    /// Get the deep clone of an object.
    /// </summary>
    /// <typeparam name="T">The type of the source.</typeparam>
    /// <param name="source">It is the object used to deep clone.</param>
    /// <param name="propertyNames"></param>
    /// <returns>Return the deep clone.</returns>
    public static T DeepClone<T>(T source, string[] propertyNames = null)
    {
        if (source == null)
        {
            throw new ArgumentNullException("Object is null");
        }
        if (propertyNames != null) { _excludedPropertyNames = propertyNames; }
        return (T)CloneProcedure(source, new Dictionary<object, object>());
        // return target;
    }

    /// <summary>
    /// The method implements deep clone using reflection.
    /// </summary>
    /// <param name="source">It is the object used to deep clone.</param>
    /// <param name="cloned"></param>
    /// <returns>Return the deep clone.</returns>
    private static object CloneProcedure(Object source, Dictionary<object, object> cloned)
    {
        if (source == null)
        {
            return null;
        }

        object clone;
        if (cloned.TryGetValue(source, out clone))
        {
            // this object has been cloned earlier, return reference to that clone
            return clone;
        }

        Type type = source.GetType();

        // If the type of object is the value type, we will always get a new object when
        // the original object is assigned to another variable. So if the type of the
        // object is primitive or enum, we just return the object. We will process the
        // struct type subsequently because the struct type may contain the reference
        // fields.
        // If the string variables contain the same chars, they always refer to the same
        // string in the heap. So if the type of the object is string, we also return the
        // object.
        if (type.IsPrimitive || type.IsEnum || type == typeof(string))
        {
            return source;
        }
        // If the type of the object is the Array, we use the CreateInstance method to get
        // a new instance of the array. We also process recursively this method in the
        // elements of the original array because the type of the element may be the reference
        // type.
        else if (type.IsArray)
        {
            Type typeElement = Type.GetType(type.FullName.Replace("[]", string.Empty) + "," + type.Assembly.FullName);
            var array = source as Array;
            Array copiedArray = Array.CreateInstance(typeElement, array.Length);
            cloned[source] = copiedArray;

            for (int i = 0; i < array.Length; i++)
            {
                // Get the deep clone of the element in the original array and assign the
                // clone to the new array.
                copiedArray.SetValue(CloneProcedure(array.GetValue(i), cloned), i);

            }
            return copiedArray;
        }

        else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
        {
            if (typeof(IList).IsAssignableFrom(type))
            {
                var collection = (IList)Activator.CreateInstance(type);
                cloned[source] = collection;

                foreach (var element in source as IEnumerable)
                {
                    collection.Add(CloneProcedure(element, cloned));
                }
                return collection;
            }
            else if (type.IsGenericType)
            {
                var objectType = type.GetGenericArguments().Single();
                if (typeof(IList<>).MakeGenericType(objectType).IsAssignableFrom(type) ||
                    typeof(ISet<>).MakeGenericType(objectType).IsAssignableFrom(type))
                {
                    var collection = Activator.CreateInstance(type);
                    cloned[source] = collection;

                    var addMethod = collection.GetType().GetMethod("Add");
                    foreach (var element in source as IEnumerable)
                    {
                        addMethod.Invoke(collection, new[] { CloneProcedure(element, cloned) });
                    }
                    return collection;
                }
            }
            return source;
        }
        // If the type of the object is class or struct, it may contain the reference fields,
        // so we use reflection and process recursively this method in the fields of the object
        // to get the deep clone of the object.
        // We use Type.IsValueType method here because there is no way to indicate directly whether
        // the Type is a struct type.
        else if (type.IsClass || type.IsValueType)
        {
            object copiedObject = Activator.CreateInstance(source.GetType());
            cloned[source] = copiedObject;

            // Get all PropertyInfo.
            PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            foreach (PropertyInfo property in properties)
            {
                if (_excludedPropertyNames == null || !_excludedPropertyNames.Contains(property.Name))
                {
                    object propertyValue = property.GetValue(source);
                    if (propertyValue != null && property.CanWrite && property.GetSetMethod() != null)
                    {
                        // Get the deep clone of the field in the original object and assign the
                        // clone to the field in the new object.
                        property.SetValue(copiedObject, CloneProcedure(propertyValue, cloned));
                    }
                }
            }
            return copiedObject;
        }
        else
        {
            throw new ArgumentException("The object is unknown type");
        }
    }
}
</code>```

Reference : https://code.msdn.microsoft.com/windowsdesktop/CSDeepCloneObject-8a53311e

Body:
How can I check 2 classes are added as members of each other.

class Team
{
   Driver driver{ get; set;}
   Driver codriver{ get; set;}
}

class Driver
{
   Team parentTeam{ get; set;}
}

I have used the following way to get the properties:-

PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
   ////if (!isParent) //need to find this.
   //{
   object propertyValue = property.GetValue(obj);
   if (propertyValue != null)
   {
      // Get the deep clone of the field in the original object and assign the clone to the field in the new object.
      property.SetValue(copiedObject, CloneProcedure(propertyValue));
   }
   //}
}

I want to skip through the first class which is a property in second when iterating through 2nd one.
Note: Some of you may feel my classes are declared incorrectly but this is a legacy system and there is no chance of me restructuring the classes.

I have tried DeclaringType and I get property.DeclaringType but obj.GetType().DeclaringType is null.

Body:
I am posting my final Deep copy utility if this will benefit anyone

 public static class DeepCloneHelper
{
    private static string[] _excludedPropertyNames = null;

    /// <summary>
    /// Get the deep clone of an object.
    /// </summary>
    /// <typeparam name="T">The type of the source.</typeparam>
    /// <param name="source">It is the object used to deep clone.</param>
    /// <param name="propertyNames"></param>
    /// <returns>Return the deep clone.</returns>
    public static T DeepClone<T>(T source, string[] propertyNames = null)
    {
        if (source == null)
        {
            throw new ArgumentNullException("Object is null");
        }
        if (propertyNames != null) { _excludedPropertyNames = propertyNames; }
        return (T)CloneProcedure(source, new Dictionary<object, object>());
        // return target;
    }

    /// <summary>
    /// The method implements deep clone using reflection.
    /// </summary>
    /// <param name="source">It is the object used to deep clone.</param>
    /// <param name="cloned"></param>
    /// <returns>Return the deep clone.</returns>
    private static object CloneProcedure(Object source, Dictionary<object, object> cloned)
    {
        if (source == null)
        {
            return null;
        }

        object clone;
        if (cloned.TryGetValue(source, out clone))
        {
            // this object has been cloned earlier, return reference to that clone
            return clone;
        }

        Type type = source.GetType();

        // If the type of object is the value type, we will always get a new object when
        // the original object is assigned to another variable. So if the type of the
        // object is primitive or enum, we just return the object. We will process the
        // struct type subsequently because the struct type may contain the reference
        // fields.
        // If the string variables contain the same chars, they always refer to the same
        // string in the heap. So if the type of the object is string, we also return the
        // object.
        if (type.IsPrimitive || type.IsEnum || type == typeof(string))
        {
            return source;
        }
        // If the type of the object is the Array, we use the CreateInstance method to get
        // a new instance of the array. We also process recursively this method in the
        // elements of the original array because the type of the element may be the reference
        // type.
        else if (type.IsArray)
        {
            Type typeElement = Type.GetType(type.FullName.Replace("[]", string.Empty) + "," + type.Assembly.FullName);
            var array = source as Array;
            Array copiedArray = Array.CreateInstance(typeElement, array.Length);
            cloned[source] = copiedArray;

            for (int i = 0; i < array.Length; i++)
            {
                // Get the deep clone of the element in the original array and assign the
                // clone to the new array.
                copiedArray.SetValue(CloneProcedure(array.GetValue(i), cloned), i);

            }
            return copiedArray;
        }

        else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
        {
            if (typeof(IList).IsAssignableFrom(type))
            {
                var collection = (IList)Activator.CreateInstance(type);
                cloned[source] = collection;

                foreach (var element in source as IEnumerable)
                {
                    collection.Add(CloneProcedure(element, cloned));
                }
                return collection;
            }
            else if (type.IsGenericType)
            {
                var objectType = type.GetGenericArguments().Single();
                if (typeof(IList<>).MakeGenericType(objectType).IsAssignableFrom(type) ||
                    typeof(ISet<>).MakeGenericType(objectType).IsAssignableFrom(type))
                {
                    var collection = Activator.CreateInstance(type);
                    cloned[source] = collection;

                    var addMethod = collection.GetType().GetMethod("Add");
                    foreach (var element in source as IEnumerable)
                    {
                        addMethod.Invoke(collection, new[] { CloneProcedure(element, cloned) });
                    }
                    return collection;
                }
            }
            return source;
        }
        // If the type of the object is class or struct, it may contain the reference fields,
        // so we use reflection and process recursively this method in the fields of the object
        // to get the deep clone of the object.
        // We use Type.IsValueType method here because there is no way to indicate directly whether
        // the Type is a struct type.
        else if (type.IsClass || type.IsValueType)
        {
            object copiedObject = Activator.CreateInstance(source.GetType());
            cloned[source] = copiedObject;

            // Get all PropertyInfo.
            PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            foreach (PropertyInfo property in properties)
            {
                if (_excludedPropertyNames == null || !_excludedPropertyNames.Contains(property.Name))
                {
                    object propertyValue = property.GetValue(source);
                    if (propertyValue != null && property.CanWrite && property.GetSetMethod() != null)
                    {
                        // Get the deep clone of the field in the original object and assign the
                        // clone to the field in the new object.
                        property.SetValue(copiedObject, CloneProcedure(propertyValue, cloned));
                    }
                }
            }
            return copiedObject;
        }
        else
        {
            throw new ArgumentException("The object is unknown type");
        }
    }
}

Reference : https://code.msdn.microsoft.com/windowsdesktop/CSDeepCloneObject-8a53311e


答:
The best pratice is using WP Rest API

Wordpress provide an simple and organized way to add API Routes that return JSON.

You can register your routes in function.php or another loaded file.

Major WP files will be loaded and you can use your functions.

WP example:

```<code><?php
/**
 * Grab latest post title by an author!
 */
function my_awesome_func( $data ) {
  $posts = get_posts( array(
    "author" => $data["id"],
  ) );

  if ( empty( $posts ) ) {
    return null;
  }

  return $posts[0]->post_title;
}

add_action( "rest_api_init", function () {
  register_rest_route( "myplugin/v1", "/author/(?P<id>\d+)", array(
    "methods" => "GET",
    "callback" => "my_awesome_func",
  ) );
} );
</code>```

Title: Call any Wordpress PHP function via AJAX

Body:
The best pratice is using WP Rest API

Wordpress provide an simple and organized way to add API Routes that return JSON.

You can register your routes in function.php or another loaded file.

Major WP files will be loaded and you can use your functions.

WP example:

<?php
/**
 * Grab latest post title by an author!
 */
function my_awesome_func( $data ) {
  $posts = get_posts( array(
    "author" => $data["id"],
  ) );

  if ( empty( $posts ) ) {
    return null;
  }

  return $posts[0]->post_title;
}

add_action( "rest_api_init", function () {
  register_rest_route( "myplugin/v1", "/author/(?P<id>\d+)", array(
    "methods" => "GET",
    "callback" => "my_awesome_func",
  ) );
} );


问:
Bind CheckBoxFor to bool?
How to bind nullable bool to checkbox in MVC 2. I try with  this code in view:

```<code><%: Html.CheckBoxFor(model =>  model.Communication.Before)%>
</code>```

But show me compilation error.

Thanks in advance.

答:
One way to bind Checkbox in MVC View

With EF database first, boolean (bit) field in the database produces a nullable bool? Property in the generated class. For demo I have a table named Dude with the fields

Id uniqueidentifier

Name varchar(50)

IsAwesome bit

The following class is generated by EF:

```<code>namespace NullableEfDemo
{
 using System;
 public partial class Dude
 {
    public System.Guid Id { get; set; }
    public string Name { get; set; }
    public Nullable<bool> IsAwesome { get; set; }
 }
}
</code>```

To be able to bind IsAwesome to checkbox I simply extend the class Dude. This is to avoid editing the generated class, if I need to refresh it.  So I added a code file DudePartial.cs to my project (the name is irrelevant). Don’t forget to declare or using the project namespace:

```<code>namespace NullableEfDemo
{
 partial class Dude
 {
    public bool Awesome
    {
        get { return IsAwesome ?? false; }
        set { IsAwesome = value; }
    }
  }
}
</code>```

This declares a new property Awesome of type bool that can be bound to the checkbox in the Edit view

```<code>@Html.CheckBoxFor(model => model.Awesome, new { @class = "control-label" })
</code>```

In the HttpPost I’m binding the models Awesome property instead of IsAwesome.

```<code>[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "Id,Name,Awesome")] Dude dude)
    {…
</code>```

Title: Bind CheckBoxFor to bool?

Body:
How to bind nullable bool to checkbox in MVC 2. I try with  this code in view:

<%: Html.CheckBoxFor(model =>  model.Communication.Before)%>

But show me compilation error.

Thanks in advance.

Body:
One way to bind Checkbox in MVC View

With EF database first, boolean (bit) field in the database produces a nullable bool? Property in the generated class. For demo I have a table named Dude with the fields

Id uniqueidentifier

Name varchar(50)

IsAwesome bit

The following class is generated by EF:

namespace NullableEfDemo
{
 using System;
 public partial class Dude
 {
    public System.Guid Id { get; set; }
    public string Name { get; set; }
    public Nullable<bool> IsAwesome { get; set; }
 }
}

To be able to bind IsAwesome to checkbox I simply extend the class Dude. This is to avoid editing the generated class, if I need to refresh it.  So I added a code file DudePartial.cs to my project (the name is irrelevant). Don’t forget to declare or using the project namespace:

namespace NullableEfDemo
{
 partial class Dude
 {
    public bool Awesome
    {
        get { return IsAwesome ?? false; }
        set { IsAwesome = value; }
    }
  }
}

This declares a new property Awesome of type bool that can be bound to the checkbox in the Edit view

@Html.CheckBoxFor(model => model.Awesome, new { @class = "control-label" })

In the HttpPost I’m binding the models Awesome property instead of IsAwesome.

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "Id,Name,Awesome")] Dude dude)
    {…


问:
convert date format from "mm/dd/yyyy hh:mm:ss a" to "dd MMM yyyy" in swift
I tried to convert from 11/17/2017 to 17 Nov 2017 but got this date 17 jan 2017.
Here is the code that i have try.

```<code>func convertDateFormater(_ date: String) -> String
{
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "mm/dd/yyyy hh:mm:ss a"
    let date = dateFormatter.date(from: date)
    dateFormatter.dateFormat = "dd MMM yyyy"
    return  dateFormatter.string(from: date!)

}
print(convertDateFormater("11/17/2017 12:24:41 PM"))
</code>```

Output : - 17 jan 2017

Can anyone help me where i'm doing mistake.

Thanks

答:
You need to use uppercase M to get the month.

```<code>dateFormatter.dateFormat = "MM/dd/yyyy hh:mm:ss a"
</code>```

Also... fix your variable names.

Body:
I tried to convert from 11/17/2017 to 17 Nov 2017 but got this date 17 jan 2017.
Here is the code that i have try.

func convertDateFormater(_ date: String) -> String
{
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "mm/dd/yyyy hh:mm:ss a"
    let date = dateFormatter.date(from: date)
    dateFormatter.dateFormat = "dd MMM yyyy"
    return  dateFormatter.string(from: date!)

}
print(convertDateFormater("11/17/2017 12:24:41 PM"))

Output : - 17 jan 2017

Can anyone help me where i'm doing mistake.

Thanks

Body:
You need to use uppercase M to get the month.

dateFormatter.dateFormat = "MM/dd/yyyy hh:mm:ss a"

Also... fix your variable names.