问:
Rosenbrock function with D dimension using PyTorch
How can I implement the Rosenbrock function with D dimension, using PyTorch?

Create the variables, where D is the number of dimensions and N is the number of elements.

```<code>x = (xmax - xmin)*torch.rand(N,D).type(dtype) + xmin
</code>```

Function :

Using straight Python I'd do something like this:

```<code>fit = 0
for i in range(D-1):
    term1 = x[i + 1] - x[i]**2
    term2 = 1 - x[i]
    fit = fit + 100 * term1**2 + term2**2
</code>```

My attempt using Pytorch:

```<code>def Rosenbrock(x):
    return torch.sum(100*(x - x**2)**2 + (x-1)**2)
</code>```

I just do not know how to do the x[i+1] without using a for loop.
  How can I deal with it?
  Thank you!

答:
Numpy has the function roll which I think can be really helpful.
Unfortunately, I am not aware of any function similar to numpy.roll for pytorch.

In my attempt, x is a numpy array in the form DxN. First we use roll to move the items in the first dimension (axis=0) one position to the left. Like this, everytime we compare x_1[i] is like if we do x[i+1]. Then, since the function takes only D-1 elements for the sum, we remove the last column slicing the pytorch tensor with [:-1, :]. Then the summation is really similar to the code you posted, just changing x for x_1 at the correct place.

```<code>def Rosenbrock(x):
    x_1 = torch.from_numpy(np.roll(x, -1, axis=0)).float()[:-1, :]
    x = torch.from_numpy(x).float()[:-1, :]

    return torch.sum(100 * (x_1 - x ** 2) ** 2 + (x - 1) ** 2, 0)
</code>```

Similarly, by using roll you could remove you for loop in the numpy version

Body:
How can I implement the Rosenbrock function with D dimension, using PyTorch?

Create the variables, where D is the number of dimensions and N is the number of elements.

x = (xmax - xmin)*torch.rand(N,D).type(dtype) + xmin

Function :

Using straight Python I'd do something like this:

fit = 0
for i in range(D-1):
    term1 = x[i + 1] - x[i]**2
    term2 = 1 - x[i]
    fit = fit + 100 * term1**2 + term2**2

My attempt using Pytorch:

def Rosenbrock(x):
    return torch.sum(100*(x - x**2)**2 + (x-1)**2)

I just do not know how to do the x[i+1] without using a for loop.
  How can I deal with it?
  Thank you!

Body:
Numpy has the function roll which I think can be really helpful.
Unfortunately, I am not aware of any function similar to numpy.roll for pytorch.

In my attempt, x is a numpy array in the form DxN. First we use roll to move the items in the first dimension (axis=0) one position to the left. Like this, everytime we compare x_1[i] is like if we do x[i+1]. Then, since the function takes only D-1 elements for the sum, we remove the last column slicing the pytorch tensor with [:-1, :]. Then the summation is really similar to the code you posted, just changing x for x_1 at the correct place.

def Rosenbrock(x):
    x_1 = torch.from_numpy(np.roll(x, -1, axis=0)).float()[:-1, :]
    x = torch.from_numpy(x).float()[:-1, :]

    return torch.sum(100 * (x_1 - x ** 2) ** 2 + (x - 1) ** 2, 0)

Similarly, by using roll you could remove you for loop in the numpy version


来源: stackexchange

问:
Show randow image on each loop of foreach without it duplication in PHP
I have 10 images which is stored as an array.
Also I have a foreach which generate me 10 items.
My goal is to add random image from this array to each of my item that is generated by foreach, furthermore images shouldn't be duplicated.

For ex.:

1 item - img1.jpg;

2 item - img3.jpg;

3 item - img9.jpg...
etc.

```<code><?php
    $rss = simplexml_load_file('https://news.google.com/news/rss/headlines/section/q/blockchain/blockchain?ned=us&hl=en&gl=US');

    $images = array('img1.jpg', 'img2.jpg', 'img3.jpg', 'img4.jpg', 'img5.jpg', 'img6.jpg', 'img7.jpg', 'img8.jpg', 'img9.jpg', 'img10.jpg');
    shuffle ($images);

    foreach ($rss->channel->item as $item) {
        foreach ($images as $image) {
            echo $image."<br/>"."<br/>";
        }
        echo $item->title."<br/>";
        echo $item->link."<br/>";
        echo $item->pubDate."<br/>";
    }
?>
</code>```

This code returns me random images for items but sometimes they are duplicated.

Is it possible to make it within PHP?

答:
like @jeroen said you only need to shuffle the array and the array initialization should be outside the foreach!

```<code>$images = array('img1.jpg', 'img2.jpg', 'img3.jpg', 'img4.jpg', 'img5.jpg',
'img6.jpg', 'img7.jpg', 'img8.jpg', 'img9.jpg', 'img10.jpg');
shuffle ($images);
foreach ($images as $image) {
   print $image;
}
</code>```

Applying this to your case :

```<code><?php
$rss = simplexml_load_file('https://news.google.com/news/rss/headlines/section/q/blockchain/blockchain?ned=us&hl=en&gl=US');

$images = array('img1.jpg', 'img2.jpg', 'img3.jpg', 'img4.jpg', 'img5.jpg', 'img6.jpg', 'img7.jpg', 'img8.jpg', 'img9.jpg', 'img10.jpg');
shuffle ($images);
$i = 0;
foreach ($rss->channel->item $item) {

    echo $images[$i]."<br/>"."<br/>";
    echo $item->title."<br/>";
    echo $item->link."<br/>";
    echo $item->pubDate."<br/>";
    $i++;
}
</code>```

?>

ContentLicense: CC BY-SA 3.0

Body:
I have 10 images which is stored as an array.
Also I have a foreach which generate me 10 items.
My goal is to add random image from this array to each of my item that is generated by foreach, furthermore images shouldn't be duplicated.

For ex.:

1 item - img1.jpg;

2 item - img3.jpg;

3 item - img9.jpg...
etc.

<?php
    $rss = simplexml_load_file('https://news.google.com/news/rss/headlines/section/q/blockchain/blockchain?ned=us&hl=en&gl=US');

    $images = array('img1.jpg', 'img2.jpg', 'img3.jpg', 'img4.jpg', 'img5.jpg', 'img6.jpg', 'img7.jpg', 'img8.jpg', 'img9.jpg', 'img10.jpg');
    shuffle ($images);

    foreach ($rss->channel->item as $item) {
        foreach ($images as $image) {
            echo $image."
"."
";
        }
        echo $item->title."
";
        echo $item->link."
";
        echo $item->pubDate."
";
    }
?>

This code returns me random images for items but sometimes they are duplicated.

Is it possible to make it within PHP?

Body:
like @jeroen said you only need to shuffle the array and the array initialization should be outside the foreach!

$images = array('img1.jpg', 'img2.jpg', 'img3.jpg', 'img4.jpg', 'img5.jpg',
'img6.jpg', 'img7.jpg', 'img8.jpg', 'img9.jpg', 'img10.jpg');
shuffle ($images);
foreach ($images as $image) {
   print $image;
}

Applying this to your case :

<?php
$rss = simplexml_load_file('https://news.google.com/news/rss/headlines/section/q/blockchain/blockchain?ned=us&hl=en&gl=US');

$images = array('img1.jpg', 'img2.jpg', 'img3.jpg', 'img4.jpg', 'img5.jpg', 'img6.jpg', 'img7.jpg', 'img8.jpg', 'img9.jpg', 'img10.jpg');
shuffle ($images);
$i = 0;
foreach ($rss->channel->item $item) {

    echo $images[$i]."<br/>"."<br/>";
    echo $item->title."<br/>";
    echo $item->link."<br/>";
    echo $item->pubDate."<br/>";
    $i++;
}

?>


问:
Expiring Certificate on Enterprise app (IOS)
I have an enterprise app out in the field signed with a distribution certificate 3 years ago that is due to expire next month. Ideally I would like to not have to redeploy my app to my users and according to the apple docs Re-Creating Certificates and Updating Related Provisioning Profiles,  it appears I can create a new dist cert, update my profile with the new cert and my app out in the field will not be effected. I have read some conflicting posts on the matter from a few years ago now admittedly that say I will need to re-deploy my enterprise app so was wondering would anyone be able to confirm for me what teh latest state of play is.

Any information would be greatly appreciated.

答:
No, you don't need to redeploy an app if your bundler identifier is same.

You can revoke current certificate and create a new one. This action can result into 'stop' usage of app in mobile device (if or when it has connection to apple server). The reason for this is, user needs to accept/trust developer of new certificate from device's settings.

Once user accepts/trust new certificate, your app will continue working as it was.

You can ask me, if you still have any confusion or problem in understanding this scenario.

Recently, I practically tested this scenario for one of my enterprise app and it was successful.

Hope it would work for you also !!!


问:
I found a bug about date
I am testing the date utility, and have found some unexpected behaviour. My test is to set the date to a given day/month/year, add 24 hours to it, and confirm that it returns the following date.

In my tests below, this works for November 4, 2017, and November 6, 2017, but not for November 5, 2017.

This is clearly a bug, isn't it? How could there be such a fundamental flaw in a key GNU utility?

