问:
Impossible to convert to float
I am doing some data visualization with matplotlib. I import a .csv file looking like this:

```<code>df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 12 entries, 0 to 11
Data columns (total 9 columns):
 #   Column       Non-Null Count  Dtype
---  ------       --------------  -----
 0   Month#       12 non-null     int64
 1   Face_Cream   12 non-null     int64
 2   Face_Wash    12 non-null     int64
 3   Toothpaste   12 non-null     int64
 4   Bath_Soap    12 non-null     int64
 5   Shampoo      12 non-null     int64
 6   Moisturizer  12 non-null     int64
 7   Total_Units  12 non-null     int64
 8   Profit       12 non-null     object
dtypes: int64(8), object(1)
memory usage: 992.0+ bytes
</code>```

No matter what I do, I cannot convert the 'Profit' column to float. It previously had '$', and whitespace in the column's elements, but I have removed them all with:

```<code>df.Profit # before
Out[125]:
0     $181,660.60
1     $177,954.70
2     $169,498.45
3     $166,075.80
4     $173,176.85
5     $201,538.70
6     $190,267.00
7     $151,039.35
8     $197,819.60
9     $161,810.55
10    $187,298.65
11    $196,434.70
Name: Profit, dtype: object

df.Profit = [num.replace('$', '').replace(' ', '').replace("'", "") for num in df.Profit]

df.Profit # after
Out[127]:
0     181,660.60
1     177,954.70
2     169,498.45
3     166,075.80
4     173,176.85
5     201,538.70
6     190,267.00
7     151,039.35
8     197,819.60
9     161,810.55
10    187,298.65
11    196,434.70
Name: Profit, dtype: object
</code>```

Alas, I have tried the astype(), convert_dtypes() methods but nothing seems to work. What am I missing?

```<code>  Month#  Face_Cream  Face_Wash      Moisturizer  Total_Units      Profit
1       2        2090       1390         1720        24600      $177,954.70
2       3        2280       1280         2020        23390      $169,498.45
3       4        3340       1890         1550        23020      $166,075.80
4       5        2820       1550         1860        23960      $173,176.85
</code>```

Title: Impossible to convert to float

Body:
I am doing some data visualization with matplotlib. I import a .csv file looking like this:

df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 12 entries, 0 to 11
Data columns (total 9 columns):
 #   Column       Non-Null Count  Dtype
---  ------       --------------  -----
 0   Month#       12 non-null     int64
 1   Face_Cream   12 non-null     int64
 2   Face_Wash    12 non-null     int64
 3   Toothpaste   12 non-null     int64
 4   Bath_Soap    12 non-null     int64
 5   Shampoo      12 non-null     int64
 6   Moisturizer  12 non-null     int64
 7   Total_Units  12 non-null     int64
 8   Profit       12 non-null     object
dtypes: int64(8), object(1)
memory usage: 992.0+ bytes

No matter what I do, I cannot convert the 'Profit' column to float. It previously had '$', and whitespace in the column's elements, but I have removed them all with:

df.Profit # before
Out[125]:
0     $181,660.60
1     $177,954.70
2     $169,498.45
3     $166,075.80
4     $173,176.85
5     $201,538.70
6     $190,267.00
7     $151,039.35
8     $197,819.60
9     $161,810.55
10    $187,298.65
11    $196,434.70
Name: Profit, dtype: object

df.Profit = [num.replace('$', '').replace(' ', '').replace("'", "") for num in df.Profit]

df.Profit # after
Out[127]:
0     181,660.60
1     177,954.70
2     169,498.45
3     166,075.80
4     173,176.85
5     201,538.70
6     190,267.00
7     151,039.35
8     197,819.60
9     161,810.55
10    187,298.65
11    196,434.70
Name: Profit, dtype: object

Alas, I have tried the astype(), convert_dtypes() methods but nothing seems to work. What am I missing?

  Month#  Face_Cream  Face_Wash      Moisturizer  Total_Units      Profit
1       2        2090       1390         1720        24600      $177,954.70
2       3        2280       1280         2020        23390      $169,498.45
3       4        3340       1890         1550        23020      $166,075.80
4       5        2820       1550         1860        23960      $173,176.85

Body:
You can cast it directly to float in list comprehension (and replace "," with "", float don't knows ",")

df = pd.DataFrame({'Profit': ['$181,660.60', '$177,954.70', '$169,498.45', '$166,075.80', '$173,176.85', '$201,538.70', '$190,267.00']})
df.Profit = [float((num).replace('$', '').replace(' ', '').replace("'", "").replace(",", "")) for num in df.Profit]
print(df.info())
print(df.head())

Output:

#   Column  Non-Null Count  Dtype
---  ------  --------------  -----
 0   Profit  5 non-null      float64
dtypes: float64(1)

    Profit
0   181660.60
1   177954.70
2   169498.45
3   166075.80
4   173176.85


来源: stackexchange

问:
Android Kotlin - app crash RuntimeException NullPointerException in MainActivity.I
In the gogole play console I see that some of the users with android 10, 11 and 12 are getting this error:

```<code>java.lang.RuntimeException:
  at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:4031)
  at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:4197)
  at android.app.servertransaction.LaunchActivityItem.execute (LaunchActivityItem.java:103)
  at android.app.servertransaction.TransactionExecutor.executeCallbacks (TransactionExecutor.java:135)
  at android.app.servertransaction.TransactionExecutor.execute (TransactionExecutor.java:95)
  at android.app.ActivityThread$H.handleMessage (ActivityThread.java:2434)
  at android.os.Handler.dispatchMessage (Handler.java:106)
  at android.os.Looper.loopOnce (Looper.java:226)
  at android.os.Looper.loop (Looper.java:313)
  at android.app.ActivityThread.main (ActivityThread.java:8633)
  at java.lang.reflect.Method.invoke (Native Method)
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:567)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1133)
Caused by: java.lang.NullPointerException:
  at com.domain.bla.MainActivity.I (MainActivity.java:30)
  at com.domain.bla.MainActivity.setNavi (MainActivity.java)
  at com.domain.bla.MainActivity.onCreate (MainActivity.java)
  at android.app.Activity.performCreate (Activity.java:8282)
  at android.app.Activity.performCreate (Activity.java:8262)
  at android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1329)
  at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:4005)
  at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:4197)
  at android.app.servertransaction.LaunchActivityItem.execute (LaunchActivityItem.java:103)
  at android.app.servertransaction.TransactionExecutor.executeCallbacks (TransactionExecutor.java:135)
  at android.app.servertransaction.TransactionExecutor.execute (TransactionExecutor.java:95)
  at android.app.ActivityThread$H.handleMessage (ActivityThread.java:2434)
  at android.os.Handler.dispatchMessage (Handler.java:106)
  at android.os.Looper.loopOnce (Looper.java:226)
  at android.os.Looper.loop (Looper.java:313)
  at android.app.ActivityThread.main (ActivityThread.java:8633)
  at java.lang.reflect.Method.invoke (Native Method)
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:567)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1133)
</code>```

I don't have the function i() in MainActivity or anywhere in the app, maybe in one of the libraries but not from me.

I have testing devices with android 11 and 12 but can't reproduce this error, everything works as it should on those.

Posting the whole MainActivity would be way too much sicne it's over 1300 lines.

This is the setNavi function:

```<code>private fun setNavi(gal: String){

    val toggle = ActionBarDrawerToggle(
        this, binding.drawerLayout, binding.contentMain.toolbar, 0, 0
    )

    binding.drawerLayout.addDrawerListener(toggle)
    toggle.syncState()
    binding.navView.setNavigationItemSelectedListener(this)

    if(gal == "latest"){
        binding.navView.setCheckedItem(R.id.nav_latest)
    }else{
        binding.navView.setCheckedItem(R.id.nav_top)
    }

    binding.navView.itemIconTintList = null

    binding.contentMain.btnOpenSearch.setOnClickListener {
        binding.drawerLayout.closeDrawer(GravityCompat.START, true)
        val i = Intent(this@MainActivity, SearchInput::class.java)
        this.startActivity(i)
    }

    val headerLayout = binding.navView.getHeaderView(0) // to set stuff in menu
    //headerLayout.btnUpload.setOnClickListener {

    val btnUpload: ConstraintLayout = headerLayout.findViewById(R.id.btnUpload)
    btnUpload.setOnClickListener {
        if(prefs.getLong("userid", 0) == 0.toLong()){
            val i = Intent(this, Login::class.java)
            this.startActivity(i)

        }else{
            binding.drawerLayout.closeDrawer(GravityCompat.START, true)

            val i = Intent(this, Upload::class.java)
            startActivity(i)
        }
    }

    setHeader()
}
</code>```

maybe the problem is in there?

答: This happens because your app has minify enabled in your release build, it obfuscates and optimizes your code, therefore will show things on different lines. You can have a more assertive stacktrace if you provide google play the txt file provided by your minify method. Read: https://developer.android.com/studio/build/shrink-code#decode-stack-trace</p>

ContentLicense: CC BY-SA 4.0

Body:
In the gogole play console I see that some of the users with android 10, 11 and 12 are getting this error:

java.lang.RuntimeException:
  at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:4031)
  at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:4197)
  at android.app.servertransaction.LaunchActivityItem.execute (LaunchActivityItem.java:103)
  at android.app.servertransaction.TransactionExecutor.executeCallbacks (TransactionExecutor.java:135)
  at android.app.servertransaction.TransactionExecutor.execute (TransactionExecutor.java:95)
  at android.app.ActivityThread$H.handleMessage (ActivityThread.java:2434)
  at android.os.Handler.dispatchMessage (Handler.java:106)
  at android.os.Looper.loopOnce (Looper.java:226)
  at android.os.Looper.loop (Looper.java:313)
  at android.app.ActivityThread.main (ActivityThread.java:8633)
  at java.lang.reflect.Method.invoke (Native Method)
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:567)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1133)
Caused by: java.lang.NullPointerException:
  at com.domain.bla.MainActivity.I (MainActivity.java:30)
  at com.domain.bla.MainActivity.setNavi (MainActivity.java)
  at com.domain.bla.MainActivity.onCreate (MainActivity.java)
  at android.app.Activity.performCreate (Activity.java:8282)
  at android.app.Activity.performCreate (Activity.java:8262)
  at android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1329)
  at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:4005)
  at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:4197)
  at android.app.servertransaction.LaunchActivityItem.execute (LaunchActivityItem.java:103)
  at android.app.servertransaction.TransactionExecutor.executeCallbacks (TransactionExecutor.java:135)
  at android.app.servertransaction.TransactionExecutor.execute (TransactionExecutor.java:95)
  at android.app.ActivityThread$H.handleMessage (ActivityThread.java:2434)
  at android.os.Handler.dispatchMessage (Handler.java:106)
  at android.os.Looper.loopOnce (Looper.java:226)
  at android.os.Looper.loop (Looper.java:313)
  at android.app.ActivityThread.main (ActivityThread.java:8633)
  at java.lang.reflect.Method.invoke (Native Method)
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:567)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1133)

I don't have the function i() in MainActivity or anywhere in the app, maybe in one of the libraries but not from me.

I have testing devices with android 11 and 12 but can't reproduce this error, everything works as it should on those.

Posting the whole MainActivity would be way too much sicne it's over 1300 lines.

This is the setNavi function:

private fun setNavi(gal: String){

    val toggle = ActionBarDrawerToggle(
        this, binding.drawerLayout, binding.contentMain.toolbar, 0, 0
    )

    binding.drawerLayout.addDrawerListener(toggle)
    toggle.syncState()
    binding.navView.setNavigationItemSelectedListener(this)

    if(gal == "latest"){
        binding.navView.setCheckedItem(R.id.nav_latest)
    }else{
        binding.navView.setCheckedItem(R.id.nav_top)
    }

    binding.navView.itemIconTintList = null

    binding.contentMain.btnOpenSearch.setOnClickListener {
        binding.drawerLayout.closeDrawer(GravityCompat.START, true)
        val i = Intent(this@MainActivity, SearchInput::class.java)
        this.startActivity(i)
    }

    val headerLayout = binding.navView.getHeaderView(0) // to set stuff in menu
    //headerLayout.btnUpload.setOnClickListener {

    val btnUpload: ConstraintLayout = headerLayout.findViewById(R.id.btnUpload)
    btnUpload.setOnClickListener {
        if(prefs.getLong("userid", 0) == 0.toLong()){
            val i = Intent(this, Login::class.java)
            this.startActivity(i)

        }else{
            binding.drawerLayout.closeDrawer(GravityCompat.START, true)

            val i = Intent(this, Upload::class.java)
            startActivity(i)
        }
    }

    setHeader()
}

maybe the problem is in there?


问:
C# For Loop with LIST using LINQ
I'm using LINQ and returning a list to my Business Logic Layer. I'mtrying to change one of the values in the list (changing the 'star' rating to an image with the number of stars).

Although the counter (i) appears to be working, the FOR loop is not working correctly.  The first time through it stops at the correct IF but then it pops out at the ELSE statement for everything and all values end up with "star0.png."  It appears as though I'm not cycling through the list???  Thanks in advance!

```<code>    for (int i = 0; i < ReviewList.Count; i++)
    {
        string serviceCode = ReviewList[i].SERVICE.SERVICE_DESC;
        if (serviceCode == "*")
        {
            ReviewList[i].SERVICE.SERVICE_DESC = "star1.png";
        }
        else if (serviceCode == "**")
        {
            ReviewList[i].SERVICE.SERVICE_DESC = "star2.png";
        }
        else if (serviceCode == "***")
        {
            ReviewList[i].SERVICE.SERVICE_DESC = "star3.png";
        }
        else if (serviceCode == "****")
        {
            ReviewList[i].SERVICE.SERVICE_DESC = "star4.png";
        }
        else
        {
            ReviewList[i].SERVICE.SERVICE_DESC = "star0.png";
        }
    }
</code>```

答:
If all values end up at star0.png, then you are cycling through the list. The fact that the else statement is the only code being executed for each element suggests a logical error -- did you perhaps mean to do something like this?

```<code>string serviceCode = ReviewList[i].SERVICE.SERVICE_CODE;
</code>```

ContentLicense: CC BY-SA 3.0

Title: C# For Loop with LIST using LINQ

Body:
I'm using LINQ and returning a list to my Business Logic Layer. I'mtrying to change one of the values in the list (changing the 'star' rating to an image with the number of stars).

Although the counter (i) appears to be working, the FOR loop is not working correctly.  The first time through it stops at the correct IF but then it pops out at the ELSE statement for everything and all values end up with "star0.png."  It appears as though I'm not cycling through the list???  Thanks in advance!

    for (int i = 0; i < ReviewList.Count; i++)
    {
        string serviceCode = ReviewList[i].SERVICE.SERVICE_DESC;
        if (serviceCode == "*")
        {
            ReviewList[i].SERVICE.SERVICE_DESC = "star1.png";
        }
        else if (serviceCode == "**")
        {
            ReviewList[i].SERVICE.SERVICE_DESC = "star2.png";
        }
        else if (serviceCode == "***")
        {
            ReviewList[i].SERVICE.SERVICE_DESC = "star3.png";
        }
        else if (serviceCode == "****")
        {
            ReviewList[i].SERVICE.SERVICE_DESC = "star4.png";
        }
        else
        {
            ReviewList[i].SERVICE.SERVICE_DESC = "star0.png";
        }
    }

Body:
If all values end up at star0.png, then you are cycling through the list. The fact that the else statement is the only code being executed for each element suggests a logical error -- did you perhaps mean to do something like this?

string serviceCode = ReviewList[i].SERVICE.SERVICE_CODE;


问:
Jenkins Plugin failure error
I'm getting failure message on adding Plugin , will anybody tell me why I'm getting this error:</p>

```<code>hudson.util.IOException2: Failed to download from http://updates.jenkins-ci.org/download/plugins/credentials/2.1.4/credentials.hpi (redirected to: http://ftp.tsukuba.wide.ad.jp/software/jenkins/plugins/credentials/2.1.4/credentials.hpi)
    at hudson.model.UpdateCenter$UpdateCenterConfiguration.download(UpdateCenter.java:822)
    at hudson.model.UpdateCenter$DownloadJob._run(UpdateCenter.java:1184)
    at hudson.model.UpdateCenter$InstallationJob._run(UpdateCenter.java:1365)
    at hudson.model.UpdateCenter$DownloadJob.run(UpdateCenter.java:1162)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at hudson.remoting.AtmostOneThreadExecutor$Worker.run(AtmostOneThreadExecutor.java:110)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.IOException: Inconsistent file length: expected 928684 but only got 884511
    at hudson.model.UpdateCenter$UpdateCenterConfiguration.download(UpdateCenter.java:805)
    ... 7 more
</code>```

答:
There is a bug in JDK 11: https://bugs.openjdk.java.net/browse/JDK-8213202

I came across the same issue.