```<code>[pp_dt_risk_batch@lvsdmetl05 creditsafe]$ date=`date -d "2017-11-04" +%s`
[pp_dt_risk_batch@lvsdmetl05 creditsafe]$ date_new=`expr $date + 86400`
[pp_dt_risk_batch@lvsdmetl05 creditsafe]$ req_t=`date -d @$date_new "+%Y%m%d"`
[pp_dt_risk_batch@lvsdmetl05 creditsafe]$ echo $req_t
20171105
[pp_dt_risk_batch@lvsdmetl05 creditsafe]$ date=`date -d "2017-11-06" +%s`
[pp_dt_risk_batch@lvsdmetl05 creditsafe]$ date_new=`expr $date + 86400`
[pp_dt_risk_batch@lvsdmetl05 creditsafe]$ req_t=`date -d @$date_new "+%Y%m%d"`
[pp_dt_risk_batch@lvsdmetl05 creditsafe]$ echo $req_t
20171107
[pp_dt_risk_batch@lvsdmetl05 creditsafe]$ date=`date -d "2017-11-05" +%s`
[pp_dt_risk_batch@lvsdmetl05 creditsafe]$ date_new=`expr $date + 86400`
[pp_dt_risk_batch@lvsdmetl05 creditsafe]$ req_t=`date -d @$date_new "+%Y%m%d"`
[pp_dt_risk_batch@lvsdmetl05 creditsafe]$ echo $req_t
20171105

[pp_dt_risk_batch@lvsdmetl05 creditsafe]$ date --version
date (GNU coreutils) 8.4
Copyright (C) 2010 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Written by David MacKenzie.
</code>```

答:
It appears you are concerned with the apparent discrepancy suggested by the following (noting that 86400 seconds = 24 hours)

2017-11-04 00:00 + 86400 seconds = 2017-11-05 00:00

2017-11-05 00:00 + 86400 seconds = 2017-11-05 24:00 (see below!)

2017-11-06 00:00 + 86400 seconds = 2017-11-07 00:00

This is not a bug.

You don't mention what timezone you are in, but in most of North America, 2017-11-05 was the day on which Daylight Saving Time ended, so it was 25 hours long (90000 seconds).

Title: I found a bug about date

Body:
I am testing the date utility, and have found some unexpected behaviour. My test is to set the date to a given day/month/year, add 24 hours to it, and confirm that it returns the following date.

In my tests below, this works for November 4, 2017, and November 6, 2017, but not for November 5, 2017.

This is clearly a bug, isn't it? How could there be such a fundamental flaw in a key GNU utility?

[pp_dt_risk_batch@lvsdmetl05 creditsafe]$ date=`date -d "2017-11-04" +%s`
[pp_dt_risk_batch@lvsdmetl05 creditsafe]$ date_new=`expr $date + 86400`
[pp_dt_risk_batch@lvsdmetl05 creditsafe]$ req_t=`date -d @$date_new "+%Y%m%d"`
[pp_dt_risk_batch@lvsdmetl05 creditsafe]$ echo $req_t
20171105
[pp_dt_risk_batch@lvsdmetl05 creditsafe]$ date=`date -d "2017-11-06" +%s`
[pp_dt_risk_batch@lvsdmetl05 creditsafe]$ date_new=`expr $date + 86400`
[pp_dt_risk_batch@lvsdmetl05 creditsafe]$ req_t=`date -d @$date_new "+%Y%m%d"`
[pp_dt_risk_batch@lvsdmetl05 creditsafe]$ echo $req_t
20171107
[pp_dt_risk_batch@lvsdmetl05 creditsafe]$ date=`date -d "2017-11-05" +%s`
[pp_dt_risk_batch@lvsdmetl05 creditsafe]$ date_new=`expr $date + 86400`
[pp_dt_risk_batch@lvsdmetl05 creditsafe]$ req_t=`date -d @$date_new "+%Y%m%d"`
[pp_dt_risk_batch@lvsdmetl05 creditsafe]$ echo $req_t
20171105

[pp_dt_risk_batch@lvsdmetl05 creditsafe]$ date --version
date (GNU coreutils) 8.4
Copyright (C) 2010 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Written by David MacKenzie.


问:
How To Write Series Of Number In Excel
I want to write numbers in excel starting from 000001 till 999999

I have done like this =TEXT(A2,"000001") but i am not been able to generate series even though not able to separate this in different attributes

Further I want to distribute each number in each different cell for example like this

```<code>A           B         C        D         E         F       G

000001      0         0        0         0         0       1

000002      0         0        0         0         0       2

till

999999      9          9       9         9          9       9
</code>```

答:
Might be a bit easier with a VBA macro. Right-click the sheet tab, select View Code, paste the below code, and Run (F5)</p>

```<code>Sub fill()
    [a1:a999999] = "=text(row(), ""000000"")"
    [b1:g999999] = "=mid($a1, column()-1, 1)"
End Sub
</code>```

Title: How To Write Series Of Number In Excel

Body:
I want to write numbers in excel starting from 000001 till 999999

I have done like this =TEXT(A2,"000001") but i am not been able to generate series even though not able to separate this in different attributes

Further I want to distribute each number in each different cell for example like this

A           B         C        D         E         F       G

000001      0         0        0         0         0       1

000002      0         0        0         0         0       2

till

999999      9          9       9         9          9       9

Body:
Might be a bit easier with a VBA macro. Right-click the sheet tab, select View Code, paste the below code, and Run (F5)

Sub fill()
    [a1:a999999] = "=text(row(), ""000000"")"
    [b1:g999999] = "=mid($a1, column()-1, 1)"
End Sub


问:
Split a Record and pass it to PublishKafka
I have log files saved in the form 20171102-logs.log.

I'm trying to pass those logs to a Kafka topic, however they're too large for the parameters defined for the topic. The allowable file size can not be changed, so I'm trying to split the files. I've tried a couple of different things, but I'm having no luck. The logs contained in the files are in the following format:

```<code>{"date":"2017-11-02T12:33:55Z", "module":"java", "version":"1.8.0.45", "node":"node-name", "username":"user"}
</code>```

Any pointers/advice on how I can split these files would be greatly appreciated.

答:
If your log files contain a single log message per line, separated by new-lines, then you can use PublishKafka and set the "Message Demarcator" to a new-line by pressing shift+enter as the value.

This will let the processor read the file based on the demarcator and publish a message to Kafka for each individual log message in the file.

Body:
I have log files saved in the form 20171102-logs.log.

I'm trying to pass those logs to a Kafka topic, however they're too large for the parameters defined for the topic. The allowable file size can not be changed, so I'm trying to split the files. I've tried a couple of different things, but I'm having no luck. The logs contained in the files are in the following format:

{"date":"2017-11-02T12:33:55Z", "module":"java", "version":"1.8.0.45", "node":"node-name", "username":"user"}

Any pointers/advice on how I can split these files would be greatly appreciated.


问:
mongoose - Combining data via aggregation
I have this kind of data:

```<code>[
  { _id: ..., class: 'A', name: 'John Doe' },
  { _id: ..., class: 'A', name: 'John Snow' },
  { _id: ..., class: 'B', name: 'Joan Doe' },
  ...
]
</code>```

I need to have an aggregated data for mongoose with the result as:

```<code>[
  { class: 'A', students: [
    { _id: ..., name: 'John Snow' },
    { _id: ..., name: 'John Doe' }
   ]},
  ...
]
</code>```

How can I do this with aggregation in mongoose?

答:
The aggregate pipeline would look like this,

```<code>[
    {
        $group: {
        _id:{ class: "$class" },
        students:{$push:{_id:"$_id", name:"$name"}}
    }
]
</code>```

I believe for mongoose you'd do something similar to:

```<code>Model.aggregate({
        $group: {
        _id:{ class: "$class" },
        students:{$push:{_id:"$_id", name:"$name"}}
    })
.exec(callback)
</code>```

Body:
I have this kind of data:

[
  { _id: ..., class: 'A', name: 'John Doe' },
  { _id: ..., class: 'A', name: 'John Snow' },
  { _id: ..., class: 'B', name: 'Joan Doe' },
  ...
]

I need to have an aggregated data for mongoose with the result as:

[
  { class: 'A', students: [
    { _id: ..., name: 'John Snow' },
    { _id: ..., name: 'John Doe' }
   ]},
  ...
]

How can I do this with aggregation in mongoose?

Body:
The aggregate pipeline would look like this,

[
    {
        $group: {
        _id:{ class: "$class" },
        students:{$push:{_id:"$_id", name:"$name"}}
    }
]

I believe for mongoose you'd do something similar to:

Model.aggregate({
        $group: {
        _id:{ class: "$class" },
        students:{$push:{_id:"$_id", name:"$name"}}
    })
.exec(callback)


问:
jQuery to loop through elements with the same class
I have a load of divs with the class testimonial and I want to use jquery to loop through them to check for each div if a specific condition is true. If it is true, it should perform an action.

Does anyone know how I would do this?

答:
```<code>$('.testimonal').each(function(i,v){
  if (condition) {
    doSomething();
  }
});
</code>```

ContentLicense: CC BY-SA 2.5


问:
Unable to instantiate fragment android.support.v14.preference.PreferenceFragment
I'm trying to use PreferenceFragment from the v7 support library for settings of my app. When I try to run it in android 4.2.2, it always returns the following exception:

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
                                                              java.lang.RuntimeException: Unable to start activity ComponentInfo{fr.mobiho.navapp/fr.mobiho.navapp.settings.activity.PrefsActivity}: android.app.Fragment$InstantiationException: Unable to instantiate fragment android.support.v14.preference.PreferenceFragment: make sure class name exists, is public, and has an empty constructor that is public
                                                                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
                                                                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
                                                                  at android.app.ActivityThread.access$600(ActivityThread.java:141)
                                                                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
                                                                  at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                  at android.os.Looper.loop(Looper.java:137)
                                                                  at android.app.ActivityThread.main(ActivityThread.java:5041)
                                                                  at java.lang.reflect.Method.invokeNative(Native Method)
                                                                  at java.lang.reflect.Method.invoke(Method.java:511)
                                                                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
                                                                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
                                                                  at dalvik.system.NativeStart.main(Native Method)
                                                               Caused by: android.app.Fragment$InstantiationException: Unable to instantiate fragment android.support.v14.preference.PreferenceFragment: make sure class name exists, is public, and has an empty constructor that is public
                                                                  at android.app.Fragment.instantiate(Fragment.java:596)
                                                                  at android.preference.PreferenceActivity.switchToHeaderInner(PreferenceActivity.java:1138)
                                                                  at android.preference.PreferenceActivity.switchToHeader(PreferenceActivity.java:1154)
                                                                  at android.preference.PreferenceActivity.onCreate(PreferenceActivity.java:560)
                                                                  at fr.mobiho.navapp.activity.AppCompatPreferenceActivity.onCreate(AppCompatPreferenceActivity.java:35)
                                                                  at fr.mobiho.navapp.settings.activity.ThemableSettingsActivity.onCreate(ThemableSettingsActivity.java:39)
                                                                  at fr.mobiho.navapp.settings.activity.PrefsActivity.onCreate(PrefsActivity.java:53)
                                                                  at android.app.Activity.performCreate(Activity.java:5104)
                                                                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
                                                                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
                                                                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
                                                                  at android.app.ActivityThread.access$600(ActivityThread.java:141)
                                                                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
                                                                  at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                  at android.os.Looper.loop(Looper.java:137)
                                                                  at android.app.ActivityThread.main(ActivityThread.java:5041)
                                                                  at java.lang.reflect.Method.invokeNative(Native Method)
                                                                  at java.lang.reflect.Method.invoke(Method.java:511)
                                                                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
                                                                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
                                                                  at dalvik.system.NativeStart.main(Native Method)
                                                               Caused by: java.lang.InstantiationException: can't instantiate class android.support.v14.preference.PreferenceFragment
                                                                  at java.lang.Class.newInstanceImpl(Native Method)
                                                                  at java.lang.Class.newInstance(Class.java:1319)
                                                                  at android.app.Fragment.instantiate(Fragment.java:585)
                                                                  at android.preference.PreferenceActivity.switchToHeaderInner(PreferenceActivity.java:1138)
                                                                  at android.preference.PreferenceActivity.switchToHeader(PreferenceActivity.java:1154)
                                                                  at android.preference.PreferenceActivity.onCreate(PreferenceActivity.java:560)
                                                                  at fr.mobiho.navapp.activity.AppCompatPreferenceActivity.onCreate(AppCompatPreferenceActivity.java:35)
                                                                  at fr.mobiho.navapp.settings.activity.ThemableSettingsActivity.onCreate(ThemableSettingsActivity.java:39)
                                                                  at fr.mobiho.navapp.settings.activity.PrefsActivity.onCreate(PrefsActivity.java:53)
                                                                  at android.app.Activity.performCreate(Activity.java:5104)
                                                                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
                                                                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
                                                                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
                                                                  at android.app.ActivityThread.access$600(ActivityThread.java:141)
                                                                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
                                                                  at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                  at android.os.Looper.loop(Looper.java:137)
                                                                  at android.app.ActivityThread.main(ActivityThread.java:5041)
                                                                  at java.lang.reflect.Method.invokeNative(Native Method)
                                                                  at java.lang.reflect.Method.invoke(Method.java:511)
                                                                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
                                                                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
                                                                  at dalvik.system.NativeStart.main(Native Method)
</code>```

But in higher version it's work fine like 5.0, 5.1, 6.0.

Here is the class AppCompatPreferenceActivity

```<code>public abstract class AppCompatPreferenceActivity extends PreferenceActivity {

    private AppCompatDelegate mDelegate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        overridePendingTransition(R.anim.slide_in_from_right, R.anim.fade_out_scale);
        getDelegate().installViewFactory();
        getDelegate().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        getDelegate().onPostCreate(savedInstanceState);
    }

    protected final ActionBar getSupportActionBar() {
        return getDelegate().getSupportActionBar();
    }

    protected final void setSupportActionBar(@Nullable Toolbar toolbar) {
        getDelegate().setSupportActionBar(toolbar);
    }

    @NonNull
    @Override
    public MenuInflater getMenuInflater() {
        return getDelegate().getMenuInflater();
    }

    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        getDelegate().setContentView(layoutResID);
    }

    @Override
    public void setContentView(View view) {
        getDelegate().setContentView(view);
    }

    @Override
    public void setContentView(View view, ViewGroup.LayoutParams params) {
        getDelegate().setContentView(view, params);
    }

    @Override
    public void addContentView(View view, ViewGroup.LayoutParams params) {
        getDelegate().addContentView(view, params);
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
        getDelegate().onPostResume();
    }

    @Override
    protected void onTitleChanged(CharSequence title, int color) {
        super.onTitleChanged(title, color);
        getDelegate().setTitle(title);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        getDelegate().onConfigurationChanged(newConfig);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (isFinishing()) {
            overridePendingTransition(R.anim.fade_in_scale, R.anim.slide_out_to_right);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        getDelegate().onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        getDelegate().onDestroy();
    }

    public void invalidateOptionsMenu() {
        getDelegate().invalidateOptionsMenu();
    }

    private AppCompatDelegate getDelegate() {
        if (mDelegate == null) {
            mDelegate = AppCompatDelegate.create(this, null);
        }
        return mDelegate;
    }
}
</code>```

And here is the MyCustomPreferenceFragment

```<code>public class MyCustomPreferenceFragment extends PreferenceFragment {

    @Inject
    PreferenceManager mPreferenceManager;

    public MyCustomPreferenceFragment() {

    }

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

    }

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {

    }
}
</code>```

答:
You have to remove abstract keyword because abstract classes cannot be instantiated,so use

```<code>public /*abstract*/ class AppCompatPreferenceActivity extends PreferenceActivity {
</code>```

For further reading Abstract Methods and Classes

Body:
I'm trying to use PreferenceFragment from the v7 support library for settings of my app. When I try to run it in android 4.2.2, it always returns the following exception:

E/AndroidRuntime: FATAL EXCEPTION: main
                                                              java.lang.RuntimeException: Unable to start activity ComponentInfo{fr.mobiho.navapp/fr.mobiho.navapp.settings.activity.PrefsActivity}: android.app.Fragment$InstantiationException: Unable to instantiate fragment android.support.v14.preference.PreferenceFragment: make sure class name exists, is public, and has an empty constructor that is public
                                                                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
                                                                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
                                                                  at android.app.ActivityThread.access$600(ActivityThread.java:141)
                                                                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
                                                                  at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                  at android.os.Looper.loop(Looper.java:137)
                                                                  at android.app.ActivityThread.main(ActivityThread.java:5041)
                                                                  at java.lang.reflect.Method.invokeNative(Native Method)
                                                                  at java.lang.reflect.Method.invoke(Method.java:511)
                                                                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
                                                                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
                                                                  at dalvik.system.NativeStart.main(Native Method)
                                                               Caused by: android.app.Fragment$InstantiationException: Unable to instantiate fragment android.support.v14.preference.PreferenceFragment: make sure class name exists, is public, and has an empty constructor that is public
                                                                  at android.app.Fragment.instantiate(Fragment.java:596)
                                                                  at android.preference.PreferenceActivity.switchToHeaderInner(PreferenceActivity.java:1138)
                                                                  at android.preference.PreferenceActivity.switchToHeader(PreferenceActivity.java:1154)
                                                                  at android.preference.PreferenceActivity.onCreate(PreferenceActivity.java:560)
                                                                  at fr.mobiho.navapp.activity.AppCompatPreferenceActivity.onCreate(AppCompatPreferenceActivity.java:35)
                                                                  at fr.mobiho.navapp.settings.activity.ThemableSettingsActivity.onCreate(ThemableSettingsActivity.java:39)
                                                                  at fr.mobiho.navapp.settings.activity.PrefsActivity.onCreate(PrefsActivity.java:53)
                                                                  at android.app.Activity.performCreate(Activity.java:5104)
                                                                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
                                                                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
                                                                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
                                                                  at android.app.ActivityThread.access$600(ActivityThread.java:141)
                                                                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
                                                                  at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                  at android.os.Looper.loop(Looper.java:137)
                                                                  at android.app.ActivityThread.main(ActivityThread.java:5041)
                                                                  at java.lang.reflect.Method.invokeNative(Native Method)
                                                                  at java.lang.reflect.Method.invoke(Method.java:511)
                                                                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
                                                                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
                                                                  at dalvik.system.NativeStart.main(Native Method)
                                                               Caused by: java.lang.InstantiationException: can't instantiate class android.support.v14.preference.PreferenceFragment
                                                                  at java.lang.Class.newInstanceImpl(Native Method)
                                                                  at java.lang.Class.newInstance(Class.java:1319)
                                                                  at android.app.Fragment.instantiate(Fragment.java:585)
                                                                  at android.preference.PreferenceActivity.switchToHeaderInner(PreferenceActivity.java:1138)
                                                                  at android.preference.PreferenceActivity.switchToHeader(PreferenceActivity.java:1154)
                                                                  at android.preference.PreferenceActivity.onCreate(PreferenceActivity.java:560)
                                                                  at fr.mobiho.navapp.activity.AppCompatPreferenceActivity.onCreate(AppCompatPreferenceActivity.java:35)
                                                                  at fr.mobiho.navapp.settings.activity.ThemableSettingsActivity.onCreate(ThemableSettingsActivity.java:39)
                                                                  at fr.mobiho.navapp.settings.activity.PrefsActivity.onCreate(PrefsActivity.java:53)
                                                                  at android.app.Activity.performCreate(Activity.java:5104)
                                                                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
                                                                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
                                                                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
                                                                  at android.app.ActivityThread.access$600(ActivityThread.java:141)
                                                                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
                                                                  at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                  at android.os.Looper.loop(Looper.java:137)
                                                                  at android.app.ActivityThread.main(ActivityThread.java:5041)
                                                                  at java.lang.reflect.Method.invokeNative(Native Method)
                                                                  at java.lang.reflect.Method.invoke(Method.java:511)
                                                                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
                                                                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
                                                                  at dalvik.system.NativeStart.main(Native Method)

But in higher version it's work fine like 5.0, 5.1, 6.0.

Here is the class AppCompatPreferenceActivity

public abstract class AppCompatPreferenceActivity extends PreferenceActivity {

    private AppCompatDelegate mDelegate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        overridePendingTransition(R.anim.slide_in_from_right, R.anim.fade_out_scale);
        getDelegate().installViewFactory();
        getDelegate().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        getDelegate().onPostCreate(savedInstanceState);
    }

    protected final ActionBar getSupportActionBar() {
        return getDelegate().getSupportActionBar();
    }

    protected final void setSupportActionBar(@Nullable Toolbar toolbar) {
        getDelegate().setSupportActionBar(toolbar);
    }

    @NonNull
    @Override
    public MenuInflater getMenuInflater() {
        return getDelegate().getMenuInflater();
    }

    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        getDelegate().setContentView(layoutResID);
    }

    @Override
    public void setContentView(View view) {
        getDelegate().setContentView(view);
    }

    @Override
    public void setContentView(View view, ViewGroup.LayoutParams params) {
        getDelegate().setContentView(view, params);
    }

    @Override
    public void addContentView(View view, ViewGroup.LayoutParams params) {
        getDelegate().addContentView(view, params);
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
        getDelegate().onPostResume();
    }

    @Override
    protected void onTitleChanged(CharSequence title, int color) {
        super.onTitleChanged(title, color);
        getDelegate().setTitle(title);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        getDelegate().onConfigurationChanged(newConfig);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (isFinishing()) {
            overridePendingTransition(R.anim.fade_in_scale, R.anim.slide_out_to_right);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        getDelegate().onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        getDelegate().onDestroy();
    }

    public void invalidateOptionsMenu() {
        getDelegate().invalidateOptionsMenu();
    }

    private AppCompatDelegate getDelegate() {
        if (mDelegate == null) {
            mDelegate = AppCompatDelegate.create(this, null);
        }
        return mDelegate;
    }
}

And here is the MyCustomPreferenceFragment

public class MyCustomPreferenceFragment extends PreferenceFragment {

    @Inject
    PreferenceManager mPreferenceManager;

    public MyCustomPreferenceFragment() {

    }

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

    }

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {

    }
}

Body:
You have to remove abstract keyword because abstract classes cannot be instantiated,so use

public /*abstract*/ class AppCompatPreferenceActivity extends PreferenceActivity {

For further reading Abstract Methods and Classes


问:
In php, Number of rows and columns in a 2 D array?
I have a two dimensional array with unknown number of elements.

$two_darray[row][column]; //there will be an unknown integer values instead of row and column keywords

If I were to write a for loop as follows, how can I determine how many rows and columns in my $two_darray. Can you please tell me if there is a library function in php that can tell me the value inside [????] [????]

```<code>for($row=0; $row<………; $row++)
{
    for($column =0; $column  <………; $ column ++)
    {
        echo $two_darray[$row][$column];
    }
    echo “\n end of one column \n”;
}
</code>```

I really need to know the value of rows and columns in order to perform other calculations.

答:
the quick way for normal,non-mixed 2-dim Array,

$Rows=count($array);
$colomns=(count($array,1)-count($array))/count($array);

Body:
I have a two dimensional array with unknown number of elements.

$two_darray[row][column]; //there will be an unknown integer values instead of row and column keywords

If I were to write a for loop as follows, how can I determine how many rows and columns in my $two_darray. Can you please tell me if there is a library function in php that can tell me the value inside [????] [????]

for($row=0; $row<………; $row++)
{
    for($column =0; $column  <………; $ column ++)
    {
        echo $two_darray[$row][$column];
    }
    echo “\n end of one column \n”;
}

I really need to know the value of rows and columns in order to perform other calculations.


问:
convert constexpr n-dimensional array of one type to constexpr n-dimensional array of a different type
Using C++11 or C++14:

I have a:

```<code>constexpr double [2][3][4] = some value;
</code>```

I want constexpr int [2][3][4] from this.

(Actually I will want constexpr my_type [2][3][4], but that should be trivially solvable once int works.)

The only solution I came up with was a container class with operator[] overloaded so it behaves like an array. Is there a way to keep standard array syntax? Or possibly std::array<std::array...>> without creating a new class?

I do not want the input to be std::array - that is a constraint of the system. The input must be C compatible. The converted array can be C++.

答:
There's a way to do this by building incrementally. That is, first solve the conversion for 1D arrays. Then based on that solution the conversion for 2D arrays etc.

```<code>template<typename U, typename T, std::size_t N, std::size_t... I>
constexpr
std::array<U, N>
convert1DArrayImpl(std::array<T, N> const &a, std::index_sequence<I...>) {
  return {static_cast<U>(a[I])...};
}

template<typename U, typename T, std::size_t N, typename Indices = std::make_index_sequence<N>>
constexpr
std::array<U, N>
convert1DArray(const std::array<T, N>& a) {
  return convert1DArrayImpl<U>(a, Indices{});
}

template<typename U, typename T, std::size_t N, std::size_t M, std::size_t... IN>
constexpr
std::array<std::array<U, N>, M>
convert2DArrayImpl(std::array<std::array<T, N>, M> a, std::index_sequence<IN...>) {
  return {convert1DArray<U>(a[IN])...};
}

template<typename U, typename T, std::size_t N, std::size_t M, typename IndicesM = std::make_index_sequence<M>>
constexpr
std::array<std::array<U, N>, M>
convert2DArray(const std::array<std::array<T, N>, M>& a) {
  return convert2DArrayImpl<U>(a, IndicesM{});
}

template<typename U, typename T, std::size_t N, std::size_t M, std::size_t K, std::size_t... IN>
constexpr
std::array<std::array<std::array<U, N>, M>, K>
convert3DArrayImpl(std::array<std::array<std::array<T, N>, M>, K> a, std::index_sequence<IN...>) {
  return {convert2DArray<U>(a[IN])...};
}

template<typename U, typename T, std::size_t N, std::size_t M, std::size_t K, typename IndicesK = std::make_index_sequence<K>>
constexpr
std::array<std::array<std::array<U, N>, M>, K>
convert3DArray(const std::array<std::array<std::array<T, N>, M>, K>& a) {
  return convert3DArrayImpl<U>(a, IndicesK{});
}
</code>```

Live Demo

ContentLicense: CC BY-SA 4.0

Body:
Using C++11 or C++14:

I have a:

constexpr double [2][3][4] = some value;

I want constexpr int [2][3][4] from this.

(Actually I will want constexpr my_type [2][3][4], but that should be trivially solvable once int works.)

The only solution I came up with was a container class with operator[] overloaded so it behaves like an array. Is there a way to keep standard array syntax? Or possibly std::array<std::array...>> without creating a new class?

I do not want the input to be std::array - that is a constraint of the system. The input must be C compatible. The converted array can be C++.

Body:
There's a way to do this by building incrementally. That is, first solve the conversion for 1D arrays. Then based on that solution the conversion for 2D arrays etc.

template<typename U, typename T, std::size_t N, std::size_t... I>
constexpr
std::array<U, N>
convert1DArrayImpl(std::array<T, N> const &a, std::index_sequence<I...>) {
  return {static_cast<U>(a[I])...};
}

template<typename U, typename T, std::size_t N, typename Indices = std::make_index_sequence<N>>
constexpr
std::array<U, N>
convert1DArray(const std::array<T, N>& a) {
  return convert1DArrayImpl<U>(a, Indices{});
}

template<typename U, typename T, std::size_t N, std::size_t M, std::size_t... IN>
constexpr
std::array<std::array<U, N>, M>
convert2DArrayImpl(std::array<std::array<T, N>, M> a, std::index_sequence<IN...>) {
  return {convert1DArray<U>(a[IN])...};
}

template<typename U, typename T, std::size_t N, std::size_t M, typename IndicesM = std::make_index_sequence<M>>
constexpr
std::array<std::array<U, N>, M>
convert2DArray(const std::array<std::array<T, N>, M>& a) {
  return convert2DArrayImpl<U>(a, IndicesM{});
}

template<typename U, typename T, std::size_t N, std::size_t M, std::size_t K, std::size_t... IN>
constexpr
std::array<std::array<std::array<U, N>, M>, K>
convert3DArrayImpl(std::array<std::array<std::array<T, N>, M>, K> a, std::index_sequence<IN...>) {
  return {convert2DArray<U>(a[IN])...};
}

template<typename U, typename T, std::size_t N, std::size_t M, std::size_t K, typename IndicesK = std::make_index_sequence<K>>
constexpr
std::array<std::array<std::array<U, N>, M>, K>
convert3DArray(const std::array<std::array<std::array<T, N>, M>, K>& a) {
  return convert3DArrayImpl<U>(a, IndicesK{});
}

Live Demo


问:
CS7036 C# There is no argument given that corresponds to the required formal parameter of
WHy im i getting this error?</p>

```<code>namespace CalculatorTest
{
    public class Calculator
    {
        public int operand1;
        public int operand2;
        public static string s;
        public static int n;

        public string WriteText(string s)
        {
            return s;
        }

        public string WriteNumber(int n)
        {

            return n.ToString();
        }
        public Calculator(int operand1, int operand2) : base()
        {
            this.operand1 = operand1;
            this.operand2 = operand2;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Calculator c = new Calculator();

        }
    }
}
</code>```

答:
As it is mentioned earlier You defined two parameters for constructor (operand1, operand2) but then You invoke constructor without any. So If You want to have Your  code working use</p>

```<code>Calculator c = new Calculator(5,10);
</code>```

Body:
WHy im i getting this error?

namespace CalculatorTest
{
    public class Calculator
    {
        public int operand1;
        public int operand2;
        public static string s;
        public static int n;

        public string WriteText(string s)
        {
            return s;
        }

        public string WriteNumber(int n)
        {

            return n.ToString();
        }
        public Calculator(int operand1, int operand2) : base()
        {
            this.operand1 = operand1;
            this.operand2 = operand2;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Calculator c = new Calculator();

        }
    }
}

Body:
As it is mentioned earlier You defined two parameters for constructor (operand1, operand2) but then You invoke constructor without any. So If You want to have Your  code working use

Calculator c = new Calculator(5,10);


问:
Is there a way to block or assert on accidental recursion in c#
I am working with a large and complex event driven body of code and there are piles of opportunity to accidentally create a recursive condition.

Sometimes the recursive condition is temporary and the application catches up with itself but even that usually creates unnecessary lag.  Other times it creates a stackoverflow which is often very difficult to debug when it happens at a client site.

I would like to have a way to either blacklist or whitelist sections of code that are permitted to recurse.   If the recursive condition happens during DEV then I want it to assert so that I can correct the code.

What I am considering is having the application examine its own stack to ensure that the method it just entered is not already on the stack.

Any pointers would be appreciated.

Note: This is for a Web Application but I have run into this challenge in multiple environments.

答:
You could call the RuntimeHelpers.EnsureSufficientExecutionStack method and then catch the InsufficientExecutionStackException that is thrown if the next method call would cause a (not catchable) StackOverflowException.

You could create an extension method for it:

```<code>public static T EnsureSafeRecursiveCall<T>(this Func<T> method)
{
    try
    {
        RuntimeHelpers.EnsureSufficientExecutionStack();
        return method();
    }
    catch (InsufficientExecutionStackException ex)
    {
        string msg = $"{method.Method.Name} would cause a {nameof(StackOverflowException)} on the next call";
        Debug.Fail(msg);
        // logging here is essential here because Debug.Fail works only with debug
        throw new StackOverflowException(msg, ex); // wrap in new exception to avoid that we get into this catch again and again(note we are in a recursive call)
    }
}
</code>```

Now your original method remains almost unchanged:

```<code>public static IEnumerable<T> YourRecursiveMethod<T>(IEnumerable<T> seq)
{
    var method = new Func<IEnumerable<T>>(() => YourRecursiveMethod(seq));
    return method.EnsureSafeRecursiveCall();
}
</code>```

Body:
You could call the RuntimeHelpers.EnsureSufficientExecutionStack method and then catch the InsufficientExecutionStackException that is thrown if the next method call would cause a (not catchable) StackOverflowException.

You could create an extension method for it:

public static T EnsureSafeRecursiveCall<T>(this Func<T> method)
{
    try
    {
        RuntimeHelpers.EnsureSufficientExecutionStack();
        return method();
    }
    catch (InsufficientExecutionStackException ex)
    {
        string msg = $"{method.Method.Name} would cause a {nameof(StackOverflowException)} on the next call";
        Debug.Fail(msg);
        // logging here is essential here because Debug.Fail works only with debug
        throw new StackOverflowException(msg, ex); // wrap in new exception to avoid that we get into this catch again and again(note we are in a recursive call)
    }
}

Now your original method remains almost unchanged:

public static IEnumerable<T> YourRecursiveMethod<T>(IEnumerable<T> seq)
{
    var method = new Func<IEnumerable<T>>(() => YourRecursiveMethod(seq));
    return method.EnsureSafeRecursiveCall();
}


问:
Each subject has a subject code.When i select one subject its subject code should be displayed in the edit box
I have a new QLineEdit(box) for the subject code.Each subject has a subject code(for eg Sentiment Analysis has code CS01,Data Cleansing has CS02,etc.).When i select one subject(Sentiment Analysis) its subject code(CS01) should be displayed in the new edit box and when i choose another subject(Data CLeansing) its subject code(CS02) should be dispalyed .How should the problem be solved?   </p>

```<code>import sys
from PyQt4 import QtGui, QtCore

class MyWindow(QtGui.QWidget):
    def __init__(self, parent = None):
        super(MyWindow, self).__init__(parent)
    self.setGeometry(50, 50, 350,350)
    QtGui.QShortcut(QtGui.QKeySequence("Esc"), self, self.close)
        # Create controls
        self.lbl = QtGui.QLabel('Types of Analysis', self)
        self.lbl.setFont(QtGui.QFont('SansSerif', 15) )
        self.cb = QtGui.QComboBox(self)
        self.cb.addItems(['Sentiment Analysis', 'Data Cleansing', 'Genomics', 'Integration', 'Visualization'])
        self.btn = QtGui.QPushButton('Submit', self)

    self.b=QtGui.QLineEdit(self)
    self.b.move(50,130)
    self.cb.currentIndexChanged[str].connect(self.b.setText)

    self.b1=QtGui.QLineEdit(self)
    self.b1.move(50,180)

    # Create layout
        mainLayout = QtGui.QVBoxLayout()
        mainLayout.addWidget(self.lbl)
        mainLayout.addWidget(self.cb)
        mainLayout.addWidget(self.b)
        mainLayout.addWidget(self.b1)
        mainLayout.addWidget(self.btn)
        self.setLayout(mainLayout)

    self.btn.clicked.connect(self.printingaction)

    self.show()

    def printingaction(self):
        print 'Current item: {0}'.format( self.cb.currentIndex() ) # ComboBox's index
        print 'Current index: {0}'.format( self.cb.currentText() ) # ComboBox's text

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    win = MyWindow()
    sys.exit( app.exec_() )
</code>```

答:
To associate a data to an item of the QComboBox you must use the setItemData() method and to obtain the value you use the itemData()

```<code>class MyWindow(QtGui.QWidget):
    def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)

        self.setGeometry(50, 50, 350, 350)
        QtGui.QShortcut(QtGui.QKeySequence("Esc"), self, self.close)  # Create controls
        self.lbl = QtGui.QLabel('Types of Analysis', self)
        self.lbl.setFont(QtGui.QFont('SansSerif', 15))
        self.cb = QtGui.QComboBox(self)
        self.btn = QtGui.QPushButton('Submit', self)
        self.b = QtGui.QLineEdit(self)
        self.b1 = QtGui.QLineEdit(self)

        data = [('Sentiment Analysis', 'CS01'),
                ('Data Cleansing', 'CS02'),
                ('Genomics', 'CS03'),
                ('Integration', 'CS04'),
                ('Visualization', 'CS05')]

        self.cb.currentIndexChanged.connect(self.onCurrentIndexChanged)

        for ix, value in enumerate(data):
            subject, code = value
            self.cb.addItem(subject)
            self.cb.setItemData(ix, code, QtCore.Qt.UserRole)

        self.b.setText(self.cb.itemData(0, QtCore.Qt.UserRole).toString())

        # Create layout
        mainLayout = QtGui.QVBoxLayout(self)
        mainLayout.addWidget(self.lbl)
        mainLayout.addWidget(self.cb)
        mainLayout.addWidget(self.b)
        mainLayout.addWidget(self.b1)
        mainLayout.addWidget(self.btn)
        self.setLayout(mainLayout)

        self.btn.clicked.connect(self.printingaction)

    def onCurrentIndexChanged(self, ix):
        combo = self.sender()
        code = combo.itemData(ix, QtCore.Qt.UserRole).toString()
        self.b.setText(code)

    def printingaction(self):
        print('Current item: {0}'.format(self.cb.currentIndex()))  # ComboBox's index
        print('current index: {0}'.format(self.cb.currentText()))  # ComboBox's text

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    win = MyWindow()
    win.show()
    sys.exit(app.exec_())