After which, I uninstalled it and installed it back with JDK8 u322-b06 (https://adoptium.net/releases.html?variant=openjdk8) and the issue was fixed.

Alternatively, you can switch the Java version in jenkins.xml as:

  <executable>C:\Java\jdk8u322-b06\\bin\java.exe</executable>
```

Title: Jenkins Plugin failure error

Body:
I'm getting failure message on adding Plugin , will anybody tell me why I'm getting this error:

hudson.util.IOException2: Failed to download from http://updates.jenkins-ci.org/download/plugins/credentials/2.1.4/credentials.hpi (redirected to: http://ftp.tsukuba.wide.ad.jp/software/jenkins/plugins/credentials/2.1.4/credentials.hpi)
    at hudson.model.UpdateCenter$UpdateCenterConfiguration.download(UpdateCenter.java:822)
    at hudson.model.UpdateCenter$DownloadJob._run(UpdateCenter.java:1184)
    at hudson.model.UpdateCenter$InstallationJob._run(UpdateCenter.java:1365)
    at hudson.model.UpdateCenter$DownloadJob.run(UpdateCenter.java:1162)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at hudson.remoting.AtmostOneThreadExecutor$Worker.run(AtmostOneThreadExecutor.java:110)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.IOException: Inconsistent file length: expected 928684 but only got 884511
    at hudson.model.UpdateCenter$UpdateCenterConfiguration.download(UpdateCenter.java:805)
    ... 7 more


问:
Symfony Ajax Form - Choice Type Options depend on other unmapped Choice Type Options
i try to keep it short.

I want to change the possible choice opotion of my ChoiceType(N.2), depending on another ChoiceType(N.1).

My ChoiceType(N.1) is unmapped and has the Option "Yes" or "No"

My ChoiceType(N.2) is mapped and filled with categorys out of an database.

The database has the Columns ID(int) | Name(string) |
Revenue(boolean)

So if the user chooce the Option Yes, i want all Categorys in the ChoiceType (N.2) with the revenue of 1(true). If the user choose No, i want to display all choice options with the categorys with the revenue of 0 (boolean)

I've done a lot of research but I just can't get it to work.
I mainly focus on de documentaion https://symfony.com/doc/current/form/dynamic_form_modification.html, but there both ChoiceTyps are Entitys, not just one. I should almost have it, but I don't know what's missing.
Here are the important parts of my code:

EntryForm:

```<code>   ->add('choice', ChoiceType::class, [
            'choices'  => [
                'No' => 0,
                'Yes' => 1,
            ],
            'data'=>0,
            'mapped' => false,
        ])

        $formModifier = function (FormInterface $form, $choice) {

            $revenue = $choice;
            $user = $this->security->getUser();
            $userId = $user->getId();

            $form->add('category', EntityType::class,[
                'class'=>Category::class,
                'query_builder' => function(CategoryRepository $repository) use($userId,
                         $revenue) {
                    $qb = $repository->createQueryBuilder('u');

                    return $qb

                        ->where('u.user=' .$userId, 'u.revenue='.   $revenue );
                }, ]);

        };

        $builder->addEventListener(
            FormEvents::PRE_SET_DATA,
            function (FormEvent $event) use ($formModifier) {

                $data = $event->getData();
                $form = $event->getForm();
                $choice = $form->get('choice')->getData();

                $formModifier($event->getForm(),  $choice);
            }
        );

        $builder->get('choice')->addEventListener(
            FormEvents::POST_SUBMIT,
            function (FormEvent $event) use ($formModifier) {

                $choice = $event->getForm()->getData();

                $formModifier($event->getForm()->getParent(), $choice);
            }
        );
</code>```

AJAX

```<code>var $choice = $('#entry_choice');

    $choice.change(function() {

        var $form = $(this).closest('form');
        var data = {};

        var choice = $('#entry_choice').val();

         data= choice;
           data[$choice] = 1;

        $.ajax({
            url: $form.attr('action'),
            type: $form.attr('method'),
           data : data,

            complete: function(html) {
                console.log( data);

              $('#entry_category').replaceWith(

      $(html.responseText).find('#entry_category'));

            }
        });
    });
</code>```

I think I don't understand the data passed from ajax correctly.
I am trying to achieve the following:  If the user change the ChoiceType from No to Yes, pass the variable $choice with the value 1 to the form. In the form at the  $formModifier it should change the variable $revenue to $choice, so that i can filter with my query_builder through all categorys where revenue is 1.  ('u.revenue='.   $revenue)

Kind regards Magnus

答:
Instead of data[$choice] = 1; try data[$choice.attr('name')] = 1;

Symfony expects the data to be sent from the front end in a specific format.

If you inspect the source of the generated html form, you will see that format.

Body:
i try to keep it short.

I want to change the possible choice opotion of my ChoiceType(N.2), depending on another ChoiceType(N.1).

My ChoiceType(N.1) is unmapped and has the Option "Yes" or "No"

My ChoiceType(N.2) is mapped and filled with categorys out of an database.

The database has the Columns ID(int) | Name(string) |
Revenue(boolean)

So if the user chooce the Option Yes, i want all Categorys in the ChoiceType (N.2) with the revenue of 1(true). If the user choose No, i want to display all choice options with the categorys with the revenue of 0 (boolean)

I've done a lot of research but I just can't get it to work.
I mainly focus on de documentaion https://symfony.com/doc/current/form/dynamic_form_modification.html, but there both ChoiceTyps are Entitys, not just one. I should almost have it, but I don't know what's missing.
Here are the important parts of my code:

EntryForm:

   ->add('choice', ChoiceType::class, [
            'choices'  => [
                'No' => 0,
                'Yes' => 1,
            ],
            'data'=>0,
            'mapped' => false,
        ])

        $formModifier = function (FormInterface $form, $choice) {

            $revenue = $choice;
            $user = $this->security->getUser();
            $userId = $user->getId();

            $form->add('category', EntityType::class,[
                'class'=>Category::class,
                'query_builder' => function(CategoryRepository $repository) use($userId,
                         $revenue) {
                    $qb = $repository->createQueryBuilder('u');

                    return $qb

                        ->where('u.user=' .$userId, 'u.revenue='.   $revenue );
                }, ]);

        };

        $builder->addEventListener(
            FormEvents::PRE_SET_DATA,
            function (FormEvent $event) use ($formModifier) {

                $data = $event->getData();
                $form = $event->getForm();
                $choice = $form->get('choice')->getData();

                $formModifier($event->getForm(),  $choice);
            }
        );

        $builder->get('choice')->addEventListener(
            FormEvents::POST_SUBMIT,
            function (FormEvent $event) use ($formModifier) {

                $choice = $event->getForm()->getData();

                $formModifier($event->getForm()->getParent(), $choice);
            }
        );

AJAX

var $choice = $('#entry_choice');

    $choice.change(function() {

        var $form = $(this).closest('form');
        var data = {};

        var choice = $('#entry_choice').val();

         data= choice;
           data[$choice] = 1;

        $.ajax({
            url: $form.attr('action'),
            type: $form.attr('method'),
           data : data,

            complete: function(html) {
                console.log( data);

              $('#entry_category').replaceWith(

      $(html.responseText).find('#entry_category'));

            }
        });
    });

I think I don't understand the data passed from ajax correctly.
I am trying to achieve the following:  If the user change the ChoiceType from No to Yes, pass the variable $choice with the value 1 to the form. In the form at the  $formModifier it should change the variable $revenue to $choice, so that i can filter with my query_builder through all categorys where revenue is 1.  ('u.revenue='.   $revenue)

Kind regards Magnus


问:
Get specific value from json object
I have a json file with the following structure:

```<code>"edition": 979,
  "attributes": [
    {
      "trait_type": "Background",
      "value": "Gray"
    },
    {
      "trait_type": "Base",
      "value": "Guy"
    },
    {
      "trait_type": "Body",
      "value": "FormalBlack"
    },
    {
      "trait_type": "Hand",
      "value": "None"
    },
    {
      "trait_type": "Head",
      "value": "Astronaut"
    },
    {
      "trait_type": "Pet",
      "value": "OrangeCat"
    }
  ],
  "properties": {
    "files": [
      {
        "uri": "979.png",
        "type": "image/png"
      }
    ],
</code>```

How can I get get the data of 'value' in 'attributes'?
I can get the whole 'attributes' object but can't get to specific values inside, for example

```<code>f = open('./metadata/0.json')

xmp = json.load(f)

print (xmp['attributes'])
</code>```

returns

```<code>[{'trait_type': 'Background', 'value': 'Purple'}, {'trait_type': 'Base', 'value': 'RedGuy'}, {'trait_type': 'Body', 'value': 'Formal'}, {'trait_type': 'Hand', 'value': 'FlamingSword'}, {'trait_type': 'Head', 'value': 'RedHead'}, {'trait_type': 'Pet', 'value': 'None'}]
</code>```

but I only need the value portion. I can run another method to search through it to get what I want but I imagine there is a much easier way.

答:
Lets say your json variable name is 'data'

You can reach with 2 way.

first one with for loop

```<code>for items in data["attributes"]:
   print(data['value'])
</code>```

second one with direct access

```<code>print(test['attributes'][0]['value'])
</code>```

with direct access.

Thanks

Title: Get specific value from json object

Body:
I have a json file with the following structure:

"edition": 979,
  "attributes": [
    {
      "trait_type": "Background",
      "value": "Gray"
    },
    {
      "trait_type": "Base",
      "value": "Guy"
    },
    {
      "trait_type": "Body",
      "value": "FormalBlack"
    },
    {
      "trait_type": "Hand",
      "value": "None"
    },
    {
      "trait_type": "Head",
      "value": "Astronaut"
    },
    {
      "trait_type": "Pet",
      "value": "OrangeCat"
    }
  ],
  "properties": {
    "files": [
      {
        "uri": "979.png",
        "type": "image/png"
      }
    ],

How can I get get the data of 'value' in 'attributes'?
I can get the whole 'attributes' object but can't get to specific values inside, for example

f = open('./metadata/0.json')

xmp = json.load(f)

print (xmp['attributes'])

returns

[{'trait_type': 'Background', 'value': 'Purple'}, {'trait_type': 'Base', 'value': 'RedGuy'}, {'trait_type': 'Body', 'value': 'Formal'}, {'trait_type': 'Hand', 'value': 'FlamingSword'}, {'trait_type': 'Head', 'value': 'RedHead'}, {'trait_type': 'Pet', 'value': 'None'}]

but I only need the value portion. I can run another method to search through it to get what I want but I imagine there is a much easier way.

Body:
Lets say your json variable name is 'data'

You can reach with 2 way.

first one with for loop

for items in data["attributes"]:
   print(data['value'])

second one with direct access

print(test['attributes'][0]['value'])

with direct access.

Thanks


问:
How to replace value in a dataframe and convert it to a list of dictionary in python pandas
I have a data frame that is created after a query is executed. Call it df1.

```<code> customerID flag
0        123   No
</code>```

Now, I have another list of dictionary like below:

```<code>list2 = [{"customerID": "123", "response": "yes", "flag": ""}]
</code>```

Now, I want to replace the value of the flag with the values of the flag from df1 for that specific customer. So, I converted this list to a data frame say df2 and tried doing it but it didn't give any errors but didn't give my expected output.

Attempt:

```<code>df2.loc[df2['customerID'].isin(df1.to_dict().keys()), 'flag'] = df2['customerID'].map(df1.to_dict())
</code>```

Expected output:

```<code>[{"customerID": "123", "response": "yes", "flag": "No"}]
</code>```

I am looking to replace it in df2 itself. Later on, I can do .to_dict(orient="records") to get the format I need.

答:
I solved it using the below way:</p>
```<code>df1 = df1.set_index('customerID')
df2 = df2.set_index('customerID')
df2.update(df1)
df2.reset_index(inplace=True)
</code>```

Body:
I have a data frame that is created after a query is executed. Call it df1.

 customerID flag
0        123   No

Now, I have another list of dictionary like below:

list2 = [{"customerID": "123", "response": "yes", "flag": ""}]

Now, I want to replace the value of the flag with the values of the flag from df1 for that specific customer. So, I converted this list to a data frame say df2 and tried doing it but it didn't give any errors but didn't give my expected output.

Attempt:

df2.loc[df2['customerID'].isin(df1.to_dict().keys()), 'flag'] = df2['customerID'].map(df1.to_dict())

Expected output:

[{"customerID": "123", "response": "yes", "flag": "No"}]

I am looking to replace it in df2 itself. Later on, I can do .to_dict(orient="records") to get the format I need.

Body:
I solved it using the below way:

df1 = df1.set_index('customerID')
df2 = df2.set_index('customerID')
df2.update(df1)
df2.reset_index(inplace=True)


问:
Troubleshoot failed cron not sending emails
Here is the server info from lsb_release -a

In our crontab, below the comments and above the cron commands we have MAILTO=myemail@gmail.com, however no emails are being sent to myemail@gmail.com. I'm not sure if the server has sendgrid or any other emailing tools installed, or if they are needed. Our cron logs all currently get sent to a file at /var/mail/myusername, and I can hop in and see them with vim /var/mail/myusername. How can I troubleshoot this further?

答: Type mailx or install the package. If you need them to go to Google, then you need to install and configure a mta package such as postfix or exim. You also have a high enough rating to know that you do not post images where plain text will do.


问:
How to turn off the ringtone programmatically?
I want to turn off the ringtone. Otherwise, at least to decrease the sound of the ring tone and to stop the vibration of the device.</p>

答: Unfortunately that would be at the user's decision, not the developer's. Another example is screen brightness.</p>


问:
Remove Characters After Number
I have a string from a file which I need to remove all the characters after the substring "c1525". Can regex be used for this? The pattern I am seeing is that all my strings have a "c" then 4 digits (although I have seen more than 4 digits, so need to take that into consideration).

```<code>d098746532d1234567c1525qFPXplFSm-FS8575664637338586224hKwHFmFSRRnm0Uc006566
</code>```

expected:

```<code>d098746532d1234567c1525
</code>```

Title: Remove Characters After Number

Body:
I have a string from a file which I need to remove all the characters after the substring "c1525". Can regex be used for this? The pattern I am seeing is that all my strings have a "c" then 4 digits (although I have seen more than 4 digits, so need to take that into consideration).

d098746532d1234567c1525qFPXplFSm-FS8575664637338586224hKwHFmFSRRnm0Uc006566

expected:

d098746532d1234567c1525

Body:
s = 'd098746532d1234567c1525qFPXplFSm-FS8575664637338586224hKwHFmFSRRnm0Uc006566'
s[:s.find('c1525')+len('c1525')]

Output:
d098746532d1234567c1525


问:
Display print messages in console PyInstaller
I'm using PyInstaller to convert my Python file to .exe; however, I see that upon running the executable file, I don't see any print messages in the terminal which I use for my reference - it's just blank (no print messages).

Command I used: pyinstaller --onefile -w myfile.py

I use Selenium module in my Python file, which uses chromedriver.exe, so after running the generated .exe file, this is what it shows:

Code:

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.service import Service
from selenium.common.exceptions import TimeoutException

from time import sleep
import random

driver = webdriver.Chrome()

wait = WebDriverWait(driver, 20)

print("Opened the browser")
</code>```

Pictures:

I need to see the print messages. Tried searching for answers but couldn't find any solutions!

How do I resolve this?

答:
If you run your .exe from a terminal like PowerShell it will probably show the output you're looking for. The window in the screenshot looks like it is coming from the Selenium driver.

If you want this to work when double-clicking on the .exe, rebuild without the -w flag:

-w, --windowed, --noconsole

Windows and Mac OS X: do not provide a console window for standard i/o. On Mac OS this also triggers building a Mac OS .app bundle. On Windows this option is automatically set if the first script is a ‘.pyw’ file. This option is ignored on *NIX systems.

Body:
I'm using PyInstaller to convert my Python file to .exe; however, I see that upon running the executable file, I don't see any print messages in the terminal which I use for my reference - it's just blank (no print messages).

Command I used: pyinstaller --onefile -w myfile.py

I use Selenium module in my Python file, which uses chromedriver.exe, so after running the generated .exe file, this is what it shows:

Code:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.service import Service
from selenium.common.exceptions import TimeoutException

from time import sleep
import random

driver = webdriver.Chrome()

wait = WebDriverWait(driver, 20)

print("Opened the browser")

Pictures:

I need to see the print messages. Tried searching for answers but couldn't find any solutions!

How do I resolve this?


问:
Cannot use final fields in Room entity
When using an entity using Room library in java, I want to have few final fields (since i don't want to have setters) and few non-final fields. I have created a similar class called Record, following the official docs.

```<code>public class Record {

    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "Id")
    private final long id;

    @ColumnInfo(name = "CreatedDate")
    private final long createdDate;

    @ColumnInfo(name = "LastModifiedDate")
    private long lastModifiedDate;

    public Record(long id, long createdDate) {
        this.id = id;
        this.createdDate = createdDate;
        this.lastModifiedDate = createdDate;
    }

    public long getId() {
        return id;
    }

    public long getCreatedDate() {
        return createdDate;
    }

    public long getLastModifiedDate() {
        return lastModifiedDate;
    }

    public void setLastModifiedDate(long unixTime) {
        lastModifiedDate = unixTime;
    }

    public void notifyRecordUpdate() {
        setLastModifiedDate(System.currentTimeMillis());
    }
}
</code>```

Note: I haven't marked this an entity because this is a base class for other entities.

But, the compiler complains that it cannot find setters for field id and createdDate.
It gives the following errors:

```<code>Record.java:10: error: Cannot find setter for field.
    private final long id;
Record.java:13: error: Cannot find setter for field.
    private final long createdDate;
</code>```

As per the docs above:

Constructor does not have to receive all fields as parameters but if a field is not passed into the constructor, it should either be public or have a public setter

the compiler should be able to find the the only constructor for final fields and use the setter for the third non-final field?

Am I missing something here?

答:
I finally figured out the issue with my code. Although it's an error made by me, I think this is such a common design pattern we use everyday in OOPS world  that many might make a similar mistake, hence posting the correct implementation.

Since I was extending the Record class, I need to define a constructor in the sub class that takes in all the required parameters.

Here's a small example as to what I was doing (Incorrect entity implementation):

```<code>@Entity(tableName = "Items")
public class Item extends Record {

    @ColumnInfo(name = "Something")
    private final String something;

    public Item(@NonNull String something) {
        super(0, System.currentTimeMillis());
        this.something = something;
    }
}
</code>```

This is a valid sub-class and java compiler won't complain, however room simply cannot find a valid constructor with all the three required fields (id, createdDate, something) which it needs to initialise the object Item from the database.

Instead this is how we need to define any subclass.

```<code>@Entity(tableName = "Items")
public class Item extends Record {

    @ColumnInfo(name = "Something")
    private final String something;

    public Item(long id, long createdDate, long @NonNull String something) {
        super(id, createdDate);
        this.something = something;
    }
}
</code>```

This is such a foolish mistake I made that I might be deleting the question altogether in the future if it doen't help anyone.

Title: Cannot use final fields in Room entity

Body:
When using an entity using Room library in java, I want to have few final fields (since i don't want to have setters) and few non-final fields. I have created a similar class called Record, following the official docs.

public class Record {

    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "Id")
    private final long id;

    @ColumnInfo(name = "CreatedDate")
    private final long createdDate;

    @ColumnInfo(name = "LastModifiedDate")
    private long lastModifiedDate;

    public Record(long id, long createdDate) {
        this.id = id;
        this.createdDate = createdDate;
        this.lastModifiedDate = createdDate;
    }

    public long getId() {
        return id;
    }

    public long getCreatedDate() {
        return createdDate;
    }

    public long getLastModifiedDate() {
        return lastModifiedDate;
    }

    public void setLastModifiedDate(long unixTime) {
        lastModifiedDate = unixTime;
    }

    public void notifyRecordUpdate() {
        setLastModifiedDate(System.currentTimeMillis());
    }
}

Note: I haven't marked this an entity because this is a base class for other entities.

But, the compiler complains that it cannot find setters for field id and createdDate.
It gives the following errors:

Record.java:10: error: Cannot find setter for field.
    private final long id;
Record.java:13: error: Cannot find setter for field.
    private final long createdDate;

As per the docs above:

Constructor does not have to receive all fields as parameters but if a field is not passed into the constructor, it should either be public or have a public setter

the compiler should be able to find the the only constructor for final fields and use the setter for the third non-final field?

Am I missing something here?

Body:
I finally figured out the issue with my code. Although it's an error made by me, I think this is such a common design pattern we use everyday in OOPS world  that many might make a similar mistake, hence posting the correct implementation.

Since I was extending the Record class, I need to define a constructor in the sub class that takes in all the required parameters.

Here's a small example as to what I was doing (Incorrect entity implementation):

@Entity(tableName = "Items")
public class Item extends Record {

    @ColumnInfo(name = "Something")
    private final String something;

    public Item(@NonNull String something) {
        super(0, System.currentTimeMillis());
        this.something = something;
    }
}

This is a valid sub-class and java compiler won't complain, however room simply cannot find a valid constructor with all the three required fields (id, createdDate, something) which it needs to initialise the object Item from the database.

Instead this is how we need to define any subclass.

@Entity(tableName = "Items")
public class Item extends Record {

    @ColumnInfo(name = "Something")
    private final String something;

    public Item(long id, long createdDate, long @NonNull String something) {
        super(id, createdDate);
        this.something = something;
    }
}

This is such a foolish mistake I made that I might be deleting the question altogether in the future if it doen't help anyone.


问:
I'm trying to create an event but I get a NullReferenceException
I want to create an event in C# but I'm getting this error:

An unhandled exception of type 'System.NullReferenceException' occurred in shei graii.exe

Additional information: Object reference not set to an instance of an object.

Server code:

```<code>public class mobile
{
    public delegate void chargeEvent();
    public event chargeEvent sampleEvent;

    private byte _charge;

    public byte charge
    {
        set
        {
            _charge = value;
            if (_charge <= 15)
            {
                sampleEvent(); // the error line
            }
        }
    }
}
</code>```

Client code:

```<code>mobile mob = new mobile();

mob.charge = 14;

mob.sampleEvent += new mobile.chargeEvent(input);
</code>```

Input code:

```<code>public void input()
{
    MessageBox.Show("battery low");
}
</code>```

答:
You get the NullReference error because you try to invoke the event before setting it. So try this instead:

```<code>mobile mob = new mobile();

mob.sampleEvent += new mobile.chargeEvent(input);

mob.charge = 14;
</code>```

This is as far as we can go with the limited code you provided.

Body:
I want to create an event in C# but I'm getting this error:

An unhandled exception of type 'System.NullReferenceException' occurred in shei graii.exe

Additional information: Object reference not set to an instance of an object.

Server code:

public class mobile
{
    public delegate void chargeEvent();
    public event chargeEvent sampleEvent;

    private byte _charge;

    public byte charge
    {
        set
        {
            _charge = value;
            if (_charge <= 15)
            {
                sampleEvent(); // the error line
            }
        }
    }
}

Client code:

mobile mob = new mobile();

mob.charge = 14;

mob.sampleEvent += new mobile.chargeEvent(input);

Input code:

public void input()
{
    MessageBox.Show("battery low");
}

Body:
You get the NullReference error because you try to invoke the event before setting it. So try this instead:

mobile mob = new mobile();

mob.sampleEvent += new mobile.chargeEvent(input);

mob.charge = 14;

This is as far as we can go with the limited code you provided.


问:
Getting this SQL Statement right with aliases
what i basically want to do is: compute the difference of to attributes and then get the row with the biggest difference.

So, here is what i tried:

```<code>SELECT caller_aor, (end_time - start_time) as duration
    FROM cdrs
    GROUP BY caller_aor
    HAVING duration = (SELECT MAX(end_time - start_time) FROM cdrs);
</code>```

duration in the HAVING clause gives an error but i cant figure out what i have to do there.

Help is appreciated.

答:
You don't want GROUP BY and HAVING (they are only used when aggregating columns).

You want a simple WHERE:

```<code>SELECT caller_aor, (end_time - start_time) as duration
FROM cdrs
WHERE (end_time - start_time) = (SELECT MAX(end_time - start_time) FROM cdrs);
</code>```

Body:
what i basically want to do is: compute the difference of to attributes and then get the row with the biggest difference.

So, here is what i tried:

SELECT caller_aor, (end_time - start_time) as duration
    FROM cdrs
    GROUP BY caller_aor
    HAVING duration = (SELECT MAX(end_time - start_time) FROM cdrs);

duration in the HAVING clause gives an error but i cant figure out what i have to do there.

Help is appreciated.

Body:
You don't want GROUP BY and HAVING (they are only used when aggregating columns).

You want a simple WHERE:

SELECT caller_aor, (end_time - start_time) as duration
FROM cdrs
WHERE (end_time - start_time) = (SELECT MAX(end_time - start_time) FROM cdrs);


问:
Isn't findAll() iterator inefficient to assert an unprecedented case in the Database?
I am a newbie constructing persistence APIs with Spring Boot, so I came about this doubt. I don't want the user to be able to register two different Accounts with the same Email. But I also don't want to use Email as primary key in the repo. So, I think the logic is quite self-explanatory.

```<code>private static boolean isRegisteredEmail(String email, AccountRepository accountRepository) {
    for ( Account account : accountRepository.findAll() ) {
        if ( account.getEmail().equals(email) ) {
            return true;
        }
    }
    return false;
}
</code>```

This works, but I start to wonder: if you get a real-case situation, like Facebook's DB in which you have almost 3 billion registers, how do you deal with this scenario? Am I overconcerning, or there's really no chance this can keep being done efficiently?

答:
you don't need to use email as primary key, you can still search for existing users with given email address using either HQL/SQL @Query in your spring data @Repository annotated interface or by composing a method name such as findUserByEmail without writing query (if entity is named user and there is a field email spring data will fetch the data from db for you).

It's much more efficient to select 1 record and not transfer through hundreds/thousands of users every time someone needs to create a new account.

Body:
I am a newbie constructing persistence APIs with Spring Boot, so I came about this doubt. I don't want the user to be able to register two different Accounts with the same Email. But I also don't want to use Email as primary key in the repo. So, I think the logic is quite self-explanatory.

private static boolean isRegisteredEmail(String email, AccountRepository accountRepository) {
    for ( Account account : accountRepository.findAll() ) {
        if ( account.getEmail().equals(email) ) {
            return true;
        }
    }
    return false;
}

This works, but I start to wonder: if you get a real-case situation, like Facebook's DB in which you have almost 3 billion registers, how do you deal with this scenario? Am I overconcerning, or there's really no chance this can keep being done efficiently?


答:
You could set_index to "customerID", convert the DataFrame to a dictionary. Then iterate over list2 and modify flag value of the list where the "customerID"s match:

```<code>df_to_dict = df.astype(str).set_index('customerID').to_dict('index')
for d in list2:
    d['flag'] = df_to_dict.get(d['customerID'], {}).get('flag', d['flag'])
</code>```

Output:

```<code>[{'customerID': '123', 'response': 'yes', 'flag': 'No'}]
</code>```

Title: How to replace value in a dataframe and convert it to a list of dictionary in python pandas

Body:
You could set_index to "customerID", convert the DataFrame to a dictionary. Then iterate over list2 and modify flag value of the list where the "customerID"s match:

df_to_dict = df.astype(str).set_index('customerID').to_dict('index')
for d in list2:
    d['flag'] = df_to_dict.get(d['customerID'], {}).get('flag', d['flag'])

Output:

[{'customerID': '123', 'response': 'yes', 'flag': 'No'}]


问:
Can we create an anonymous inner class from a concrete class?
There is something surprising in the following code. The ListCell class is not abstract, but we were able to create an anonymous class from it and override its method! How is this possible?

```<code>ListCell<TodoItem> listCell = new ListCell<>() {
    @Override
    public void updateIndex(int i) {
        super.updateIndex(i);
    }
};
</code>```

答:
The concept of anonymous classes (cf. JLS, §15.9.5) is simply not related/restricted to abstract classes.

new ListCell<>() {} creates an instance of a subclass (with a synthetic name) of ListCell. Subclassing is possible unless the parent class is final. Subclasses can override methods from the parent class unless they're final.

Body:
There is something surprising in the following code. The ListCell class is not abstract, but we were able to create an anonymous class from it and override its method! How is this possible?

ListCell<TodoItem> listCell = new ListCell<>() {
    @Override
    public void updateIndex(int i) {
        super.updateIndex(i);
    }
};


问:
Java MongoDB – Find objects that contain a certain string returning no results
I'm using java's mongodb driver and trying to get all items where the "text" contains the term "Example". However, it just returns no items, no matter what I try. Even using "a" instead of "Example" (which 100% is included in most results) returns 0.

What am I doing wrong here?

```<code>db.getCollection("Items").find(in("text", "Example"))
</code>```

Also tried passing a List instead of "Example", which also didn't work.

Any suggestions?

Thanks!

答:
Using collections a solution could look like this one:

```<code>db.getCollection("Items").find(Filters.in("text", ".*Example.*"));
</code>```

You need a regex because (from the JavaDoc) in:

```<code>Creates a filter that matches all documents where the value of a field **equals** any value in the list of specified values.
</code>```

Body:
I'm using java's mongodb driver and trying to get all items where the "text" contains the term "Example". However, it just returns no items, no matter what I try. Even using "a" instead of "Example" (which 100% is included in most results) returns 0.

What am I doing wrong here?

db.getCollection("Items").find(in("text", "Example"))

Also tried passing a List instead of "Example", which also didn't work.

Any suggestions?

Thanks!

Body:
Using collections a solution could look like this one:

db.getCollection("Items").find(Filters.in("text", ".*Example.*"));

You need a regex because (from the JavaDoc) in:

Creates a filter that matches all documents where the value of a field **equals** any value in the list of specified values.


问:
Filtering serial data for logarithmic functions
The purpose of my code is import serial data for logathmic regression on live data. At the current moment, all my data is filtered out instead of just the points (x,y) where y<0. I'm learning python and this is my first project, Yaa :(

```<code>import serial
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from scipy import stats

#initialize serial port
ser = serial.Serial()
ser.port = '/dev/cu.usbmodem14101' #Arduino serial port
ser.baudrate = 9600
ser.timeout = 10 #specify timeout when using readline()
ser.open()
if ser.is_open==True:
    print("\nAll right, serial port now open. Configuration:\n")
    print(ser, "\n") #print serial parameters

fig1 = plt.figure(figsize=(10,7))
ax1 = fig1.add_subplot(2, 1, 1)
xs = [] #store trials here (n)
ys = [] #store relative frequency here

# This function is called periodically from FuncAnimation
def animate(i, xs, ys):

        #Acquire and parse data from serial port
        line=ser.readline()      #ascii
        line_as_list = line.split(b',')
        i = float(line_as_list[0])
        Y = line_as_list[1]
        Y_as_list = Y.split(b'\n')
        Y_float = float(Y_as_list[0])
        cc=str(ser.readline())
        print(cc[2:][:-5])
        xs.append(i)
        ys.append(Y_float)
K = 0
def filter_where(xs, K):
        return xs[np.where(ys > K)]
print(xs)

print(ys)
def filter_where(ys, K):
        return ys[np.where(ys > K)]
print(ys)
#adding regression - commented out b/c it generates error that it is empty

#slope, intercept, r, p, std_err = stats.linregress(xs, ys)

#def myfunc(xs):
#  return slope * xs + intercept

#mymodel = list(map(myfunc, xs))

plt.scatter(xs, ys)
#plt.plot(xs, mymodel)
# Draw x and y lists
ax1.clear()
ax1.plot(xs, ys)

ani = animation.FuncAnimation(fig1, animate, fargs=(xs, ys), interval=10)
plt.show()
</code>```

Edit: I changed the code.  I moved the filter out of the animate part.  And I added the new i and y to xs and ys respectively.  I made it print the serial so you can see that it is getting info.

Here is is sample output

```<code>All right, serial port now open. Configuration:

Serial<id=0x109132c50, open=True>(port='/dev/cu.usbmodem14101', baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=10, xonxoff=False, rtscts=False, dsrdtr=False)

[]
[]
[]
0.30,0.011
0.70,0.011
1.11,0.013
1.51,0.005
1.91,0.006
2.31,0.012
2.71,0.004
3.12,0.005
3.52,0.004
3.92,0.014
4.32,0.005
4.72,-0.001
5.13,0.008
5.53,0.009
5.93,0.010
6.33,0.013
6.73,0.000
7.13,0.004
</code>```

答:
I couldn't get Tempman's more concise solution to work but I got this to work on the same idea.  As you suggested I don't need to filter all the xs and ys in the ainmate, and I don't even need the filters to be defined in the first place.  I have two variables in my serial data that work as a pair (x,y).  If the y is invalid data, then the x is too.  I am filtering it after parsing the serial and before appending it to rest of the data.</p>
```<code>    #Acquire and parse data from serial port
    line=ser.readline()      #ascii
    line_as_list = line.split(b',')
    i = float(line_as_list[0])
    Y = line_as_list[1]
    Y_as_list = Y.split(b'\n')
    Y_float = float(Y_as_list[0])
    if Y_float>0:
            xs.append(i)
            ys.append(Y_float)
</code>```

Body:
The purpose of my code is import serial data for logathmic regression on live data. At the current moment, all my data is filtered out instead of just the points (x,y) where y<0. I'm learning python and this is my first project, Yaa :(

import serial
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from scipy import stats

#initialize serial port
ser = serial.Serial()
ser.port = '/dev/cu.usbmodem14101' #Arduino serial port
ser.baudrate = 9600
ser.timeout = 10 #specify timeout when using readline()
ser.open()
if ser.is_open==True:
    print("\nAll right, serial port now open. Configuration:\n")
    print(ser, "\n") #print serial parameters

fig1 = plt.figure(figsize=(10,7))
ax1 = fig1.add_subplot(2, 1, 1)
xs = [] #store trials here (n)
ys = [] #store relative frequency here

# This function is called periodically from FuncAnimation
def animate(i, xs, ys):

        #Acquire and parse data from serial port
        line=ser.readline()      #ascii
        line_as_list = line.split(b',')
        i = float(line_as_list[0])
        Y = line_as_list[1]
        Y_as_list = Y.split(b'\n')
        Y_float = float(Y_as_list[0])
        cc=str(ser.readline())
        print(cc[2:][:-5])
        xs.append(i)
        ys.append(Y_float)
K = 0
def filter_where(xs, K):
        return xs[np.where(ys > K)]
print(xs)

print(ys)
def filter_where(ys, K):
        return ys[np.where(ys > K)]
print(ys)
#adding regression - commented out b/c it generates error that it is empty

#slope, intercept, r, p, std_err = stats.linregress(xs, ys)

#def myfunc(xs):
#  return slope * xs + intercept

#mymodel = list(map(myfunc, xs))

plt.scatter(xs, ys)
#plt.plot(xs, mymodel)
# Draw x and y lists
ax1.clear()
ax1.plot(xs, ys)

ani = animation.FuncAnimation(fig1, animate, fargs=(xs, ys), interval=10)
plt.show()

Edit: I changed the code.  I moved the filter out of the animate part.  And I added the new i and y to xs and ys respectively.  I made it print the serial so you can see that it is getting info.

Here is is sample output

All right, serial port now open. Configuration:

Serial<id=0x109132c50, open=True>(port='/dev/cu.usbmodem14101', baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=10, xonxoff=False, rtscts=False, dsrdtr=False)

[]
[]
[]
0.30,0.011
0.70,0.011
1.11,0.013
1.51,0.005
1.91,0.006
2.31,0.012
2.71,0.004
3.12,0.005
3.52,0.004
3.92,0.014
4.32,0.005
4.72,-0.001
5.13,0.008
5.53,0.009
5.93,0.010
6.33,0.013
6.73,0.000
7.13,0.004

Body:
I couldn't get Tempman's more concise solution to work but I got this to work on the same idea.  As you suggested I don't need to filter all the xs and ys in the ainmate, and I don't even need the filters to be defined in the first place.  I have two variables in my serial data that work as a pair (x,y).  If the y is invalid data, then the x is too.  I am filtering it after parsing the serial and before appending it to rest of the data.

    #Acquire and parse data from serial port
    line=ser.readline()      #ascii
    line_as_list = line.split(b',')
    i = float(line_as_list[0])
    Y = line_as_list[1]
    Y_as_list = Y.split(b'\n')
    Y_float = float(Y_as_list[0])
    if Y_float>0:
            xs.append(i)
            ys.append(Y_float)


Title: Remove Characters After Number

Body:
>>> txt = "d098746532d1234567c1525qFPXplFSm-FS8575664637338586224hKwHFmFSRRnm0Uc006566"
>>> import re
>>> re.match("[^c]*(c\d+)", txt).group()
'd098746532d1234567c1525'


问:
ASP.NET Web Site + Windows Forms App + WCF Service: Client Credentials
Let's say that I'm considering designing a WCF service whose primary purpose is to provide broad services that can be used by three disparate applications: a public-facing Web site, an internal Windows Forms application, and a wireless mobile device. The purpose of the service is twofold: (1) to consolidate code related to business processes in a central location and (2) to lock down access to the legacy database, finally and once and for all hiding it behind one suite of services.

Currently, each of the three applications has its own persistence and domain layers with slightly different views of the same database. Instead of all three applications talking to the database, they would talk to the WCF service, enabling new features from some clients (the mobile picker can't currently trigger processes to send e-mail, obviously) and centralizing notification systems (instead of a scheduled task polling the database every five minutes for new orders, just ping the overhead paging system when the AcceptNewOrder() service method is invoked by one of these clients). All in all, this sounds pretty sane so far.

In terms of overall design, however, I'm stumped when it comes to security. The Windows Forms application currently just uses Windows principals; employees are stored in Active Directory, and upon application startup, they can login as the current Windows user (in which case no password is required) or they can supply their domain name and password. The mobile client doesn't have any concept of a user; its connection to the database is a hardcoded string. And the Web site has thousands of users stored in the legacy database. So how do I implement the identity model and configure the WCF endpoints to deal with this?

In terms of the Windows Forms application, this is no great issue: the WCF proxy can be initiated once and can hang around in memory, so I only need the client credentials once (and can prompt for them again if the proxy ever faults). The mobile client can just be special cased and use an X509 certificate for authentication against the WCF service. But what do I do about the Web site?

In the Web site's case, anonymous access to some services is allowed. And for the services that require authentication in the hypothetical "Customer" role, I obviously don't want to have to authenticate them on each and every request for two reasons:

I need their username and password each time. Storing this pair of information pretty much anywhere--the session, an encrypted cookie, the moon--seems like a bad idea.

I would have to hit the users table in the database for each request. Ouch.

The only solution that I can come up with is to treat the Web site as a trusted subsystem. The WCF service expects a particular X509 certificate from the Web site. The Web site, using Forms Authentication internally (which invokes an AuthenticateCustomer() method on the service that returns a boolean result), can add an additional claim to the list of credentials, something like "joe@example.com is logged in as a customer." Then somehow a custom IIdentity object and IPrincipal could be constructed on the service with that claim, the WCF service being confident that the Web site has properly authenticated the customer (it will know that the claim hasn't been tampered with, at least, because it'll know the Web site's certificate ahead of time).

With all of that in place, the WCF service code would be able to say things like [PrincipalPermission.Demand(Role=MyRoles.Customer)] or [PrincipalPermission.Demand(Role=MyRoles.Manager)], and the Thread.CurrentPrincipal would have something that represented a user (an e-mail address for a customer or a distinguished name for an employee, both of them useful for logging and auditing).

In other words, two different endpoints would exist for each service: one that accepted well-known client X509 certificates (for the mobile devices and the Web site), and one that accept Windows users (for the employees).

Sorry this is so long. So the question is: Does any of this make sense? Does the proposed solution make sense? And am I making this too complicated?

答: For anonymouse public access use basichttpbinding and also have the following in the web.config file

OwnerDisplayName: Nicholas Piasecki

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: jay


问:
ERROR Installing Pkg.add("IJulia"): no active project
I want to install Julia in my jupyter notebook. I am getting this. I am not able to find what means the reference to 'no active Project'. Any help will be very welcomed. Thanks</p>
```<code>
julia> using Pkg

julia> Pkg.add("IJulia")
ERROR: no active project
Stacktrace:
  [1] pkgerror(msg::String)
    @ Pkg.Types C:\Users\madel\Julia-1.7.2\share\julia\stdlib\v1.7\Pkg\src\Types.jl:68
  [2] find_project_file(env::Nothing)
    @ Pkg.Types C:\Users\madel\Julia-1.7.2\share\julia\stdlib\v1.7\Pkg\src\Types.jl:200
  [3] Pkg.Types.EnvCache(env::Nothing) (repeats 2 times)
    @ Pkg.Types C:\Users\madel\Julia-1.7.2\share\julia\stdlib\v1.7\Pkg\src\Types.jl:319
  [4] Pkg.Types.Context()
    @ Pkg.Types .\util.jl:478
  [5] add(pkgs::Vector{Pkg.Types.PackageSpec}; io::Base.TTY, kwargs::Base.Pairs{Symbol, Union{}, Tuple{}, NamedTuple{(), Tuple{}}})
    @ Pkg.API C:\Users\madel\Julia-1.7.2\share\julia\stdlib\v1.7\Pkg\src\API.jl:145
  [6] add(pkgs::Vector{Pkg.Types.PackageSpec})
    @ Pkg.API C:\Users\madel\Julia-1.7.2\share\julia\stdlib\v1.7\Pkg\src\API.jl:144
  [7] #add#27
    @ C:\Users\madel\Julia-1.7.2\share\julia\stdlib\v1.7\Pkg\src\API.jl:142 [inlined]
  [8] add
    @ C:\Users\madel\Julia-1.7.2\share\julia\stdlib\v1.7\Pkg\src\API.jl:142 [inlined]
  [9] #add#26
    @ C:\Users\madel\Julia-1.7.2\share\julia\stdlib\v1.7\Pkg\src\API.jl:141 [inlined]
 [10] add(pkg::String)
    @ Pkg.API C:\Users\madel\Julia-1.7.2\share\julia\stdlib\v1.7\Pkg\src\API.jl:141
 [11] top-level scope
    @ REPL[36]:1

julia>
</code>```

答:
I tried to add a new environment user path as JULIA_HOME to the following route:
C:\Users\madel\Julia-1.7.2\bin and works now. It seems like I was not pointing the right path.</p>

Body:
I want to install Julia in my jupyter notebook. I am getting this. I am not able to find what means the reference to 'no active Project'. Any help will be very welcomed. Thanks

julia> using Pkg

julia> Pkg.add("IJulia")
ERROR: no active project
Stacktrace:
  [1] pkgerror(msg::String)
    @ Pkg.Types C:\Users\madel\Julia-1.7.2\share\julia\stdlib\v1.7\Pkg\src\Types.jl:68
  [2] find_project_file(env::Nothing)
    @ Pkg.Types C:\Users\madel\Julia-1.7.2\share\julia\stdlib\v1.7\Pkg\src\Types.jl:200
  [3] Pkg.Types.EnvCache(env::Nothing) (repeats 2 times)
    @ Pkg.Types C:\Users\madel\Julia-1.7.2\share\julia\stdlib\v1.7\Pkg\src\Types.jl:319
  [4] Pkg.Types.Context()
    @ Pkg.Types .\util.jl:478
  [5] add(pkgs::Vector{Pkg.Types.PackageSpec}; io::Base.TTY, kwargs::Base.Pairs{Symbol, Union{}, Tuple{}, NamedTuple{(), Tuple{}}})
    @ Pkg.API C:\Users\madel\Julia-1.7.2\share\julia\stdlib\v1.7\Pkg\src\API.jl:145
  [6] add(pkgs::Vector{Pkg.Types.PackageSpec})
    @ Pkg.API C:\Users\madel\Julia-1.7.2\share\julia\stdlib\v1.7\Pkg\src\API.jl:144
  [7] #add#27
    @ C:\Users\madel\Julia-1.7.2\share\julia\stdlib\v1.7\Pkg\src\API.jl:142 [inlined]
  [8] add
    @ C:\Users\madel\Julia-1.7.2\share\julia\stdlib\v1.7\Pkg\src\API.jl:142 [inlined]
  [9] #add#26
    @ C:\Users\madel\Julia-1.7.2\share\julia\stdlib\v1.7\Pkg\src\API.jl:141 [inlined]
 [10] add(pkg::String)
    @ Pkg.API C:\Users\madel\Julia-1.7.2\share\julia\stdlib\v1.7\Pkg\src\API.jl:141
 [11] top-level scope
    @ REPL[36]:1

julia>


问:
SQLSTATE[HY000] [2005] Unknown MySQL server host 'localhost:3306' (2)
currently i am facing above problem in laravel. basically this project is setup on mac OS x and currently i am working on it in Linux. so when i run it is on browser it give me that error. i have also changed the my database details in database file. but now this error comes. so can you please tell me how can i fix it.

Open: /var/www/laravel-projects/wit/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php

```<code>*/
public function createConnection($dsn, array $config, array $options)
{
$username = array_get($config, 'username');
$password = array_get($config, 'password');
return new PDO($dsn, $username, $password, $options);
}
</code>```

Thanks

答:
For those who search similar problem solution in laravel 8.

I had this error

```<code>ERROR 2005 (HY000): Unknown MySQL server host 'mysql' (0)
</code>```

You should check 2 files config/database.php and .env

In my case in .env i changed only db_database username and password

```<code>DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=laravel_app
DB_USERNAME=laravel_db_user
DB_PASSWORD=someP@ssword1234
</code>```

The second line DB_HOST=mysql caused this error, so change it to:

```<code>DB_HOST=localhost
</code>```

And it worked fine.

I run mysql on my macos by this command:

```<code>sudo /usr/local/mysql/support-files/mysql.server start
</code>```

and manage it by phpmyadmin

Body:
currently i am facing above problem in laravel. basically this project is setup on mac OS x and currently i am working on it in Linux. so when i run it is on browser it give me that error. i have also changed the my database details in database file. but now this error comes. so can you please tell me how can i fix it.

Open: /var/www/laravel-projects/wit/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php

*/
public function createConnection($dsn, array $config, array $options)
{
$username = array_get($config, 'username');
$password = array_get($config, 'password');
return new PDO($dsn, $username, $password, $options);
}

Thanks

Body:
For those who search similar problem solution in laravel 8.

I had this error

ERROR 2005 (HY000): Unknown MySQL server host 'mysql' (0)

You should check 2 files config/database.php and .env

In my case in .env i changed only db_database username and password

DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=laravel_app
DB_USERNAME=laravel_db_user
DB_PASSWORD=someP@ssword1234

The second line DB_HOST=mysql caused this error, so change it to:

DB_HOST=localhost

And it worked fine.

I run mysql on my macos by this command:

sudo /usr/local/mysql/support-files/mysql.server start

and manage it by phpmyadmin


问:
"TypeError: <lambda>() takes 1 positional argument but 2 were given" Lambda expression in Python
I write a simple lambda function to generate a random list of booleans with the following code:

```<code>randBinList = lambda n: [random()<0.5 for _ in range(n)]
</code>```

This function works perfect, for example:

```<code>>>> randBinList(100)
[False, False, True, False, False, True, True, False, True, False, False, False, False, True, False, True, False, False, False, False, False, False, True, False, True, True, True, False, False, True, True, False, False, False, False, True, False, True, False, True, False, False, True, False, False, False, True, False, True, False, False, False, False, True, True, True, True, False, True, True, True, True, False, True, True, True, True, False, False, True, True, False, True, False, True, False, True, True, False, False, False, False, True, True, False, False, False, False, True, False, False, True, True, True, False, True, False, True, False, False]
</code>```

However, when I tried to add this function to a new class I'm working on I received the following error:

```<code>return self.randBinList(num_of_features)
TypeError: <lambda>() takes 1 positional argument but 2 were given
</code>```

I do not know why it says that tow arguments were given? Here is the code of my class.  Thanks for your help.

```<code>import sys, csv, os, subprocess, time
from collections import deque, defaultdict
import random
from typing import List
    class ScriptFeatures():
        randBinList = lambda n: [random()<0.5 for _ in range(n)]

        def get_random_individual (self):
            num_of_features = len(self.d)
            return self.randBinList(100)
</code>```

答:
You have to override the on_checkbox_Active callback.

Register to the callback ->

```<code>self.testCheckBox.bind(active= self.on_checkbox_Active)
</code>```

override  ->

```<code>def on_checkbox_Active(self,checkboxInstance, isActive):
                     print('test CheckBox')
</code>```

Body:
I write a simple lambda function to generate a random list of booleans with the following code:

randBinList = lambda n: [random()<0.5 for _ in range(n)]

This function works perfect, for example:

>>> randBinList(100)
[False, False, True, False, False, True, True, False, True, False, False, False, False, True, False, True, False, False, False, False, False, False, True, False, True, True, True, False, False, True, True, False, False, False, False, True, False, True, False, True, False, False, True, False, False, False, True, False, True, False, False, False, False, True, True, True, True, False, True, True, True, True, False, True, True, True, True, False, False, True, True, False, True, False, True, False, True, True, False, False, False, False, True, True, False, False, False, False, True, False, False, True, True, True, False, True, False, True, False, False]

However, when I tried to add this function to a new class I'm working on I received the following error:

return self.randBinList(num_of_features)
TypeError: <lambda>() takes 1 positional argument but 2 were given

I do not know why it says that tow arguments were given? Here is the code of my class.  Thanks for your help.

import sys, csv, os, subprocess, time
from collections import deque, defaultdict
import random
from typing import List
    class ScriptFeatures():
        randBinList = lambda n: [random()<0.5 for _ in range(n)]

        def get_random_individual (self):
            num_of_features = len(self.d)
            return self.randBinList(100)

Body:
You have to override the on_checkbox_Active callback.

Register to the callback ->

self.testCheckBox.bind(active= self.on_checkbox_Active)

override  ->

def on_checkbox_Active(self,checkboxInstance, isActive):
                     print('test CheckBox')


问:
Different color scales for different facets of choropleth map in Plotly?
I made a choropleth map with continuous color scale and divided it for 4 sub-map facets. The problem is that color scale gauge is one for all 4 maps, and even if I'll try to change color scale it’ll be applied to all maps together. Is there a way to set different color scaling for different facets?</p>
```<code>fig = px.choropleth(df,
                     geojson=counties,
                     locations='id',
                     color='count',
                     facet_col='age_group',
                     facet_col_wrap=2,
                     color_continuous_scale='BuGn',
                     hover_name='county',
                     width=1000,
                     height=900,
                     animation_frame='year')
fig.update_geos(fitbounds="locations")
fig.show()
</code>```

答:
you have not provided sample geojson or data.  Have picked up US states and simulated a dataframe so your code pretty much works unchanged (add featurekeyid parameter)

it's a case of updating traces in figure and animation frames to use separate coloraxis

with traces updated, positioning and colorscale of each coloraxis needs to be set

```<code>import plotly.express as px
import requests
import geopandas as gpd

# get some geojson
geojson = requests.get(
    "https://raw.githubusercontent.com/nvkelso/natural-earth-vector/master/geojson/ne_110m_admin_1_states_provinces.geojson"
).json()
counties = {
    k: v
    if k != "features"
    else [
        {
            k: v if k != "properties" else {"id": i, "name": v["name"]}
            for k, v in f.items()
        }
        for i, f in enumerate(v)
    ]
    for k, v in geojson.items()
}

# construct a dataframe of strucrture implied in question
df = (
    pd.json_normalize(counties["features"])
    .pipe(lambda d: d.drop(columns=[c for c in d.columns if not "properties" in c]))
    .rename(columns={"properties.id": "id", "properties.name": "county"})
    .merge(pd.DataFrame({"year": range(2015, 2023)}), how="cross")
    .merge(pd.DataFrame({"age_group": ["<18", "18-30", "30-65", ">65"]}), how="cross")
    .pipe(
        lambda d: d.assign(
            count=np.random.randint(1, 50, len(d))
            * (pd.factorize(d["age_group"])[0] + 1)
        )
    )
)

fig = px.choropleth(
    df,
    geojson=counties,
    locations="id",
    featureidkey="properties.id",
    color="count",
    facet_col="age_group",
    facet_col_wrap=2,
    color_continuous_scale="BuGn",
    hover_name="county",
    width=1000,
    height=900,
    animation_frame="year",
)
fig.update_geos(fitbounds="locations")

# update traces to use different coloraxis
for i, t in enumerate(fig.data):
    t.update(coloraxis=f"coloraxis{i+1}")
for fr in fig.frames:
    # update each of the traces in each of the animation frames
    for i, t in enumerate(fr.data):
        t.update(coloraxis=f"coloraxis{i+1}")

# position / config all coloraxis
fig.update_layout(
    coloraxis={"colorbar": {"x": -0.2, "len": 0.5, "y": 0.8}},
    coloraxis2={
        "colorbar": {
            "x": 1.2,
            "len": 0.5,
            "y": 0.8,
        },
        "colorscale": fig.layout["coloraxis"]["colorscale"],
    },
    coloraxis3={
        "colorbar": {"x": -0.2, "len": 0.5, "y": 0.3},
        "colorscale": fig.layout["coloraxis"]["colorscale"],
    },
    coloraxis4={
        "colorbar": {"x": 1.2, "len": 0.5, "y": 0.3},
        "colorscale": fig.layout["coloraxis"]["colorscale"],
    },
)
</code>```

Body:
I made a choropleth map with continuous color scale and divided it for 4 sub-map facets. The problem is that color scale gauge is one for all 4 maps, and even if I'll try to change color scale it’ll be applied to all maps together. Is there a way to set different color scaling for different facets?

fig = px.choropleth(df,
                     geojson=counties,
                     locations='id',
                     color='count',
                     facet_col='age_group',
                     facet_col_wrap=2,
                     color_continuous_scale='BuGn',
                     hover_name='county',
                     width=1000,
                     height=900,
                     animation_frame='year')
fig.update_geos(fitbounds="locations")
fig.show()

Body:
you have not provided sample geojson or data.  Have picked up US states and simulated a dataframe so your code pretty much works unchanged (add featurekeyid parameter)

it's a case of updating traces in figure and animation frames to use separate coloraxis

with traces updated, positioning and colorscale of each coloraxis needs to be set

import plotly.express as px
import requests
import geopandas as gpd

# get some geojson
geojson = requests.get(
    "https://raw.githubusercontent.com/nvkelso/natural-earth-vector/master/geojson/ne_110m_admin_1_states_provinces.geojson"
).json()
counties = {
    k: v
    if k != "features"
    else [
        {
            k: v if k != "properties" else {"id": i, "name": v["name"]}
            for k, v in f.items()
        }
        for i, f in enumerate(v)
    ]
    for k, v in geojson.items()
}

# construct a dataframe of strucrture implied in question
df = (
    pd.json_normalize(counties["features"])
    .pipe(lambda d: d.drop(columns=[c for c in d.columns if not "properties" in c]))
    .rename(columns={"properties.id": "id", "properties.name": "county"})
    .merge(pd.DataFrame({"year": range(2015, 2023)}), how="cross")
    .merge(pd.DataFrame({"age_group": ["<18", "18-30", "30-65", ">65"]}), how="cross")
    .pipe(
        lambda d: d.assign(
            count=np.random.randint(1, 50, len(d))
            * (pd.factorize(d["age_group"])[0] + 1)
        )
    )
)

fig = px.choropleth(
    df,
    geojson=counties,
    locations="id",
    featureidkey="properties.id",
    color="count",
    facet_col="age_group",
    facet_col_wrap=2,
    color_continuous_scale="BuGn",
    hover_name="county",
    width=1000,
    height=900,
    animation_frame="year",
)
fig.update_geos(fitbounds="locations")

# update traces to use different coloraxis
for i, t in enumerate(fig.data):
    t.update(coloraxis=f"coloraxis{i+1}")
for fr in fig.frames:
    # update each of the traces in each of the animation frames
    for i, t in enumerate(fr.data):
        t.update(coloraxis=f"coloraxis{i+1}")

# position / config all coloraxis
fig.update_layout(
    coloraxis={"colorbar": {"x": -0.2, "len": 0.5, "y": 0.8}},
    coloraxis2={
        "colorbar": {
            "x": 1.2,
            "len": 0.5,
            "y": 0.8,
        },
        "colorscale": fig.layout["coloraxis"]["colorscale"],
    },
    coloraxis3={
        "colorbar": {"x": -0.2, "len": 0.5, "y": 0.3},
        "colorscale": fig.layout["coloraxis"]["colorscale"],
    },
    coloraxis4={
        "colorbar": {"x": 1.2, "len": 0.5, "y": 0.3},
        "colorscale": fig.layout["coloraxis"]["colorscale"],
    },
)


问:
Protocol buffers for JavaScript?
Is there a way to do protocol buffers in JavaScript?

Why for .js?

If you think about sciencey requirements for a moment, situations pop up where you might want to send a large block of data to the client.  With CRUD-style it doesn't really matter so much what you use.  With sciencey stuff it does matter (at least I think it does).

tradeoffs:

protobuffs balances compactness, serialize and deserialize speeds well.

text based protocols (xml / json) have a larger message size... but with javascript I wonder which is more effective.

reference:

code.google.com/p/protobuf-plugin-closure

Google Protocol Buffers or something similar for .net/javascript

https://github.com/sirikata/protojs

Google Protocol Buffers - JavaScript

http://www.vitaliykulikov.com/2011/02/gwt-friendly-protocol-buffers.html

http://benhakala.blogspot.com/2010/05/converting-google-protocol-buffers-to.html (alludes to google maps possibly using protobufs)

Additional references provided by community (see below for more context):

https://github.com/dcodeIO/ProtoBuf.js

http://blog.ltgt.net/exploring-using-protobuf-in-the-browser/

http://blog.ltgt.net/using-protobuf-client-side-with-gwt

http://code.google.com/p/protobuf-gwt/

答:
Google makes heavy use of Protocol Buffers in JS (GMail, etc.) through their Closure Library, generating JS code with a (unfortunately non-open-sourced) modified protoc (it would probably have to be ported to a protoc extension before being open-sourced).

Apache Wave (whose client webapp is built with GWT) also uses Protocol Buffers for its communications with the server, generating Java code by reflecting on the Java classes produced by protoc (this is the PST, aka protobuf-stringtemplate, subproject).

Previously, Wave was using protostuff (and I don't know why they switched to their own solution, I suspect PST is derived from what the original Google Wave was using, and protostuff was only an intermediate step during the move to open-source).

As a side note, I started exploring using Protocol Buffers on the browser side a while ago: http://blog.ltgt.net/exploring-using-protobuf-in-the-browser/ & http://blog.ltgt.net/using-protobuf-client-side-with-gwt with some almost-working code at http://code.google.com/p/protobuf-gwt/ that you might want to resurrect.

Finally, there's work underway to make GWT RequestFactory proxies compatible with the server-side Java classes generated by protoc (and you could use a protoc extension or a similar approach to Wave's PST to generate your RequestFactory proxies). It should already be possible, provided you use builders all the way on the server-side (which is not quite how the Protocol Buffers Java API was designed).

Title: Protocol buffers for JavaScript?


问:
Powershell - Find computers with a specific username logged in
I've been trying to figure out a powershell script that doing a search of all computers
with a specific username logged in.

so far I've found a way looking via all computers the 'explorer.exe' process and owner

Also I found this script:

```<code>Function Get-Username {
    Clear-Host
    $Global:Username = Read-Host "Enter Username"
    if ($Username -eq $null){
        Write-Host "Username cannot be blank, please enter a Username"
        Get-Username
    }
    $UserCheck = Get-ADUser $Username
    if ($UserCheck -eq $null){
        Write-Host "Invalid Username, please verify this is the logon id for the account"
        Get-Username
    }
}
Get-Username

Function Get-Computername {
    Clear-Host
    $Global:Prefix = Read-Host "Enter Computername"
    Clear-Host
}
Get-Computername

$computers = Get-ADComputer -Filter {Enabled -eq 'true' -and SamAccountName -like $Prefix}
$CompCount = $Computers.Count
Write-Host "Searching for $Username on $Prefix on $CompCount Computers`n"

foreach ($comp in $computers){
    $Computer = $comp.Name
    $Reply = $null
    $Reply = test-connection $Computer -count 1 -quiet
    if($Reply -eq 'True'){
        if($Computer -eq $env:COMPUTERNAME){
            $proc = gwmi win32_process -ErrorAction SilentlyContinue -computer $Computer -Filter "Name = 'explorer.exe'"
        }
        else{
            $proc = gwmi win32_process -ErrorAction SilentlyContinue -Credential $Credential -computer $Computer -Filter "Name = 'explorer.exe'"
        }

            $progress++
            ForEach ($p in $proc) {
                $temp = ($p.GetOwner()).User
                Write-Progress -activity "Working..." -status "Status: $progress of $CompCount Computers checked" -PercentComplete (($progress/$Computers.Count)*100)
                if ($temp -eq $Username){
                write-host "$Username is logged on $Computer"
                }
            }
        }
    }
</code>```

This is not my script, only trying to use it.

this script can take a very long long time, trying to run on about 300 machines, it can take for 20 minutes run.

now im not sure, which part is taking most of the time, im thinking either the gwmi win32 process, that checking on each machine if the process 'explorer.exe' is on
or the part test-connection that trying to ping each machine first, and then check for the 'explorer.exe' process.

for your knowledge, is there any faster way with powershell script to do this kind of checkup?
to search for a specific username on which machines logged on?

Thanks in advance for any help!

答:
this is a slightly different approach. [grin] it presumes that you may want to check on more than one user name, so it grabs ALL the users on ALL the systems. once you have that, you can query for the one you want ... and then query for the next without having to wait for the system list to be scanned again.

the code ...

```<code>$ComputerList = @"
LocalHost
10.0.0.1
127.0.0.1
BetterNotBeThere
$env:COMPUTERNAME
"@ -split [System.Environment]::NewLine
#endregion >>> fake reading in a list of computer names

$GCIMI_Params = @{
    ClassName = 'CIM_ComputerSystem'
    ComputerName = $ComputerList
    ErrorAction = 'SilentlyContinue'
    # this will hold the errors from the non-repsonding systems - if you want that info
    ErrorVariable =  'NonResponderList'
    }
$LoggedInUserList = Get-CimInstance @GCIMI_Params |
    ForEach-Object {
        [PSCustomObject]@{
            # the ".Split()" gets rid of the domain/workgroup/system part of the UserName
            UserName = $_.UserName.Split('\')[-1]
            ComputerName = $_.DNSHostName
            # this shows the name used by the G-CimI call - it can be different
            QueryComputerName = $_.PSComputerName
            }
        }

#get your target user name
$TargetUserName = $env:USERNAME

#get the system that name is logged into
$LoggedInUserList.Where({$_.UserName -eq $TargetUserName})

</code>```

output on my system today ...

```<code>UserName    ComputerName QueryComputerName
--------    ------------ -----------------
MyUserName  MySysName    MySysName
MyUserName  MySysName    LocalHost
MyUserName  MySysName    127.0.0.1
</code>```

what the code does ...

builds a list of systems to check

when you are ready to do this with real data, just remove the entire #region/#endregion block & replace it with your Get-ADComputer call.

builds a splat of the parameters for the Get-CimInstance call

sends the G-CimI call to the target systems

generates a [PSCustomObject] containing the desired properties

sends that PSCO out to a results collection

grabs a user name

filters the results collection

shows the system[s] the user name is logged into - if there are any

note that i only have one system, so the 3 responses are all from that same box. also note that the computer can be referred to by DNS name, IP address, or LocalHost.

Body:
I've been trying to figure out a powershell script that doing a search of all computers
with a specific username logged in.

so far I've found a way looking via all computers the 'explorer.exe' process and owner

Also I found this script:

Function Get-Username {
    Clear-Host
    $Global:Username = Read-Host "Enter Username"
    if ($Username -eq $null){
        Write-Host "Username cannot be blank, please enter a Username"
        Get-Username
    }
    $UserCheck = Get-ADUser $Username
    if ($UserCheck -eq $null){
        Write-Host "Invalid Username, please verify this is the logon id for the account"
        Get-Username
    }
}
Get-Username

Function Get-Computername {
    Clear-Host
    $Global:Prefix = Read-Host "Enter Computername"
    Clear-Host
}
Get-Computername

$computers = Get-ADComputer -Filter {Enabled -eq 'true' -and SamAccountName -like $Prefix}
$CompCount = $Computers.Count
Write-Host "Searching for $Username on $Prefix on $CompCount Computers`n"

foreach ($comp in $computers){
    $Computer = $comp.Name
    $Reply = $null
    $Reply = test-connection $Computer -count 1 -quiet
    if($Reply -eq 'True'){
        if($Computer -eq $env:COMPUTERNAME){
            $proc = gwmi win32_process -ErrorAction SilentlyContinue -computer $Computer -Filter "Name = 'explorer.exe'"
        }
        else{
            $proc = gwmi win32_process -ErrorAction SilentlyContinue -Credential $Credential -computer $Computer -Filter "Name = 'explorer.exe'"
        }

            $progress++
            ForEach ($p in $proc) {
                $temp = ($p.GetOwner()).User
                Write-Progress -activity "Working..." -status "Status: $progress of $CompCount Computers checked" -PercentComplete (($progress/$Computers.Count)*100)
                if ($temp -eq $Username){
                write-host "$Username is logged on $Computer"
                }
            }
        }
    }

This is not my script, only trying to use it.

this script can take a very long long time, trying to run on about 300 machines, it can take for 20 minutes run.

now im not sure, which part is taking most of the time, im thinking either the gwmi win32 process, that checking on each machine if the process 'explorer.exe' is on
or the part test-connection that trying to ping each machine first, and then check for the 'explorer.exe' process.

for your knowledge, is there any faster way with powershell script to do this kind of checkup?
to search for a specific username on which machines logged on?

Thanks in advance for any help!

Body:
this is a slightly different approach. [grin] it presumes that you may want to check on more than one user name, so it grabs ALL the users on ALL the systems. once you have that, you can query for the one you want ... and then query for the next without having to wait for the system list to be scanned again.

the code ...

$ComputerList = @"
LocalHost
10.0.0.1
127.0.0.1
BetterNotBeThere
$env:COMPUTERNAME
"@ -split [System.Environment]::NewLine
#endregion >>> fake reading in a list of computer names

$GCIMI_Params = @{
    ClassName = 'CIM_ComputerSystem'
    ComputerName = $ComputerList
    ErrorAction = 'SilentlyContinue'
    # this will hold the errors from the non-repsonding systems - if you want that info
    ErrorVariable =  'NonResponderList'
    }
$LoggedInUserList = Get-CimInstance @GCIMI_Params |
    ForEach-Object {
        [PSCustomObject]@{
            # the ".Split()" gets rid of the domain/workgroup/system part of the UserName
            UserName = $_.UserName.Split('\')[-1]
            ComputerName = $_.DNSHostName
            # this shows the name used by the G-CimI call - it can be different
            QueryComputerName = $_.PSComputerName
            }
        }

#get your target user name
$TargetUserName = $env:USERNAME

#get the system that name is logged into
$LoggedInUserList.Where({$_.UserName -eq $TargetUserName})

output on my system today ...

UserName    ComputerName QueryComputerName
--------    ------------ -----------------
MyUserName  MySysName    MySysName
MyUserName  MySysName    LocalHost
MyUserName  MySysName    127.0.0.1

what the code does ...

builds a list of systems to check

when you are ready to do this with real data, just remove the entire #region/#endregion block & replace it with your Get-ADComputer call.

builds a splat of the parameters for the Get-CimInstance call

sends the G-CimI call to the target systems

generates a [PSCustomObject] containing the desired properties

sends that PSCO out to a results collection

grabs a user name

filters the results collection

shows the system[s] the user name is logged into - if there are any

note that i only have one system, so the 3 responses are all from that same box. also note that the computer can be referred to by DNS name, IP address, or LocalHost.


问:
How do I get Netbeans to use the specified Gradle version?
I've come back to project after a long diversion, and upgraded tooling. This means Netbeans 12.5, Java 17, Gradle 7.3… at least allegedly. For some reason, despite setting the Gradle version to 7.3, it appears to build with 7.0.

Per the image below, setting the Gradle version to 7.3 doesn't seem to be picked up. (That is immediately after hitting Apply.) It still tries to build with 7.0. And – for some indeterminate reason – it can't.

Restarts don't help; I can't get the configuration to be picked up. (Searches for reference to similar issues provide 5-year-old answers that are no longer relevant.) I've even tried deleting the 7.0 distribution; to no avail, it comes right back.

Can anyone provide guidance on getting this to work properly?

答:
Don't bother with gradle in Netbeans. It's a horrible, buggy disaster and 12.6 just seems to want to up the ante.

Netbeans does NOT support gradle in a meaningful way for normal users.

You now get complex multi-projects whether you want them or not.

When creating a Java Application you don't get a choice at what the Main class is called. It will be App with app.java and you will like it.

If you try to rename app.java to something useful. It will not change "Class App" to "Class Useful" it will instead change it to "ClassUsefulp". It will not rename the test file and you will be left with several syntax errors that you can have fun cleaning up.

No, you cannot rename the subproject itself. That will continue to be the extremely descriptive and useful "app" subproject. The IDE will not provide you a way to rename that.

There is no meaningful, intuitive way to create/delete/modify subprojects.

If your gradle version is somehow out of sync there is still no useful way to reset/recreate the gradle wrapper other than creating a whole new project and moving your source code over to the new project.

Oh, so you gave in and accepted the multi-project structure. You noticed that if you go through the multi-project creator GUI then you can create multiple subprojects. Yeah, good luck with that. They won't have gradle build.scripts or wrappers. You won't be able to build your awesome creation.

Want to use command line arguments? Forget it. There is no "run" element in the project properties. You cannot create different run configurations.

Want dependencies? Or any other project configuration? It's all manual editing of gradle files. There's no GUI to assist non-gradle-wizards.

Yeah. you can probably work around a lot of this by dropping to a command line shell and editing the gradle scripts/files manually and running gradle commands manually. A) you're going to need to be a gradle wizard, and B) why are you using an IDE in the first place? you've got gradle, you've got vi available. Bathe in the nostalgia because you'll have to anyways.

Do you like the idea of gradle? Do you use Netbeans? Stick with Ant, or Maven if you need external dependencies; you'll thank me later.


问:
Why does -INT_MIN = INT_MIN in a signed, two's complement representation?
I still haven't found a reason why the lowest signed negative number doesn't have an equivalent signed positive number?
I mean in a 3 digit binary number for simplicity
100 is -4? but we can't have a positive 4 in signed format because we can't. It overflows.
So how do we know two's complement 1000 is -4 1000 0000 is  -128 and so on? We have no original positive number</p>

答:
Two's complement represents negative numbers by reserving the highest bit as negative.
This means you can't use the highest bit as positive anymore.

All the other (lower) bits are positive but no matter how you add them up,
the sum can never reach the highest bit because it's seen as negative.