</code>```

Body:
I have a new QLineEdit(box) for the subject code.Each subject has a subject code(for eg Sentiment Analysis has code CS01,Data Cleansing has CS02,etc.).When i select one subject(Sentiment Analysis) its subject code(CS01) should be displayed in the new edit box and when i choose another subject(Data CLeansing) its subject code(CS02) should be dispalyed .How should the problem be solved?

import sys
from PyQt4 import QtGui, QtCore

class MyWindow(QtGui.QWidget):
    def __init__(self, parent = None):
        super(MyWindow, self).__init__(parent)
    self.setGeometry(50, 50, 350,350)
    QtGui.QShortcut(QtGui.QKeySequence("Esc"), self, self.close)
        # Create controls
        self.lbl = QtGui.QLabel('Types of Analysis', self)
        self.lbl.setFont(QtGui.QFont('SansSerif', 15) )
        self.cb = QtGui.QComboBox(self)
        self.cb.addItems(['Sentiment Analysis', 'Data Cleansing', 'Genomics', 'Integration', 'Visualization'])
        self.btn = QtGui.QPushButton('Submit', self)

    self.b=QtGui.QLineEdit(self)
    self.b.move(50,130)
    self.cb.currentIndexChanged[str].connect(self.b.setText)

    self.b1=QtGui.QLineEdit(self)
    self.b1.move(50,180)

    # Create layout
        mainLayout = QtGui.QVBoxLayout()
        mainLayout.addWidget(self.lbl)
        mainLayout.addWidget(self.cb)
        mainLayout.addWidget(self.b)
        mainLayout.addWidget(self.b1)
        mainLayout.addWidget(self.btn)
        self.setLayout(mainLayout)

    self.btn.clicked.connect(self.printingaction)

    self.show()

    def printingaction(self):
        print 'Current item: {0}'.format( self.cb.currentIndex() ) # ComboBox's index
        print 'Current index: {0}'.format( self.cb.currentText() ) # ComboBox's text

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    win = MyWindow()
    sys.exit( app.exec_() )

Body:
To associate a data to an item of the QComboBox you must use the setItemData() method and to obtain the value you use the itemData()

class MyWindow(QtGui.QWidget):
    def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)

        self.setGeometry(50, 50, 350, 350)
        QtGui.QShortcut(QtGui.QKeySequence("Esc"), self, self.close)  # Create controls
        self.lbl = QtGui.QLabel('Types of Analysis', self)
        self.lbl.setFont(QtGui.QFont('SansSerif', 15))
        self.cb = QtGui.QComboBox(self)
        self.btn = QtGui.QPushButton('Submit', self)
        self.b = QtGui.QLineEdit(self)
        self.b1 = QtGui.QLineEdit(self)

        data = [('Sentiment Analysis', 'CS01'),
                ('Data Cleansing', 'CS02'),
                ('Genomics', 'CS03'),
                ('Integration', 'CS04'),
                ('Visualization', 'CS05')]

        self.cb.currentIndexChanged.connect(self.onCurrentIndexChanged)

        for ix, value in enumerate(data):
            subject, code = value
            self.cb.addItem(subject)
            self.cb.setItemData(ix, code, QtCore.Qt.UserRole)

        self.b.setText(self.cb.itemData(0, QtCore.Qt.UserRole).toString())

        # Create layout
        mainLayout = QtGui.QVBoxLayout(self)
        mainLayout.addWidget(self.lbl)
        mainLayout.addWidget(self.cb)
        mainLayout.addWidget(self.b)
        mainLayout.addWidget(self.b1)
        mainLayout.addWidget(self.btn)
        self.setLayout(mainLayout)

        self.btn.clicked.connect(self.printingaction)

    def onCurrentIndexChanged(self, ix):
        combo = self.sender()
        code = combo.itemData(ix, QtCore.Qt.UserRole).toString()
        self.b.setText(code)

    def printingaction(self):
        print('Current item: {0}'.format(self.cb.currentIndex()))  # ComboBox's index
        print('current index: {0}'.format(self.cb.currentText()))  # ComboBox's text

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    win = MyWindow()
    win.show()
    sys.exit(app.exec_())


问:
what is the most pythonic way to split a 2d array to arrays of each row?
I have a function foo that returns an array with the shape (1000, 2)
how can I split it to two arrays a(1000) and b(1000)
I'm looking for something like this:

```<code>a;b = foo()
</code>```

I'm looking for an answer that can easily generalize to the case in which the shape is (1000, 5) or so.

答:
So this is a little nuts, but if you want to assign different letters to each sub-array in your array, and do so for any number of sub-arrays (up to 26 because alphabet), you could do:

```<code>import string
letters = list(string.ascii_lowercase)  # get all of the lower-case letters
arr_dict = {k: v for k, v in zip(letters, foo())}
</code>```

or more simply (for the last line):

```<code>arr_dict = dict(zip(letters, foo()))
</code>```

Then you can access each individual element as arr_dict['a'] or arr_dict['b']. This feels a little mad-scientist-ey to me, but I thought it was fun.

Body:
I have a function foo that returns an array with the shape (1000, 2)
how can I split it to two arrays a(1000) and b(1000)
I'm looking for something like this:

a;b = foo()

I'm looking for an answer that can easily generalize to the case in which the shape is (1000, 5) or so.

Body:
So this is a little nuts, but if you want to assign different letters to each sub-array in your array, and do so for any number of sub-arrays (up to 26 because alphabet), you could do:

import string
letters = list(string.ascii_lowercase)  # get all of the lower-case letters
arr_dict = {k: v for k, v in zip(letters, foo())}

or more simply (for the last line):

arr_dict = dict(zip(letters, foo()))

Then you can access each individual element as arr_dict['a'] or arr_dict['b']. This feels a little mad-scientist-ey to me, but I thought it was fun.


问:
Codeigniter 3 registration application: let user know email already exists via a flash message
I have made a Registration and Login application with Codeigniter 3.

The Signup form validation makes sure that every email in the users table is unique, as illustrated bellow:

Instead of "The Email field must contain a unique value" below the e-mail field, I want a flash message to let the user know the provided email already exists and that he/she should sigin in instead of signing up:

I am using an $email_exists function inside an if statement but the function itself does not exist yet.

I want to make use of CI's is_unique inside the $email_exists function. How can I do this?

Is this a good approach to achieving the desired functionality?

My signup() function looks like this:

```<code>public function signup()
 {
    $this->form_validation->set_rules('first_name', 'First name', 'required');
    $this->form_validation->set_rules('last_name', 'Last name', 'required');
    $this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email|is_unique[users.email]');
    $this->form_validation->set_rules('password', 'Password', 'required|matches[cpassword]');
    $this->form_validation->set_rules('cpassword', 'Confirm password', 'required');
    $this->form_validation->set_error_delimiters('<p class="error">', '</p>');

    if ($this->form_validation->run()) {
        $first_name = $this->input->post('first_name');
        $last_name = $this->input->post('last_name');
        $email =  $this->input->post('email');
        $password = $this->input->post('password');
        $date_created = date('Y-m-d H:i:s');
        $date_updated = date('Y-m-d H:i:s');
        $verification_key = md5($email);
        $active = 0;
        $this->load->model('Usermodel');
        // Create account
        if ($this->Usermodel->user_register($first_name, $last_name, $email, $password, $date_created, $date_updated, $verification_key, $active)) {
            $this->session->set_flashdata("signup_sucess", "Your account was created. Your have to activate it before you can signin. We have send you an activation email at $email.");
        } else {
            $this->session->set_flashdata("signup_failure", "We ware unable to create your account");
        }
        redirect('signup');
    } else {
        $this->load->view('signup');
        if ($email_exists) {
            $this->session->set_flashdata("email_exists", "The email address you provided already exists. Please signup.");
        }
    }
}
</code>```

答:
```<code>public function signup()
{
    $this->form_validation->set_rules('first_name', 'First name', 'required');
    $this->form_validation->set_rules('last_name', 'Last name', 'required');
    $this->form_validation->set_rules('email', 'Email', );
    $this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email|is_unique[users.email]',
            array('required' => 'Email is Required.'),
            array('is_unique' => 'Email Already exist.')
    );
    $this->form_validation->set_rules('password', 'Password', 'required|matches[cpassword]');
    $this->form_validation->set_rules('cpassword', 'Confirm password', 'required');
    $this->form_validation->set_error_delimiters('<p class="error">', '</p>');

    if ($this->form_validation->run() != FALSE)
    {
        $email = $this->input->post('email');
        $first_name = $this->input->post('first_name');
        $last_name = $this->input->post('last_name');
        $password = $this->input->post('password');
        $date_created = date('Y-m-d H:i:s');
        $date_updated = date('Y-m-d H:i:s');
        $verification_key = md5($email);
        $active = 0;
        $this->load->model('Usermodel');
        // Create account
        if ($this->Usermodel->user_register($first_name, $last_name, $email, $password, $date_created, $date_updated ,$verification_key , $active))
        {
            // Create a view for Check Email in View.
            $this->load->view('Check_Email_view');
        }
        else
        {
            $signup_failure="Something Went Wrong Please Sign Up again.";
            $this->load->view('signup',$signup_failure, true);
            // in view Use Isset($signup_failure)
        }
    }
    else
    {
        $this->load->view('signup');
    }
}
</code>```

Body:
I have made a Registration and Login application with Codeigniter 3.

The Signup form validation makes sure that every email in the users table is unique, as illustrated bellow:

Instead of "The Email field must contain a unique value" below the e-mail field, I want a flash message to let the user know the provided email already exists and that he/she should sigin in instead of signing up:

I am using an $email_exists function inside an if statement but the function itself does not exist yet.

I want to make use of CI's is_unique inside the $email_exists function. How can I do this?

Is this a good approach to achieving the desired functionality?

My signup() function looks like this:

public function signup()
 {
    $this->form_validation->set_rules('first_name', 'First name', 'required');
    $this->form_validation->set_rules('last_name', 'Last name', 'required');
    $this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email|is_unique[users.email]');
    $this->form_validation->set_rules('password', 'Password', 'required|matches[cpassword]');
    $this->form_validation->set_rules('cpassword', 'Confirm password', 'required');
    $this->form_validation->set_error_delimiters('
', '
');

    if ($this->form_validation->run()) {
        $first_name = $this->input->post('first_name');
        $last_name = $this->input->post('last_name');
        $email =  $this->input->post('email');
        $password = $this->input->post('password');
        $date_created = date('Y-m-d H:i:s');
        $date_updated = date('Y-m-d H:i:s');
        $verification_key = md5($email);
        $active = 0;
        $this->load->model('Usermodel');
        // Create account
        if ($this->Usermodel->user_register($first_name, $last_name, $email, $password, $date_created, $date_updated, $verification_key, $active)) {
            $this->session->set_flashdata("signup_sucess", "Your account was created. Your have to activate it before you can signin. We have send you an activation email at $email.");
        } else {
            $this->session->set_flashdata("signup_failure", "We ware unable to create your account");
        }
        redirect('signup');
    } else {
        $this->load->view('signup');
        if ($email_exists) {
            $this->session->set_flashdata("email_exists", "The email address you provided already exists. Please signup.");
        }
    }
}


问:
Why fopen() does not open my data?
My code does not happen any error, it seems in my opinion my fopen() in FILE* file= fopen("008.espresso.din", "r"); can not open the file that i'm using, if it does not happen any error, i don't know what else to do. why i can't open the file ?,
my data is like this :

```<code>2 400170 8fa40000
0 7ffebc84 0
2 400174 3c1c1001
2 400178 279cc660
2 40017c 27a50004
2 400180 af8589a8
</code>```

i compile it with gcc -o cache cache.c -lm

here is the code :

```<code>#include <stdio.h>
#include <stdlib.h>
#include <math.h>

/* struktur baca */
struct read
{
    int dummy1;
    int address;
    int dummy2;
}read;

/* struktur memory address */
struct memaddress
{
    int tag;
    int set;
}mem;

/*struktur cache */
struct cache
{
    int tag;
    int valid;
};

int main(void)
{
    int i;
    double hitrate;
    double missrate;
    int maskingsetbit;
    struct cache* cache;
    int set=0, bitset;
    int block, bitblock;
    int miss=0;
    int hit=0;
    int total=0;

    /* jumlah cache dan block */
    do{
        printf("Masukkan jumlah set cache:");
        scanf("%d", &set);
        printf("Masukkan jumlah block:");
        scanf("%d", &block);

        /* hitung jumlah bit */
        bitset=log2(set);
        bitblock=log2(block*4);
        maskingsetbit=pow(2,bitset)-1;

        /* periksa jumlah bit */
    }while (bitset+bitblock>31);

    /*alokasi memory pada cache */
    cache=(struct cache*) malloc(set*sizeof(struct cache));

    /* buka file */
    FILE* file= fopen("008.espresso.din", "r");

    /* inisialisasi cache */
    for(i=0;i<set;i++)
    {
        cache[i].valid=0;
        cache[i].tag=0;
    }
    while (!feof(file))
    {
        /* baca data dinero */
        fscanf(file, "%x", &read.dummy1);
        if(feof(file))
            break;
        fscanf(file, "%x", &read.address);
        fscanf(file, "%x", &read.dummy2);

        /*pilah bit tag dari address */
        mem.tag = read.address>>(bitblock+bitset);
        mem.set = (read.address>>bitblock)&(maskingsetbit);

        /*hitung total reference */
        total++;

        if(cache[mem.set].valid==0)
        {
            miss++;
            cache[mem.set].valid=1;
            cache[mem.set].tag=mem.tag;
        }else{
            if(cache[mem.set].tag!=mem.tag)
            {
                miss++;
                cache[mem.set].tag!=mem.tag;
            }else{
                hit++;
            }
        }

        /* hitung hit rate dan miss rate */
        hitrate=hit;
        hitrate=hitrate/total*100;
        missrate=miss;
        missrate=missrate/total*100;

        printf("\n\nTotal Hit\t=%d\n",hit);
        printf("Total Miss\t=%d\n",miss);
        printf("Hitt Rate\t=%.2f%%\n",hitrate);
        printf("Miss Rate\t=%.2f%%\n",missrate);
        printf("Total Reference\t=%d\n",total);

        fclose(file);
        return(0);

    }
}
</code>```

答:
It already has a comparison on it, and yeah, it stupidly does some calculation and prints out inside the while loop.  It works, it prints like this:

Total Hit =448264 Total Miss  =551736 Hitt Rate   =44.83% Miss
  Rate  =55.17% Total Reference =1000000

Title: Why fopen() does not open my data?

Body:
My code does not happen any error, it seems in my opinion my fopen() in FILE* file= fopen("008.espresso.din", "r"); can not open the file that i'm using, if it does not happen any error, i don't know what else to do. why i can't open the file ?,
my data is like this :

2 400170 8fa40000
0 7ffebc84 0
2 400174 3c1c1001
2 400178 279cc660
2 40017c 27a50004
2 400180 af8589a8

i compile it with gcc -o cache cache.c -lm

here is the code :

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

/* struktur baca */
struct read
{
    int dummy1;
    int address;
    int dummy2;
}read;

/* struktur memory address */
struct memaddress
{
    int tag;
    int set;
}mem;

/*struktur cache */
struct cache
{
    int tag;
    int valid;
};

int main(void)
{
    int i;
    double hitrate;
    double missrate;
    int maskingsetbit;
    struct cache* cache;
    int set=0, bitset;
    int block, bitblock;
    int miss=0;
    int hit=0;
    int total=0;

    /* jumlah cache dan block */
    do{
        printf("Masukkan jumlah set cache:");
        scanf("%d", &set);
        printf("Masukkan jumlah block:");
        scanf("%d", &block);

        /* hitung jumlah bit */
        bitset=log2(set);
        bitblock=log2(block*4);
        maskingsetbit=pow(2,bitset)-1;

        /* periksa jumlah bit */
    }while (bitset+bitblock>31);

    /*alokasi memory pada cache */
    cache=(struct cache*) malloc(set*sizeof(struct cache));

    /* buka file */
    FILE* file= fopen("008.espresso.din", "r");

    /* inisialisasi cache */
    for(i=0;i<set;i++)
    {
        cache[i].valid=0;
        cache[i].tag=0;
    }
    while (!feof(file))
    {
        /* baca data dinero */
        fscanf(file, "%x", &read.dummy1);
        if(feof(file))
            break;
        fscanf(file, "%x", &read.address);
        fscanf(file, "%x", &read.dummy2);

        /*pilah bit tag dari address */
        mem.tag = read.address>>(bitblock+bitset);
        mem.set = (read.address>>bitblock)&(maskingsetbit);

        /*hitung total reference */
        total++;

        if(cache[mem.set].valid==0)
        {
            miss++;
            cache[mem.set].valid=1;
            cache[mem.set].tag=mem.tag;
        }else{
            if(cache[mem.set].tag!=mem.tag)
            {
                miss++;
                cache[mem.set].tag!=mem.tag;
            }else{
                hit++;
            }
        }

        /* hitung hit rate dan miss rate */
        hitrate=hit;
        hitrate=hitrate/total*100;
        missrate=miss;
        missrate=missrate/total*100;

        printf("\n\nTotal Hit\t=%d\n",hit);
        printf("Total Miss\t=%d\n",miss);
        printf("Hitt Rate\t=%.2f%%\n",hitrate);
        printf("Miss Rate\t=%.2f%%\n",missrate);
        printf("Total Reference\t=%d\n",total);

        fclose(file);
        return(0);

    }
}


问:
AngularJS: promise in a loop
I am unable to do the promise looping.

I make a service call to get list of providers, then for each provider, I make another service call to get a customer.

A provider has 1 or more customers. So eventual list of customer is to be decorated and displayed.

In other format I am trying to achieve:

```<code>*serviceA.getProvider(){

  foreach(providers){

   foreach(provider.customerID){

    serviceB.getCustomer(customerId)

   }

  }

}
.then(

  foreach(Customer){

   updateTheCustomer;

   addUpdatedCustomerToAList

  }

displayUpdatedCustomreList();

)*
</code>```

I have written following code, that isn't working

```<code>doTheJob(model: Object) {
    let A = [];
    let B = [];

let fetchP = function(obj) {
  obj.Service1.fetchAllP().then(function (response) {
    let P = cloneDeep(response.data);

    _.forEach(P, function(prov) {
      _.forEach(prov.CIds, function(Id) {
        A.push(Id);
      });
    });

    _.forEach(A, function(CId) {
      return obj.Service2.getById(CId);//what works is if this statement was: return obj.Service2.getById(A[0]);
                                        //So, clearly, returning promise inside loop isn't working
    });
  })
  .then(function(response) {
    B.push(response.data); //This response is undefined

    angular.forEach(B, function (value) {
      obj.updateAdr(value)
    });

    obj.dispay(B);
  });
};
fetchP(this);

}
</code>```

答: forEach don't stop when you use return inside of it, try to use a plain loop instead, why you don't just loop with for ?

Title: AngularJS: promise in a loop

Body:
I am unable to do the promise looping.

I make a service call to get list of providers, then for each provider, I make another service call to get a customer.

A provider has 1 or more customers. So eventual list of customer is to be decorated and displayed.

In other format I am trying to achieve:

*serviceA.getProvider(){

  foreach(providers){

   foreach(provider.customerID){

    serviceB.getCustomer(customerId)

   }

  }

}
.then(

  foreach(Customer){

   updateTheCustomer;

   addUpdatedCustomerToAList

  }

displayUpdatedCustomreList();

)*

I have written following code, that isn't working

doTheJob(model: Object) {
    let A = [];
    let B = [];

let fetchP = function(obj) {
  obj.Service1.fetchAllP().then(function (response) {
    let P = cloneDeep(response.data);

    _.forEach(P, function(prov) {
      _.forEach(prov.CIds, function(Id) {
        A.push(Id);
      });
    });

    _.forEach(A, function(CId) {
      return obj.Service2.getById(CId);//what works is if this statement was: return obj.Service2.getById(A[0]);
                                        //So, clearly, returning promise inside loop isn't working
    });
  })
  .then(function(response) {
    B.push(response.data); //This response is undefined

    angular.forEach(B, function (value) {
      obj.updateAdr(value)
    });

    obj.dispay(B);
  });
};
fetchP(this);

}


问:
WindowState: System.InvalidOperationException: Nullable object must have a value
I am working on a Windows app (running on Windows 10, built with VS2017) which threw the following exception:

The method that caused the exception is:

```<code>    private void RestoreWindow()
    {
        this.WindowState = WindowState.Normal;

        this.Width = this.LastSize.Value.Width;
        this.Height = this.LastSize.Value.Height;
        this.Left = this.LastSize.Value.X;
        this.Top = this.LastSize.Value.Y;

        this.LastSize = null;
    }
</code>```

The state change event is handled like so:

```<code>    private void windowChat_StateChanged(object sender, EventArgs e)
    {
        if (WindowState.Normal == this.WindowState)
        {
            this.MaxHeight = Double.PositiveInfinity;
            this.MaxWidth = Double.PositiveInfinity;
        }
    }
</code>```

My understanding is that this exception is caused when the object is NULL, in this case WindowState, but I don't see how that is possible since it is a system property.

The stack trace is:

System.InvalidOperationException: Nullable object must have a value.

  at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)

  at RestoreWindow() in x.cs:line 324

  at RestoreButton_Click(Object sender, RoutedEventArgs e) in x.cs:line 100

  at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)

  at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)

  at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)

  at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)

  at System.Windows.Controls.Primitives.ButtonBase.OnClick()

  at System.Windows.Controls.Button.OnClick()

  at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)

  at System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender, MouseButtonEventArgs e)

  at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)

  at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)

  at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)

  at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)

  at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)

  at System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e)

  at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)

  at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)

  at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)

  at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)

  at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)

  at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)

  at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)

  at System.Windows.Input.InputManager.ProcessStagingArea()

  at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)

  at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)

  at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)

  at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)

  at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)

  at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)

  at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)

  at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)

  at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)

答:
The stack trace indicated a problem at line 324, which was this line of code:

```<code>this.WindowState = WindowState.Normal;
</code>```

But the issue was with LastSize being null.

Body:
I am working on a Windows app (running on Windows 10, built with VS2017) which threw the following exception:

The method that caused the exception is:

    private void RestoreWindow()
    {
        this.WindowState = WindowState.Normal;

        this.Width = this.LastSize.Value.Width;
        this.Height = this.LastSize.Value.Height;
        this.Left = this.LastSize.Value.X;
        this.Top = this.LastSize.Value.Y;

        this.LastSize = null;
    }

The state change event is handled like so:

    private void windowChat_StateChanged(object sender, EventArgs e)
    {
        if (WindowState.Normal == this.WindowState)
        {
            this.MaxHeight = Double.PositiveInfinity;
            this.MaxWidth = Double.PositiveInfinity;
        }
    }

My understanding is that this exception is caused when the object is NULL, in this case WindowState, but I don't see how that is possible since it is a system property.

The stack trace is:

System.InvalidOperationException: Nullable object must have a value.

  at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)

  at RestoreWindow() in x.cs:line 324

  at RestoreButton_Click(Object sender, RoutedEventArgs e) in x.cs:line 100

  at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)

  at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)

  at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)

  at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)

  at System.Windows.Controls.Primitives.ButtonBase.OnClick()

  at System.Windows.Controls.Button.OnClick()

  at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)

  at System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender, MouseButtonEventArgs e)

  at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)

  at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)

  at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)

  at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)

  at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)

  at System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e)

  at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)

  at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)

  at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)

  at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)

  at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)

  at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)

  at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)

  at System.Windows.Input.InputManager.ProcessStagingArea()

  at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)

  at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)

  at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)

  at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)

  at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)

  at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)

  at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)

  at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)

  at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)

Body:
The stack trace indicated a problem at line 324, which was this line of code:

this.WindowState = WindowState.Normal;

But the issue was with LastSize being null.


问:
How to Change the MenuItem Colors of Forms ViewList in iOS ViewCellRenderer?
Is there any way to Change the color of ContextAction Menus added in Xamarin.Forms Xaml file. IsDestructive="True" sets the menu color to Red. But i need another menu to look like Green or some other color.

Here is my Forms Xaml code..

```<code><ListView x:Name="planList" ItemsSource="{x:Static local:SampleData.PLAN_DATA}" RowHeight="150" HorizontalOptions="FillAndExpand">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <ViewCell.ContextActions>
                    <MenuItem Clicked="OnEditClick" Text="Edit" CommandParameter="{Binding .}"/> <!-- THIS HAS TO BE GREEN COLOR -->
                    <MenuItem Clicked="OnDeleteClick" Text="Delete" IsDestructive="True" />
                </ViewCell.ContextActions>
                <ViewCell.View>
                    <StackLayout Orientation="Vertical"  HorizontalOptions="Start" VerticalOptions="FillAndExpand">
                        <!--Non Editable State-->
                        <StackLayout Orientation="Horizontal" Spacing="28" IsVisible="{Binding isNotSaveState}">
                            <Frame  WidthRequest="130" HeightRequest="50" BackgroundColor="#151617" HorizontalOptions="Start">
                                <Label Text="{Binding from}" TextColor="#ff9600" FontSize="Medium" FontFamily="Helvetica"/>
                            </Frame>
                        </StackLayout>
                        <!--Editable State-->
                        <StackLayout Orientation="Horizontal" Spacing="0"  IsVisible="{Binding isSaveState}">
                            <StackLayout Orientation="Horizontal" Spacing="5">
                                <Label Text="From" TextColor="#838288"  FontSize="Medium" FontFamily="Helvetica"/>
                                <Entry Text="" BackgroundColor="Red"/>
                            </StackLayout>
                            <Button Text="Save" BackgroundColor="Green" CommandParameter="{Binding .}" Clicked="onSaveClick" />
                        </StackLayout>
                    </StackLayout>
                </ViewCell.View>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>
</code>```

Here is my Renderer..

```<code>[assembly: ExportRenderer(typeof(MyApp.Views.Cells.CustomViewCell), typeof(MyApp.iOS.Views.Cells.CustomViewCellRenderer))]
namespace MyApp.iOS.Views.Cells
{

    public class CustomViewCellRenderer : ViewCellRenderer
    {
        public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv)
        {
            UITableViewCell cell = base.GetCell(item, reusableCell, tv);

            // I have no Idea how to access the Swipe Menus from Renderer

            //cell.EditingAccessory
            //cell.EditingAccessoryView

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

答:
For  Xamarin.Forms.2.3.3.193 & Xamarin.Forms.Platform.iOS (2.x) version number Version=2.0.0.0 and field names Case changed to NormalBackground & DestructiveBackground

using System;

using CoreGraphics;
using Foundation;
using UIKit;

using Xamarin.Forms.Platform.iOS;
using Xamarin.Forms;
using System.Reflection;

[assembly: ExportRenderer(typeof(ViewCell), typeof(App.Renderers.CustomViewCellRenderer))]
namespace App.Renderers
{
    public class CustomViewCellRenderer : ViewCellRenderer
    {
        public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv)
        {
            UITableViewCell cell = base.GetCell(item, reusableCell, tv);

            try
            {
                // This is the assembly full name which may vary by the Xamarin.Forms version installed.
                // NullReferenceException is raised if the full name is not correct.
                var globalContextViewCell = Type.GetType("Xamarin.Forms.Platform.iOS.ContextActionsCell, Xamarin.Forms.Platform.iOS, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null");

                // Now change the static field value! "NormalBackground" OR "DestructiveBackground"
                if(globalContextViewCell != null)
                {
                    var normalButton = globalContextViewCell.GetField("NormalBackground", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);

                    if (normalButton != null)
                    {
                        normalButton.SetValue(null, getImageBasedOnColor("ff9500"));
                    }

                    var destructiveButton = globalContextViewCell.GetField("DestructiveBackground", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);

                    if (destructiveButton != null)
                    {
                        destructiveButton.SetValue(null, getImageBasedOnColor("B3B3B3"));
                    }
                }

            }
            catch (Exception e)
            {
                Console.WriteLine("Error in setting background color of Menu Item : " + e.ToString());
            }

            return cell;
        }

        private UIImage getImageBasedOnColor(string colorCode)
        {
            // Get UIImage with a green color fill
            CGRect rect = new CGRect(0, 0, 1, 1);
            CGSize size = rect.Size;
            UIGraphics.BeginImageContext(size);
            CGContext currentContext = UIGraphics.GetCurrentContext();
            currentContext.SetFillColor(Color.FromHex(colorCode).ToCGColor());
            currentContext.FillRect(rect);
            var backgroundImage = UIGraphics.GetImageFromCurrentImageContext();
            currentContext.Dispose();

            return backgroundImage;
        }

    }

}
```

Body:
Is there any way to Change the color of ContextAction Menus added in Xamarin.Forms Xaml file. IsDestructive="True" sets the menu color to Red. But i need another menu to look like Green or some other color.

Here is my Forms Xaml code..

<ListView x:Name="planList" ItemsSource="{x:Static local:SampleData.PLAN_DATA}" RowHeight="150" HorizontalOptions="FillAndExpand">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <ViewCell.ContextActions>
                    <MenuItem Clicked="OnEditClick" Text="Edit" CommandParameter="{Binding .}"/>
                    <MenuItem Clicked="OnDeleteClick" Text="Delete" IsDestructive="True" />
                </ViewCell.ContextActions>
                <ViewCell.View>
                    <StackLayout Orientation="Vertical"  HorizontalOptions="Start" VerticalOptions="FillAndExpand">

                        <StackLayout Orientation="Horizontal" Spacing="28" IsVisible="{Binding isNotSaveState}">
                            <Frame  WidthRequest="130" HeightRequest="50" BackgroundColor="#151617" HorizontalOptions="Start">

                            </Frame>
                        </StackLayout>

                        <StackLayout Orientation="Horizontal" Spacing="0"  IsVisible="{Binding isSaveState}">
                            <StackLayout Orientation="Horizontal" Spacing="5">

                                <Entry Text="" BackgroundColor="Red"/>
                            </StackLayout>
                            <Button Text="Save" BackgroundColor="Green" CommandParameter="{Binding .}" Clicked="onSaveClick" />
                        </StackLayout>
                    </StackLayout>
                </ViewCell.View>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

Here is my Renderer..

[assembly: ExportRenderer(typeof(MyApp.Views.Cells.CustomViewCell), typeof(MyApp.iOS.Views.Cells.CustomViewCellRenderer))]
namespace MyApp.iOS.Views.Cells
{

    public class CustomViewCellRenderer : ViewCellRenderer
    {
        public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv)
        {
            UITableViewCell cell = base.GetCell(item, reusableCell, tv);

            // I have no Idea how to access the Swipe Menus from Renderer

            //cell.EditingAccessory
            //cell.EditingAccessoryView

            return cell;
        }
    }
}