问:
Static to non-static refactoring, can't have both?
I have a refactoring situation that I cannot find an elegant solution for...

Disclaimer:
Keep in mind that I am oversimplifying this example to reduce clutter, and not disclose things I am not allowed to disclose :)
As such, please do not assume that this is the ONLY code in my giant codebase, and offer solutions that cut corners or change parts of the design that I mention cannot be changed due to outside constraints.

The facts:

I have a utility class, it has a bunch of static methods, they utilize a singleton resource:

```<code>public final class Utility
{
   private static final Resource RES = Resource.getInstance();

   private Utility() {}  // Prevent instantiating Utility

   public static boolean utilMethodOne() { return RES.isSomething(); }
   public static int utilMethodTwo() { RES.getNumThings(); }
   ...
   public static void utilMethodInfinity() { ... }
}
</code>```

Utility is in a library JAR that is used by several applications in a large codebase -- let's say on the order of 10,000 calls to its static methods, e.g.:   if(Utility.utilMethodOne()) { ... }

Resource is an outside class from another library JAR.

Resource also has a method Resource.getInstance(String name) that will return a named instance, which may relate to a different underlying resource based on the name (internally it keeps the named resources in a Map<String,Resource>).

Resource.getInstance() returns the equivalent of Resoruce.getInstance(""), aka the default instance.

The situation:

The Utility needs to be enhanced to now execute against one of several resources, so my plan is to make the Utility an instantiable class with a non-static Resource member variable.  Something like this:

```<code>public final class Utility
{
   private Resource res;

   public Utility(String resName)
   {
      this.res =  = Resource.getInstance(resName);
   }

   public boolean utilMethodOne() { return this.res.isSomething(); }
   public int utilMethodTwo() { this.res.getNumThings(); }
   ...
   public void utilMethodInfinity() { ... }
}
</code>```

Now all this is great, and I can start creating Utility objects that access their specified resource instead of just the default one.  However, as I mentioned, there are 10-100K method calls that are now invalid as they were calling static methods!

The problem:

My plan was to keep the static methods in Utility, and have them use the default instance from Resource, while adding in non-static variants for the instantiated Utility objects that use their "local" resource reference.

```<code>   // Best of both worlds:
   public static boolean utilMethodOne() { return RES.isSomething(); }
   public boolean utilMethodOne() { return this.res.isSomething(); }
</code>```

Maybe I can't have my cake & eat it too:

```<code>error: method utilMethodOne() is already defined in class Utility
   public static boolean utilMethodOne(String sql)
</code>```

So it seems I am going to have to either...

Introduce a whole new BetterUtility class for places that want to use the named-resources.

Update 10,000 places to instantiate & use the revised Utility object.

...?  (hint: this is where your suggestions come in!)

I really don't like 1 or 2 for a variety of reasons, so I need to ensure there is no better 3 option before settling.  Is there any way to retain a single class that can provide both the static & non-static interfaces in this case?

UPDATE 2020-06-01:

I am coming to the realization that this magical option 3 doesn't exist.  So out of my original two options I think #2 is best as it's just one time "just get it out of the way and be done with it" type effort.  Also incorporated some of your suggestions in the design(s).

So now that I have a direction on this, I am left with [hopefully only] one more key decision...

Update all the calls to create new objects

```<code>// For a one-off call, do it inline
boolean foo = new Utility("res1").utilMethodOne();

// Or when used multiple times, re-use the object
Utility util = new Utility("res1");
boolean foo = util.utilMethodOne();
int bar = util.utilMethodTwo();
...
</code>```

Given the amount/frequency of usage, this seems like a whole lot of wasted efforts creating short-lived objects.

Follow the pattern that Resource itself uses, creating my own named-singleton map of Utilities (1:1 with their respectively named Resource)

```<code>public final class Utility
{
   private static final Map<String,Utility> NAMED_INSTANCES = new HashMap<>();

   private Resource res;

   private Utility(String resName)
   {
      this.res = Resource.getInstance(resName);
   }

   public static Utility getInstance(String resName)
   {
      synchronized(NAMED_INSTANCES)
      {
         Utility instance = NAMED_INSTANCES.get(resName);
         if(instance == null)
         {
            instance = new Utility(resName);
            NAMED_INSTANCES.put(resName, instance);
         }

         return instance;
      }
   }

   public boolean utilMethodOne() { return this.res.isSomething(); }
   public int utilMethodTwo() { this.res.getNumThings(); }
   ...
   public void utilMethodInfinity() { ... }
}

// Now the calls can use
Utility.getInstance("res1")

// In place of
new Utility("res1")
</code>```

So essentially this boils down to object creation vs. a synchronization + map lookup at each usage.  Probably a little bit of premature optimization here, but I'll probably have to stick with this decision long term.

UPDATE 2020-06-29:

Didn't want to leave an "Internet dead end" here...
I did eventually get all the call sites updated as described above (including option #2 from the 2020-06-01 update).  It has made it through all testing and been running in production for a week or so now in various applications.

答:
Keep the old methods and the new methods static.</p>

```<code>private static final String DEFAULT = "RESOURCE1";
private static Map<String, Resource> resources = new HashMap();
static{
// initialize all resources
}
public static boolean utilMethod() { return resources.get(DEFAULT).isSomething(); }
public static boolean utilMethod(String resourceName) { return resources.get(resourceName).isSomething(); }
</code>```

Body:
I have a refactoring situation that I cannot find an elegant solution for...

Disclaimer:
Keep in mind that I am oversimplifying this example to reduce clutter, and not disclose things I am not allowed to disclose :)
As such, please do not assume that this is the ONLY code in my giant codebase, and offer solutions that cut corners or change parts of the design that I mention cannot be changed due to outside constraints.

The facts:

I have a utility class, it has a bunch of static methods, they utilize a singleton resource:

public final class Utility
{
   private static final Resource RES = Resource.getInstance();

   private Utility() {}  // Prevent instantiating Utility

   public static boolean utilMethodOne() { return RES.isSomething(); }
   public static int utilMethodTwo() { RES.getNumThings(); }
   ...
   public static void utilMethodInfinity() { ... }
}

Utility is in a library JAR that is used by several applications in a large codebase -- let's say on the order of 10,000 calls to its static methods, e.g.:   if(Utility.utilMethodOne()) { ... }

Resource is an outside class from another library JAR.

Resource also has a method Resource.getInstance(String name) that will return a named instance, which may relate to a different underlying resource based on the name (internally it keeps the named resources in a Map<String,Resource>).

Resource.getInstance() returns the equivalent of Resoruce.getInstance(""), aka the default instance.

The situation:

The Utility needs to be enhanced to now execute against one of several resources, so my plan is to make the Utility an instantiable class with a non-static Resource member variable.  Something like this:

public final class Utility
{
   private Resource res;

   public Utility(String resName)
   {
      this.res =  = Resource.getInstance(resName);
   }

   public boolean utilMethodOne() { return this.res.isSomething(); }
   public int utilMethodTwo() { this.res.getNumThings(); }
   ...
   public void utilMethodInfinity() { ... }
}

Now all this is great, and I can start creating Utility objects that access their specified resource instead of just the default one.  However, as I mentioned, there are 10-100K method calls that are now invalid as they were calling static methods!

The problem:

My plan was to keep the static methods in Utility, and have them use the default instance from Resource, while adding in non-static variants for the instantiated Utility objects that use their "local" resource reference.

   // Best of both worlds:
   public static boolean utilMethodOne() { return RES.isSomething(); }
   public boolean utilMethodOne() { return this.res.isSomething(); }

Maybe I can't have my cake & eat it too:

error: method utilMethodOne() is already defined in class Utility
   public static boolean utilMethodOne(String sql)

So it seems I am going to have to either...

Introduce a whole new BetterUtility class for places that want to use the named-resources.

Update 10,000 places to instantiate & use the revised Utility object.

...?  (hint: this is where your suggestions come in!)

I really don't like 1 or 2 for a variety of reasons, so I need to ensure there is no better 3 option before settling.  Is there any way to retain a single class that can provide both the static & non-static interfaces in this case?

UPDATE 2020-06-01:

I am coming to the realization that this magical option 3 doesn't exist.  So out of my original two options I think #2 is best as it's just one time "just get it out of the way and be done with it" type effort.  Also incorporated some of your suggestions in the design(s).

So now that I have a direction on this, I am left with [hopefully only] one more key decision...

Update all the calls to create new objects

// For a one-off call, do it inline
boolean foo = new Utility("res1").utilMethodOne();

// Or when used multiple times, re-use the object
Utility util = new Utility("res1");
boolean foo = util.utilMethodOne();
int bar = util.utilMethodTwo();
...

Given the amount/frequency of usage, this seems like a whole lot of wasted efforts creating short-lived objects.

Follow the pattern that Resource itself uses, creating my own named-singleton map of Utilities (1:1 with their respectively named Resource)

public final class Utility
{
   private static final Map<String,Utility> NAMED_INSTANCES = new HashMap<>();

   private Resource res;

   private Utility(String resName)
   {
      this.res = Resource.getInstance(resName);
   }

   public static Utility getInstance(String resName)
   {
      synchronized(NAMED_INSTANCES)
      {
         Utility instance = NAMED_INSTANCES.get(resName);
         if(instance == null)
         {
            instance = new Utility(resName);
            NAMED_INSTANCES.put(resName, instance);
         }

         return instance;
      }
   }

   public boolean utilMethodOne() { return this.res.isSomething(); }
   public int utilMethodTwo() { this.res.getNumThings(); }
   ...
   public void utilMethodInfinity() { ... }
}

// Now the calls can use
Utility.getInstance("res1")

// In place of
new Utility("res1")

So essentially this boils down to object creation vs. a synchronization + map lookup at each usage.  Probably a little bit of premature optimization here, but I'll probably have to stick with this decision long term.

UPDATE 2020-06-29:

Didn't want to leave an "Internet dead end" here...
I did eventually get all the call sites updated as described above (including option #2 from the 2020-06-01 update).  It has made it through all testing and been running in production for a week or so now in various applications.

Body:
Keep the old methods and the new methods static.

private static final String DEFAULT = "RESOURCE1";
private static Map<String, Resource> resources = new HashMap();
static{
// initialize all resources
}
public static boolean utilMethod() { return resources.get(DEFAULT).isSomething(); }
public static boolean utilMethod(String resourceName) { return resources.get(resourceName).isSomething(); }


来源: stackexchange

问:
Javascript form validation
How do I let users know that "there are changes left to be saved on the form if they try to close the browser window?"

I have a form with couple of fields, Now if the user changes some of the fields and clicks on Close button on the browser window, my script should alert him of unsaved changes. How do I implement this? I have put in basic form validation but can't seem to think of a solution for window.close() event. Any sample links would be helpful.

答:
You can't prevent a user from closing a window (that would mean a malicious script could do that as well, making it a huge security vulnerability).

That being said, you can ask if the user wants to save his/ her changes before actually leaving the page. You would need onBeforeUnload (set the attribute in HTML or use javascript) to call a script. This is what that script could look like:

```<code>function beforeClose () {

    if (formChanged) {

        var chk = confirm('Do you want to save your changes before you go?');
        if (chk) {

             // Code (AJAX) that will send/ store the data)

         }
     }
}
</code>```

In this function I invented a variable called 'formChanged'. The most sensible way to do this is to track whether a user has changed things while on the page (by adding the onChange attribute to the form fields that will set the formChanged variable to true). The linked post in your question's first comment shows you a jQuery script that will check for changes, if you want to use that.

ContentLicense: CC BY-SA 3.0

Title: Javascript form validation

Body:
You can't prevent a user from closing a window (that would mean a malicious script could do that as well, making it a huge security vulnerability).

That being said, you can ask if the user wants to save his/ her changes before actually leaving the page. You would need onBeforeUnload (set the attribute in HTML or use javascript) to call a script. This is what that script could look like:

function beforeClose () {

    if (formChanged) {

        var chk = confirm('Do you want to save your changes before you go?');
        if (chk) {

             // Code (AJAX) that will send/ store the data)

         }
     }
}

In this function I invented a variable called 'formChanged'. The most sensible way to do this is to track whether a user has changed things while on the page (by adding the onChange attribute to the form fields that will set the formChanged variable to true). The linked post in your question's first comment shows you a jQuery script that will check for changes, if you want to use that.


问:
InnoDB full-text-search deadlock
I have a medium-volume application that does about 40 inserts per second. All inserts are in the format of:

```<code>UPDATE item SET values=... WHERE row_id='18273-3749d-8743'
</code>```

Furthermore, no item is updated multiple times at the same time. It seems simple enough and there should never be a deadlock if we ignore everything else. However, I have a fulltext field that seems to acquire a pseudo-table level lock, instead of a row-level lock, if I'm troubleshooting this correctly. Here is the error that it gives on SHOW ENGINE INNODB STATUS:

```<code>LATEST DEADLOCK DETECTED
...
RECORD LOCKS space ... index FTS_DOC_ID_INDEX of table
</code>```

So, if I'm interpreting this correctly, it seems like FTS_DOC_ID_INDEX is doing some sort of "more-than-row-level-lock" to update the search index. Is this what is occurring? And if so, what's the correct way to deal with this -- as in, I cannot decrease the number of writes to the application, is there a way to do a "safe update" (?) on the FTS field? Or do I need to  write the updates such that I remove the fts field and queue those separately (which would seem like a huge pain to do). What's the best way to deal with this?

答:
(After seeing the SELECT, etc`, I may have a better answer, but here is starting advice.)

Whenever you may get a deadlock, you should provide in your code for recovering from it.  That is, check for deadlock after doing the UPDATE, then re-execute the update once.

ContentLicense: CC BY-SA 4.0

Title: InnoDB full-text-search deadlock

Body:
I have a medium-volume application that does about 40 inserts per second. All inserts are in the format of:

UPDATE item SET values=... WHERE row_id='18273-3749d-8743'

Furthermore, no item is updated multiple times at the same time. It seems simple enough and there should never be a deadlock if we ignore everything else. However, I have a fulltext field that seems to acquire a pseudo-table level lock, instead of a row-level lock, if I'm troubleshooting this correctly. Here is the error that it gives on SHOW ENGINE INNODB STATUS:

LATEST DEADLOCK DETECTED
...
RECORD LOCKS space ... index FTS_DOC_ID_INDEX of table

So, if I'm interpreting this correctly, it seems like FTS_DOC_ID_INDEX is doing some sort of "more-than-row-level-lock" to update the search index. Is this what is occurring? And if so, what's the correct way to deal with this -- as in, I cannot decrease the number of writes to the application, is there a way to do a "safe update" (?) on the FTS field? Or do I need to  write the updates such that I remove the fts field and queue those separately (which would seem like a huge pain to do). What's the best way to deal with this?


问:
Open and scan dms for key words
I'm working on a bot, and wanted to know if there was a way to open dms from all people in a server, and see if any commands were in there. If so I want the commands to be completed, but only with certain key words. Please help!</p>

答:
You can loop through the Guild's members collection and access the GuildMember's DMchannel using GuildMember.user.dmChannel then fetch all the messages using dmChannel.messages.fetch() then use filter() to get the messages with the keywords you're looking for

message.guild.members.cache.forEach(async (member) => {
  const fetchedMsgs = await member.user.dmChannel.messages.fetch()
  const messages = fetchedMsgs.filter((message) => message.content.toLowerCase().includes('search term')) // make sure the search term is lowercase
  messages.forEach((message) => console.log(`${message.author.username} (${message.author.id}): '${message.content}' @ ${message.createdAt}`)
})
```

Title: Open and scan dms for key words


问:
Handle text overflow in flutter
How to manage input to Text widget below, when i am having a hardcoded value like "data" it works fine but when i pass variable which has input value i get overflow issue. I am able to understand why its giving error but not sure how to fix that.</p>

```<code> return Container(
      width: sizew,
      height: sizeh,
      decoration: boxDecoration,

      child: FlatButton(
        padding: EdgeInsets.all(10),
        onPressed: onTap,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.all(Radius.elliptical(10,10),)
        ),
        child: SingleChildScrollView(
            child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              child  ?? Container(),
              Text("data"),
            ],
          ),
        ),

      ),
    );
</code>```

答:
Not sure what i was doing wrong, but i just realized that

```<code>Text(label)
</code>```

Is not accepted by flutter, even though other values like sizew and sizeh works direct. Passing value like, solved my problem. As there was error related to overflow i was trying to solve it different way. I should have mentioned how i am passing value in my post to make it clear...

```<code>Text('$label')
</code>```

Title: Handle text overflow in flutter

Body:
How to manage input to Text widget below, when i am having a hardcoded value like "data" it works fine but when i pass variable which has input value i get overflow issue. I am able to understand why its giving error but not sure how to fix that.

 return Container(
      width: sizew,
      height: sizeh,
      decoration: boxDecoration,

      child: FlatButton(
        padding: EdgeInsets.all(10),
        onPressed: onTap,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.all(Radius.elliptical(10,10),)
        ),
        child: SingleChildScrollView(
            child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              child  ?? Container(),
              Text("data"),
            ],
          ),
        ),

      ),
    );

Body:
Not sure what i was doing wrong, but i just realized that

Text(label)

Is not accepted by flutter, even though other values like sizew and sizeh works direct. Passing value like, solved my problem. As there was error related to overflow i was trying to solve it different way. I should have mentioned how i am passing value in my post to make it clear...

Text('$label')


问:
How to login with new IAM user
I can not login with new IAM user who has console access:

I have downloaded credentials and when trying to login using given console url(https://My_AWS_Account_ID.signin.aws.amazon.com/console/) and I  am receiving following error:

Your authentication information is incorrect. Please try again.

This is a policy summary for user:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "s3:*",
            "Resource": "my-s3-arn"
        }
    ]
}

I have tried to manage and change password for this user and to login again but the same error appears:

Any idea how to login or troubleshout problem?

答: I have faced this problem in the past, usually when the IAM user was added recently. The two ways to overcome this were to wait a day or two and try the credentials again or change the password manually (not using automatically generated passwords).</p>

Title: How to login with new IAM user


问:
When/why to prefix variables with "$" when using jQuery?

Possible Duplicate:

  Why would a javascript variable start with a dollar sign?

I see people using the dollar sign in front of variables when using jQuery. Is there any reason behind this? I'm I missing something basic or is it just a common practice?

答:
Many people using jQuery will prefix variables that contain a jQuery object with a $, so that they are easily identified. Consider this example:</p>

```<code>var $img = $(".someclass span.otherclass img");
/* somewhere later in the code */
$img.bind("click", function() {/*...*/});
</code>```

Body:
Many people using jQuery will prefix variables that contain a jQuery object with a $, so that they are easily identified. Consider this example:

var $img = $(".someclass span.otherclass img");
/* somewhere later in the code */
$img.bind("click", function() {/*...*/});


问:
Get the Data values from the registry using powershell
I am trying to add an application in 'DisallowRun' registry key to avoid running application to specific users. Need to add the application if not exist. Consider 'TestApp3.exe' in this case.

Used below query to get the list of items in the key. It is giving Name(Key Name), Property(Name Value : Data Value)

```<code>Get-Item -Path "Registry::HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\DisallowRun"
</code>```

Output

Name                           Property

----                           --------

DisallowRun                    1 : TestApp1.exe

DisallowRun                    2 : TestApp2.exe

DisallowRun                    3 : TestApp3.exe

DisallowRun                    4 : TestApp4.exe

When i use .Property in the code, getting only Name Values and not Data Values

```<code>(Get-Item -Path "Registry::HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\DisallowRun").Property
</code>```

Output

1

2

3

4

If i get only the Data Values (similar to below) then i could have use contains function to check the specific application is already available or not. Please help me to get only Data Value or is there anyway to check the application is exist in the registry key.

TestApp1.exe

TestApp2.exe

TestApp3.exe

TestApp4.exe

Body:
I am trying to add an application in 'DisallowRun' registry key to avoid running application to specific users. Need to add the application if not exist. Consider 'TestApp3.exe' in this case.

Used below query to get the list of items in the key. It is giving Name(Key Name), Property(Name Value : Data Value)

Get-Item -Path "Registry::HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\DisallowRun"

Output

Name                           Property

----                           --------

DisallowRun                    1 : TestApp1.exe

DisallowRun                    2 : TestApp2.exe

DisallowRun                    3 : TestApp3.exe

DisallowRun                    4 : TestApp4.exe

When i use .Property in the code, getting only Name Values and not Data Values

(Get-Item -Path "Registry::HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\DisallowRun").Property

Output

1

2

3

4

If i get only the Data Values (similar to below) then i could have use contains function to check the specific application is already available or not. Please help me to get only Data Value or is there anyway to check the application is exist in the registry key.

TestApp1.exe

TestApp2.exe

TestApp3.exe

TestApp4.exe

Body: Try Get-ItemProperty -Path Registry::HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\DisallowRun


问:
atomicCAS for bool implementation
I'm trying to figure out is there a bug in the answer (now deleted) about the implementation of Cuda-like atomicCAS for bools. The code from the answer (reformatted):

```<code>static __inline__ __device__ bool atomicCAS(bool *address, bool compare, bool val)
{
    unsigned long long addr = (unsigned long long)address;
    unsigned pos = addr & 7;  // byte position within the unsigned long long
    int *int_addr = (int *)(addr - pos);  // int-aligned address
    int old = *int_addr, assumed, ival;

    do
    {
        assumed = old;
        if(val)
            ival = old | (1 << (8 * pos));
        else
            ival = old & (~((0xFFU) << (8 * pos)));
        old = atomicCAS(int_addr, assumed, ival);
    } while(assumed != old);

    return (bool)(old & ((0xFFU) << (8 * pos)));
}
</code>```

According to the documentation, atomicCAS should set *address to (*address == compare ? val : *address), but in the implementation above compare argument is never used!

The code I use to reproduce the bug:

```<code>#include <cstdio>

// atomicCAS definition here

__device__ bool b;

__global__ void kernel()
{
    b = false;
    atomicCAS(&b, true, true); // `(b == true ? true : b)`, where b is false equals to false
    printf("%d\n", b); // b is false => expected output is 0
}

int main()
{
    kernel<<<1, 1>>>();
    cudaDeviceSynchronize();
}
</code>```

The expected output is 0, but the actual output is 1.

I have a suggestion about how to fix it but am not 100% sure it's thread-safe:

```<code>static __inline__ __device__ bool atomicCAS(bool *address, bool compare, bool val)
{
    unsigned long long addr = (unsigned long long)address;
    unsigned pos = addr & 3;  // byte position within the int
    int *int_addr = (int *)(addr - pos);  // int-aligned address
    int old = *int_addr, assumed, ival;

    do
    {
        if(*address != compare) // If we expected that bool to be different, then
            break; // stop trying to update it and just return it's current value

        assumed = old;
        if(val)
            ival = old | (1 << (8 * pos));
        else
            ival = old & (~((0xFFU) << (8 * pos)));
        old = atomicCAS(int_addr, assumed, ival);
    } while(assumed != old);

    return (bool)(old & ((0xFFU) << (8 * pos)));
}
</code>```

My questions are

Is there a bug in the first code sample from the answer? If there is,

Does the last code sample fix it thread-safely?

答:
Many many thanks to @RobertCrovella; the first code sample does contain a bug, the second does fix it, but is not thread-safe (see question comments for details). The thread-safe fix:</p>

```<code>static __inline__ __device__ bool atomicCAS(bool *address, bool compare, bool val)
{
    unsigned long long addr = (unsigned long long)address;
    unsigned pos = addr & 3;  // byte position within the int
    int *int_addr = (int *)(addr - pos);  // int-aligned address
    int old = *int_addr, assumed, ival;

    bool current_value;

    do
    {
        current_value = (bool)(old & ((0xFFU) << (8 * pos)));

        if(current_value != compare) // If we expected that bool to be different, then
            break; // stop trying to update it and just return it's current value

        assumed = old;
        if(val)
            ival = old | (1 << (8 * pos));
        else
            ival = old & (~((0xFFU) << (8 * pos)));
        old = atomicCAS(int_addr, assumed, ival);
    } while(assumed != old);

    return current_value;
}
</code>```

Title: atomicCAS for bool implementation

Body:
I'm trying to figure out is there a bug in the answer (now deleted) about the implementation of Cuda-like atomicCAS for bools. The code from the answer (reformatted):

static __inline__ __device__ bool atomicCAS(bool *address, bool compare, bool val)
{
    unsigned long long addr = (unsigned long long)address;
    unsigned pos = addr & 7;  // byte position within the unsigned long long
    int *int_addr = (int *)(addr - pos);  // int-aligned address
    int old = *int_addr, assumed, ival;

    do
    {
        assumed = old;
        if(val)
            ival = old | (1 << (8 * pos));
        else
            ival = old & (~((0xFFU) << (8 * pos)));
        old = atomicCAS(int_addr, assumed, ival);
    } while(assumed != old);

    return (bool)(old & ((0xFFU) << (8 * pos)));
}

According to the documentation, atomicCAS should set *address to (*address == compare ? val : *address), but in the implementation above compare argument is never used!

The code I use to reproduce the bug:

#include <cstdio>

// atomicCAS definition here

__device__ bool b;

__global__ void kernel()
{
    b = false;
    atomicCAS(&b, true, true); // `(b == true ? true : b)`, where b is false equals to false
    printf("%d\n", b); // b is false => expected output is 0
}

int main()
{
    kernel<<<1, 1>>>();
    cudaDeviceSynchronize();
}

The expected output is 0, but the actual output is 1.

I have a suggestion about how to fix it but am not 100% sure it's thread-safe:

static __inline__ __device__ bool atomicCAS(bool *address, bool compare, bool val)
{
    unsigned long long addr = (unsigned long long)address;
    unsigned pos = addr & 3;  // byte position within the int
    int *int_addr = (int *)(addr - pos);  // int-aligned address
    int old = *int_addr, assumed, ival;

    do
    {
        if(*address != compare) // If we expected that bool to be different, then
            break; // stop trying to update it and just return it's current value

        assumed = old;
        if(val)
            ival = old | (1 << (8 * pos));
        else
            ival = old & (~((0xFFU) << (8 * pos)));
        old = atomicCAS(int_addr, assumed, ival);
    } while(assumed != old);

    return (bool)(old & ((0xFFU) << (8 * pos)));
}

My questions are

Is there a bug in the first code sample from the answer? If there is,

Does the last code sample fix it thread-safely?

Body:
Many many thanks to @RobertCrovella; the first code sample does contain a bug, the second does fix it, but is not thread-safe (see question comments for details). The thread-safe fix:

static __inline__ __device__ bool atomicCAS(bool *address, bool compare, bool val)
{
    unsigned long long addr = (unsigned long long)address;
    unsigned pos = addr & 3;  // byte position within the int
    int *int_addr = (int *)(addr - pos);  // int-aligned address
    int old = *int_addr, assumed, ival;

    bool current_value;

    do
    {
        current_value = (bool)(old & ((0xFFU) << (8 * pos)));

        if(current_value != compare) // If we expected that bool to be different, then
            break; // stop trying to update it and just return it's current value

        assumed = old;
        if(val)
            ival = old | (1 << (8 * pos));
        else
            ival = old & (~((0xFFU) << (8 * pos)));
        old = atomicCAS(int_addr, assumed, ival);
    } while(assumed != old);

    return current_value;
}


问:
How to resolve class inheritance error after interpretation in Isabelle?
I am getting an error that I don't understand in isabelle when try to build a class heirarchy after a global_interpretation.

Here is a toy non-working example to illustrate.

```<code>theory mnwe

imports Main

begin

class natop =
  fixes natop :: "nat \<Rightarrow> 'a \<Rightarrow> 'a"

definition (in natop) list_double :: "'a list \<Rightarrow> 'a list"
  where "list_double xs = map (natop 2) xs"

global_interpretation semiring_1_natop: natop "\<lambda>n x. of_nat n * x"
  defines list_double = semiring_1_natop.list_double
  .

class special_list =
  fixes speclist :: "'a list"

class double_special_list = semiring_1 + special_list +
  assumes "list_double speclist = speclist"

end
</code>```

The final class double_special_list raises the following error:

```<code>Type inference imposes additional sort constraint semiring_1 of type parameter 'a of sort type
</code>```

Huh? Class double_special_list explicitly inherits from class semiring_1 ...

Can someone please enlighten me on what I'm doing wrong?

Update:

If I drop class special_list and instead do

```<code>class double_special_list = semiring_1 +
  fixes speclist :: "'a list"
  assumes "list_double speclist = speclist"
</code>```

I get error

```<code>Type unification failed: Variable 'a::type not of sort semiring_1
</code>```

which again is a "Huh?" given the semiring_1 superclass specification.

答:
OK, the following works (at least, doesn't throw any errors), but seems weird to me with the hidden semiring_1 superclass declaration inside the fixes of class double_special_list. To be honest, I'm not really sure what the difference is between the code in my question and the code in this answer, and why the former is an error, but there you go.

```<code>theory answer

imports Main

begin

class natop =
  fixes natop :: "nat \<Rightarrow> 'a \<Rightarrow> 'a"

definition (in natop) list_double :: "'a list \<Rightarrow> 'a list"
  where "list_double xs = map (natop 2) xs"

global_interpretation semiring_1_natop: natop "\<lambda>n x. of_nat n * x"
  defines list_double = semiring_1_natop.list_double
  .

class double_special_list =
  fixes speclist :: "'a::semiring_1 list"
  assumes "list_double speclist = speclist"

lemma test:
  fixes a b c :: "'a::double_special_list"
  shows "a * (b + c) = a * b + a * c"
  by (simp add: algebra_simps)

end
</code>```

Body:
I am getting an error that I don't understand in isabelle when try to build a class heirarchy after a global_interpretation.

Here is a toy non-working example to illustrate.

theory mnwe

imports Main

begin

class natop =
  fixes natop :: "nat \<Rightarrow> 'a \<Rightarrow> 'a"

definition (in natop) list_double :: "'a list \<Rightarrow> 'a list"
  where "list_double xs = map (natop 2) xs"

global_interpretation semiring_1_natop: natop "\<lambda>n x. of_nat n * x"
  defines list_double = semiring_1_natop.list_double
  .

class special_list =
  fixes speclist :: "'a list"

class double_special_list = semiring_1 + special_list +
  assumes "list_double speclist = speclist"

end

The final class double_special_list raises the following error:

Type inference imposes additional sort constraint semiring_1 of type parameter 'a of sort type

Huh? Class double_special_list explicitly inherits from class semiring_1 ...

Can someone please enlighten me on what I'm doing wrong?

Update:

If I drop class special_list and instead do

class double_special_list = semiring_1 +
  fixes speclist :: "'a list"
  assumes "list_double speclist = speclist"

I get error

Type unification failed: Variable 'a::type not of sort semiring_1

which again is a "Huh?" given the semiring_1 superclass specification.

Body:
OK, the following works (at least, doesn't throw any errors), but seems weird to me with the hidden semiring_1 superclass declaration inside the fixes of class double_special_list. To be honest, I'm not really sure what the difference is between the code in my question and the code in this answer, and why the former is an error, but there you go.

theory answer

imports Main

begin

class natop =
  fixes natop :: "nat \<Rightarrow> 'a \<Rightarrow> 'a"

definition (in natop) list_double :: "'a list \<Rightarrow> 'a list"
  where "list_double xs = map (natop 2) xs"

global_interpretation semiring_1_natop: natop "\<lambda>n x. of_nat n * x"
  defines list_double = semiring_1_natop.list_double
  .

class double_special_list =
  fixes speclist :: "'a::semiring_1 list"
  assumes "list_double speclist = speclist"

lemma test:
  fixes a b c :: "'a::double_special_list"
  shows "a * (b + c) = a * b + a * c"
  by (simp add: algebra_simps)

end


问:
How to add Radio Button in Formik Validations Reactjs?
I am using Formik for Validating my Registration form I want to add validate gender via radio button how can I do that. I am not able to add radio button.

This is what I have done:-

```<code> const SignupSchema = Yup.object().shape({
        email: Yup.string()
          .email('Invalid email')
          .required('Required'),
        password: Yup.string()
          .min(4, 'Password Must be four characters long!')
          .max(20, 'Too Long!')
          .required('Required'),

      });
    class Register extends Component {
        render() {
            return (
                   <Formik
                     initialValues={{
                        email: '',
                        password:'',
                        gender:'',

                     }}
                     validationSchema={SignupSchema}
                     onSubmit={values => {
                       console.log(values);
                     }}
                   >
                     {({ errors, touched }) => (
                       <Form>

                         <Field style={customStyles.textfield} placeholder="Email" name="email" type="email" />
                         {errors.email && touched.email ? <div}>{errors.email}</div> : null}

                         <Field placeholder="Enter Password" name="password" type="password" />
                         {errors.password && touched.password ? <div >{errors.password}</div> : null}

                         <button type="submit">Submit</button>
                       </Form>
                     )}
                   </Formik>
             </div>
            )
        }
    }
</code>```

答:
This can be done simply but using this code below. it worked for me:
You will need to import Formik from "formik"

```<code><Formik
  initialValues={{
     email: '',
     password:'',
     gender:'',
   }}
  // validations
   validationSchema={SignupSchema}
   onSubmit={values => { console.log(values); }}
  >
     {(formik) => (
          <Form onSubmit={formik.handleSubmit}>
              //Your Other inputs........
              <div className="custom-control">
                 <input
                    id="male"
                    type="radio"
                    value="male"
                    name='gender'
                    onChange={formik.handleChange}
                    defaultChecked={formik.values.gender=== "male"}
                  />
                  <label
                     className="custom-control-label"
                     htmlFor="male"
                   >
                     Male
                   </label>
              </div>
              <div className="custom-control">
                 <input
                    id="female"
                    type="radio"
                    value="female"
                    name='gender'
                    onChange={formik.handleChange}
                    defaultChecked={formik.values.gender=== "female"}
                  />
                 <label
                   className="custom-control-label"
                   htmlFor="female"
                  >
                    Female
                 </label>
              </div>
              //Your Other inputs......
             <button type="submit">Submit</button>
          </Form>
      )}
  </Formik>
</code>```

Body:
I am using Formik for Validating my Registration form I want to add validate gender via radio button how can I do that. I am not able to add radio button.

This is what I have done:-

 const SignupSchema = Yup.object().shape({
        email: Yup.string()
          .email('Invalid email')
          .required('Required'),
        password: Yup.string()
          .min(4, 'Password Must be four characters long!')
          .max(20, 'Too Long!')
          .required('Required'),

      });
    class Register extends Component {
        render() {
            return (
                   <Formik
                     initialValues={{
                        email: '',
                        password:'',
                        gender:'',

                     }}
                     validationSchema={SignupSchema}
                     onSubmit={values => {
                       console.log(values);
                     }}
                   >
                     {({ errors, touched }) => (
                       <Form>

                         <Field style={customStyles.textfield} placeholder="Email" name="email" type="email" />
                         {errors.email && touched.email ?
{errors.email}
 : null}

                         <Field placeholder="Enter Password" name="password" type="password" />
                         {errors.password && touched.password ?
{errors.password}
 : null}

                         <button type="submit">Submit</button>
                       </Form>
                     )}
                   </Formik>

            )
        }
    }

Body:
This can be done simply but using this code below. it worked for me:
You will need to import Formik from "formik"

<Formik
  initialValues={{
     email: '',
     password:'',
     gender:'',
   }}
  // validations
   validationSchema={SignupSchema}
   onSubmit={values => { console.log(values); }}
  >
     {(formik) => (
          <Form onSubmit={formik.handleSubmit}>
              //Your Other inputs........
              <div className="custom-control">
                 <input
                    id="male"
                    type="radio"
                    value="male"
                    name='gender'
                    onChange={formik.handleChange}
                    defaultChecked={formik.values.gender=== "male"}
                  />
                  <label
                     className="custom-control-label"
                     htmlFor="male"
                   >
                     Male
                   </label>
              </div>
              <div className="custom-control">
                 <input
                    id="female"
                    type="radio"
                    value="female"
                    name='gender'
                    onChange={formik.handleChange}
                    defaultChecked={formik.values.gender=== "female"}
                  />
                 <label
                   className="custom-control-label"
                   htmlFor="female"
                  >
                    Female
                 </label>
              </div>
              //Your Other inputs......
             <button type="submit">Submit</button>
          </Form>
      )}
  </Formik>


问:
Throttle HTTP request in Java Servlet
In a java servlet, how can I throttle http requests coming from users based on the client's IP address?  I do not want to serve more than X requests per second coming from a particular source IP address where X is configurable and having practical values in [0.1; 10] range (from 1 request in 10 sec to 10 requests per sec).</p>

答: Use a servlet filter: if you're on Jetty 7.0 or higher there is this</p>

Title: Throttle HTTP request in Java Servlet


问:
JavaScript CSS Progress bar for a VoIP test
I basically have two divs, one being absolutely placed over the other. I also have a variable from an application that represents the percent of a VoIP test completeness. Now I need to have the progress bar call the percent variable using JavaScript.

I have been told I need an asynchronously update the progress bar but im unsure how to do that. im aware there are many ways to do this. I am still learning JavaScript and need an example to work with. I have tried a number of what I would assume would work but what I post here is just the most recent attempt.

I am referencing this YouTube example/tutorial, but obviously I am not using setInterval() because I want the width based on the variable. I have the test run on a button's click and felt that it was unnecessary to include.

//Variable for the test's percent. it provides just a number in increments of 5

<param name="js-prog" value="progress($PROGRESS$)">\

 function progress(pRess) {
      const pRessBar = document.getElementsByClassName('ressBar');
      const computedStyle = getComputedStyle(pRessBar);
      const styleWidth = parseFloat(computedStyle.getPropertyValue('pwidth')) || 0
      pRessBar.style.setproperty('pwidth', styleWidth + pRess)
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.ressBar {
  position: relative;
  width: 500px;
  height: 3em;
  background-color: #111;
  margin-left: auto;
  margin-right: auto;
  border-radius: 15px;
  color: white;
}
.ressBar::before {
  content: attr(data-label);
  display: flex;
  align-items: center;
  position: absolute;
  left: .5em;
  top: .5em;
  bottom: .5em;
  width: calc(var(pwidth, 0) * 1%);
  min-width: .1rem;
  max-width: calc(100% - 1em);
  background-color: #069;
  border-radius: 15px;
  padding: 1em;
}</code>```

`

```

答:
css variables should always have double dash at beginning of their names.

Personally, I find the example twisted on youtube,

for the same result, I see things like that:

const pRessBar = document.getElementById('ressBar')

function setRessBar_percent(val) { // 0 <= val <= 100
  pRessBar.style.setProperty('--pwidth', `${val}%`)
  pRessBar.dataset.label = (val<100)? 'Loading...' : 'Loading completed ;-)'
}

/* test part */
inSiz.oninput=_=>
  {
  inSiz.nextSibling.textContent = `${inSiz.value}%`
  setRessBar_percent(inSiz.value)
  }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#ressBar {
  box-sizing: border-box;
  position: relative;
  width: 500px;
  --pwidth: 50%;
  height: 3em;
  background-color: #111;
  margin: 1em auto;
  border-radius: 1.5em;
  color: white;
  border: .5em solid #111; ; /* try red color */
  overflow: hidden;
}
#ressBar::before {
  position: absolute;
  top: 0;
  left: calc( -100% + var(--pwidth) );
  content: '';
  width: 100%;
  height: 100%;
  background-color: #069;
  border-radius: 1em;
}
#ressBar::after {
  content: attr(data-label);
  position: absolute;
  left: 1em;
  top: 0;
  height: 2em;
  line-height: 2em;
}

/* test part */

#inSiz {
margin : 1em;
width: 200px;
}</code>```

play with this range :

<input id="inSiz" type="range" value="50" min="0" max="100" step="1">50% (supposed value for the progress bar)

 to test the appearance of the progress bar
```
</div>
</div>
</p>
<blockquote>
<p>let me pick your brain and try to pick this apart.</p>
</blockquote>
<p>no problemo amigo ;)</p>
<blockquote>
<ol>
<li>double dash makes sense but I thought that JavaScript doesn't like dashes or other certain symbols.</li>
</ol>
</blockquote>
<p>it's just in the doc, and for javascript it's not a symbol or anything but just a string</p>
<p>Using CSS custom properties (variables) ==doc== or for ==JS part==</p>
<blockquote>
<ol start="2">
<li>so #ressBar::before is for the width that is being changed and #ressBar::after is for the text "Loading..."?</li>
</ol>
</blockquote>
<p>the text "Loading ..." is in the <code>::after</code>,<br />
while the progress bar is in the <code>::before</code>, so that it appears below.</p>
<p>Putting the text and the progress bar together is a bad idea:<br />
if the progress is zero then the text cannot be displayed in a null space</p>
<blockquote>
<ol start="3">
<li>is there a reason why the calculation for the "width" is under left vs right?</li>
</ol>
</blockquote>
<p>in my code the blue bar is <code>width: 100%</code> of it's parent.<br />
It just "moves" more or less to the right depending on the progress value requested.</p>
<p>the excess part is to the <code>left</code> in negative value of its parent element (<code>#ressBar {</code> which has as rule css: <code>overflow: hidden;</code><br />
two advantages:<br />
1- you just make the size you want on the parent with no other css change<br />
2- the blue bar has no css problems with the <code>border-radius: 1em;</code> when it size is less than 1em</p>
<blockquote>
<ol start="4">
<li>I don't understand how the JavaScript portion is working. I understand pRessBar but I don't understand your comment referencing 0 <= val <= 0 OR the syntax for setProperty ``` '${val}%' ``

0 <= val <= 0 is a mistake and should be  0 <= val <= 100  that's say val argument should be between 0 and 100

${val}% it's a normal use of arguments in Template literals  if val==45 it's made 45% (% is just a character like another)

Body:
I basically have two divs, one being absolutely placed over the other. I also have a variable from an application that represents the percent of a VoIP test completeness. Now I need to have the progress bar call the percent variable using JavaScript.

I have been told I need an asynchronously update the progress bar but im unsure how to do that. im aware there are many ways to do this. I am still learning JavaScript and need an example to work with. I have tried a number of what I would assume would work but what I post here is just the most recent attempt.

I am referencing this YouTube example/tutorial, but obviously I am not using setInterval() because I want the width based on the variable. I have the test run on a button's click and felt that it was unnecessary to include.

//Variable for the test's percent. it provides just a number in increments of 5

<param name="js-prog" value="progress($PROGRESS$)">\

 function progress(pRess) {
      const pRessBar = document.getElementsByClassName('ressBar');
      const computedStyle = getComputedStyle(pRessBar);
      const styleWidth = parseFloat(computedStyle.getPropertyValue('pwidth')) || 0
      pRessBar.style.setproperty('pwidth', styleWidth + pRess)
}

.ressBar {
  position: relative;
  width: 500px;
  height: 3em;
  background-color: #111;
  margin-left: auto;
  margin-right: auto;
  border-radius: 15px;
  color: white;
}
.ressBar::before {
  content: attr(data-label);
  display: flex;
  align-items: center;
  position: absolute;
  left: .5em;
  top: .5em;
  bottom: .5em;
  width: calc(var(pwidth, 0) * 1%);
  min-width: .1rem;
  max-width: calc(100% - 1em);
  background-color: #069;
  border-radius: 15px;
  padding: 1em;
}

`

Body:
css variables should always have double dash at beginning of their names.

Personally, I find the example twisted on youtube,

for the same result, I see things like that:

const pRessBar = document.getElementById('ressBar')

function setRessBar_percent(val) { // 0 <= val <= 100
  pRessBar.style.setProperty('--pwidth', `${val}%`)
  pRessBar.dataset.label = (val<100)? 'Loading...' : 'Loading completed ;-)'
}

/* test part */
inSiz.oninput=_=>
  {
  inSiz.nextSibling.textContent = `${inSiz.value}%`
  setRessBar_percent(inSiz.value)
  }

#ressBar {
  box-sizing: border-box;
  position: relative;
  width: 500px;
  --pwidth: 50%;
  height: 3em;
  background-color: #111;
  margin: 1em auto;
  border-radius: 1.5em;
  color: white;
  border: .5em solid #111; ; /* try red color */
  overflow: hidden;
}
#ressBar::before {
  position: absolute;
  top: 0;
  left: calc( -100% + var(--pwidth) );
  content: '';
  width: 100%;
  height: 100%;
  background-color: #069;
  border-radius: 1em;
}
#ressBar::after {
  content: attr(data-label);
  position: absolute;
  left: 1em;
  top: 0;
  height: 2em;
  line-height: 2em;
}

/* test part */

#inSiz {
margin : 1em;
width: 200px;
}

<div Id="ressBar" data-label="Loading..."></div>

<!-- test part -->
<hr>
<p>play with this range : <p>
<input id="inSiz" type="range" value="50" min="0" max="100" step="1"><span>50%</span> (supposed value for the progress bar)
<p> to test the appearance of the progress bar<p>

let me pick your brain and try to pick this apart.

no problemo amigo ;)

double dash makes sense but I thought that JavaScript doesn't like dashes or other certain symbols.

it's just in the doc, and for javascript it's not a symbol or anything but just a string

Using CSS custom properties (variables) ==doc== or for ==JS part==

so #ressBar::before is for the width that is being changed and #ressBar::after is for the text "Loading..."?

the text "Loading ..." is in the ::after,

while the progress bar is in the ::before, so that it appears below.

Putting the text and the progress bar together is a bad idea:

if the progress is zero then the text cannot be displayed in a null space

is there a reason why the calculation for the "width" is under left vs right?

in my code the blue bar is width: 100% of it's parent.

It just "moves" more or less to the right depending on the progress value requested.

the excess part is to the left in negative value of its parent element (#ressBar { which has as rule css: overflow: hidden;

two advantages:

1- you just make the size you want on the parent with no other css change

2- the blue bar has no css problems with the border-radius: 1em; when it size is less than 1em

I don't understand how the JavaScript portion is working. I understand pRessBar but I don't understand your comment referencing 0 <= val <= 0 OR the syntax for setProperty ``` '${val}%' ``

0 <= val <= 0 is a mistake and should be  0 <= val <= 100  that's say val argument should be between 0 and 100

${val}% it's a normal use of arguments in Template literals  if val==45 it's made 45% (% is just a character like another)


问:
Is it possible to override font size limit on labels in R plotly bar chart?
I have a plotly grouped bar chart with labels. I can change the font size on the labels, but plotly won't allow the fonts to get exceed a certain limit that appears to be determined by the width/height of the bars. This becomes a problem when there are a larger number of groups and/or values to graph. In some of these cases, the text won't become larger than, for example, 8 point font. Is there a way to exceed this limitation?

Here's some sample code:

```<code>library(dplyr)
library(plotly)
data.frame(Desc = c("A", "A", "B", "B", "C", "C"),
           Group = c("Group1", "Group2", "Group1", "Group2", "Group1", "Group2"),
           Value = c(5, 4, 6, 4, 5, 3)) %>%
  plotly::plot_ly(data = .) %>%
  plotly::add_trace(x = ~Value,
                    y = ~Desc,
                    color = ~Group,
                    type = 'bar',
                    text = ~Value,
                    textposition = "outside",
                    textfont = list(size = 10), # size is defined here
                    )
</code>```

This chart, with font size of 10, outputs:

If I change the font to 30 point, then:

Finally, at 50 point (where it is unchanged relative to 30 point):

答:
You can use layout and set uniformtext to change the text size. I increased the x axis range to make the large numbers fit.

suppressPackageStartupMessages({
library(dplyr);
library(plotly)})
data.frame(Desc = c("A", "A", "B", "B", "C", "C"),
           Group = c("Group1", "Group2", "Group1", "Group2", "Group1", "Group2"),
           Value = c(5, 4, 6, 4, 5, 3)) %>%
    plotly::plot_ly(data = .) %>%
    plotly::add_trace(x = ~Value,
                      y = ~Desc,
                      color = ~Group,
                      type = 'bar',
                      text = ~Value,
                      textposition = "outside"
    ) %>% layout(xaxis=list(range=c(0, 7)),
                 uniformtext=list(minsize=80, mode='show'))
```

Created on 2020-05-29 by the reprex package (v0.3.0)

Body:
I have a plotly grouped bar chart with labels. I can change the font size on the labels, but plotly won't allow the fonts to get exceed a certain limit that appears to be determined by the width/height of the bars. This becomes a problem when there are a larger number of groups and/or values to graph. In some of these cases, the text won't become larger than, for example, 8 point font. Is there a way to exceed this limitation?

Here's some sample code:

library(dplyr)
library(plotly)
data.frame(Desc = c("A", "A", "B", "B", "C", "C"),
           Group = c("Group1", "Group2", "Group1", "Group2", "Group1", "Group2"),
           Value = c(5, 4, 6, 4, 5, 3)) %>%
  plotly::plot_ly(data = .) %>%
  plotly::add_trace(x = ~Value,
                    y = ~Desc,
                    color = ~Group,
                    type = 'bar',
                    text = ~Value,
                    textposition = "outside",
                    textfont = list(size = 10), # size is defined here
                    )

This chart, with font size of 10, outputs:

If I change the font to 30 point, then:

Finally, at 50 point (where it is unchanged relative to 30 point):

Body:
You can use layout and set uniformtext to change the text size. I increased the x axis range to make the large numbers fit.

suppressPackageStartupMessages({
library(dplyr);
library(plotly)})
data.frame(Desc = c("A", "A", "B", "B", "C", "C"),
           Group = c("Group1", "Group2", "Group1", "Group2", "Group1", "Group2"),
           Value = c(5, 4, 6, 4, 5, 3)) %>%
    plotly::plot_ly(data = .) %>%
    plotly::add_trace(x = ~Value,
                      y = ~Desc,
                      color = ~Group,
                      type = 'bar',
                      text = ~Value,
                      textposition = "outside"
    ) %>% layout(xaxis=list(range=c(0, 7)),
                 uniformtext=list(minsize=80, mode='show'))

Created on 2020-05-29 by the reprex package (v0.3.0)


问:
overriding the binary predicate when doing a lexicographical compare in ruby
If I have two arrays, a1 and a2 in ruby, to do a lexicographical comparison I do a1 <=> a2.

Is there a way to override how ruby compares each element?

What I'd like to do is something like

```<code>a1.collect(&:name) <=> a2.collect(&:name)
</code>```

without the collect because that's creating two new arrays (e.g. if we're sorting an array of arrays, a ton of time would be spent in the allocator).

I could write my own lexicographical compare function, but that seems very anti-ruby and I'm not sure if it would be faster because the the amount of time spent in ruby space (vs C space).

edit: another example would be for doing a case insensitive lexicographical compare of two arrays of strings.

答:
Pass a custom block to sort_by instead:

```<code>meta_array = [a1, a2]
meta_array.sort_by do |arr|
  arr.collect(&:name)
end
</code>```

Body:
If I have two arrays, a1 and a2 in ruby, to do a lexicographical comparison I do a1 <=> a2.

Is there a way to override how ruby compares each element?

What I'd like to do is something like

a1.collect(&:name) <=> a2.collect(&:name)

without the collect because that's creating two new arrays (e.g. if we're sorting an array of arrays, a ton of time would be spent in the allocator).

I could write my own lexicographical compare function, but that seems very anti-ruby and I'm not sure if it would be faster because the the amount of time spent in ruby space (vs C space).

edit: another example would be for doing a case insensitive lexicographical compare of two arrays of strings.

Body:
Pass a custom block to sort_by instead:

meta_array = [a1, a2]
meta_array.sort_by do |arr|
  arr.collect(&:name)
end


问:
How to update React state once per iteration of a loop
I have built a maze solving python program, and I am trying to make a React app to visualize it. I have successfully connected the python side and the basic React side I have, and I can visualize the maze portion of the program. The issue is the agent that solves the maze will just appear over the goal instead of working its way through the maze

The maze is a grid with obstacles randomly placed on it (Pictured Here)
Maze with Obstacles

I am trying to get the agent, which would be a blue square, to move its way through the maze one tile at a time, about every 100ms. The data the React side gets from the python side is as follows:

Python passes the initial maze matrix with the goal and the obstacles only

Python then passes an array holding each of the coordinates that the agent moves to

EX. [[0,0],[0,1],[1,1],[2,1]]

React displays the initial maze matrix with the obstacles and goals, but when I try to iterate through the array of coordinates for the agent, it just displays every single tile where the agent moved all at once at the end (Pictured Here)After image with agent positions shown This is a new maze generation, the obstacles are not the same as the first image

I am aware that the React state only gets updated once, at the end of the loop. I want to find a way to make it update once per iteration, with the maze resetting to the original state at the beginning of every iteration, followed by the agent being placed. What I believe to be the relevant code is below

Start Maze Action (Occurs after user presses a button)

```<code>startMaze = () => {
    this.state.apiClient.startMaze().then((data) => this.moveAgent(data));
};
</code>```

Move Agent Function (Note: There is an initial matrix and a current matrix. Current matrix is what I have holding the position of the agent with the goal and the obstacles, initial matrix just has the goal and the obstacles)

```<code>moveAgent = (data) => {
    data.map((coords) => {
        var newMatrix = this.state.matrix;
        newMatrix[coords[0]][coords[1]] = 2;
        this.setState({ currentMatrix: newState });
        sleep(1000);
    });
};
</code>```

If there's anything else needed to solve the issue, just let me know and I'll add it.

答:
I guess you could use setTimeout to fix your issue. Maybe something like this:

```<code>moveAgent = (data) => {
   if(data.length < 1) return;

    var coords = data.shift();
    var newMatrix = this.state.matrix;
    newMatrix[coords[0]][coords[1]] = 2;
    this.setState({ currentMatrix: newState });
    setTimeout(() => { moveAgent(data); }, 1000);
};
</code>```

sleep does not exist in JS. So what we use here is setTimeout which calls a function after a given time (here 1000ms, so 1 second). And we use it to call the function again, using and removing the first element of the array each time.

Body:
I have built a maze solving python program, and I am trying to make a React app to visualize it. I have successfully connected the python side and the basic React side I have, and I can visualize the maze portion of the program. The issue is the agent that solves the maze will just appear over the goal instead of working its way through the maze

The maze is a grid with obstacles randomly placed on it (Pictured Here)
Maze with Obstacles

I am trying to get the agent, which would be a blue square, to move its way through the maze one tile at a time, about every 100ms. The data the React side gets from the python side is as follows:

Python passes the initial maze matrix with the goal and the obstacles only

Python then passes an array holding each of the coordinates that the agent moves to

EX. [[0,0],[0,1],[1,1],[2,1]]

React displays the initial maze matrix with the obstacles and goals, but when I try to iterate through the array of coordinates for the agent, it just displays every single tile where the agent moved all at once at the end (Pictured Here)After image with agent positions shown This is a new maze generation, the obstacles are not the same as the first image

I am aware that the React state only gets updated once, at the end of the loop. I want to find a way to make it update once per iteration, with the maze resetting to the original state at the beginning of every iteration, followed by the agent being placed. What I believe to be the relevant code is below

Start Maze Action (Occurs after user presses a button)

startMaze = () => {
    this.state.apiClient.startMaze().then((data) => this.moveAgent(data));
};

Move Agent Function (Note: There is an initial matrix and a current matrix. Current matrix is what I have holding the position of the agent with the goal and the obstacles, initial matrix just has the goal and the obstacles)

moveAgent = (data) => {
    data.map((coords) => {
        var newMatrix = this.state.matrix;
        newMatrix[coords[0]][coords[1]] = 2;
        this.setState({ currentMatrix: newState });
        sleep(1000);
    });
};

If there's anything else needed to solve the issue, just let me know and I'll add it.

Body:
I guess you could use setTimeout to fix your issue. Maybe something like this:

moveAgent = (data) => {
   if(data.length < 1) return;

    var coords = data.shift();
    var newMatrix = this.state.matrix;
    newMatrix[coords[0]][coords[1]] = 2;
    this.setState({ currentMatrix: newState });
    setTimeout(() => { moveAgent(data); }, 1000);
};

sleep does not exist in JS. So what we use here is setTimeout which calls a function after a given time (here 1000ms, so 1 second). And we use it to call the function again, using and removing the first element of the array each time.


问:
What is the JPA CriteriaBuilder way for filtering on Sub Classes?
JPA 2.0 provided a means to filter by subclass using the JPQL expressions TYPE, for example :

```<code>SELECT e
FROM entity e
WHERE TYPE(e) = :entityType
</code>```

where parameter entityType would be the value of the discriminator column.

What is the recommended way for achieving the same thing with the JPA criteria builder, considering the discriminator column appears to be off limits?

I'm using JPA 2.1 and so far the only solution that seems adequate is mapping the discriminator column as a read only field within the Java entity, but I'm not sure if this is a supported feature.

答:
If you just want to check the exact type of an expression, use Path.type() as described above.

But if you want the Criteria API equivalent of Java's instanceof operator, the only way to do it is by explicitly listing all of the sub-types Class objects. But this makes your code brittle against future refactoring, etc.

Here's a utility class providing a JPAUtil.instanceOf() method that solves that problem:

/**
 * JPA utility methods.
 */
public final class JPAUtil {

    private JPAUtil() {
    }

    /**
     * Build an IN predicate from a collection of possible values.
     */
    public static <T> Predicate in(CriteriaBuilder builder, Expression<T> expr, Iterable<? extends T> values) {
        final CriteriaBuilder.In<T> in = builder.in(expr);
        values.forEach(in::value);
        return in;
    }

    /**
     * Build an "instanceof" predicate.
     */
    @SuppressWarnings("unchecked")
    public static Predicate instanceOf(EntityManager entityManager, Path<?> path, Class<?> type) {
        final Set<Class<?>> subtypes = entityManager.getMetamodel().getManagedTypes().stream()
          .map(ManagedType::getJavaType)
          .filter(type::isAssignableFrom)
          .collect(Collectors.toSet());
        return JPAUtil.in(entityManager.getCriteriaBuilder(), (Expression<Class<?>>)path.type(), subtypes);
    }
}
```

Body:
JPA 2.0 provided a means to filter by subclass using the JPQL expressions TYPE, for example :

SELECT e
FROM entity e
WHERE TYPE(e) = :entityType

where parameter entityType would be the value of the discriminator column.

What is the recommended way for achieving the same thing with the JPA criteria builder, considering the discriminator column appears to be off limits?

I'm using JPA 2.1 and so far the only solution that seems adequate is mapping the discriminator column as a read only field within the Java entity, but I'm not sure if this is a supported feature.


问:
C# Properties.Settings missing
I messed up the C# Properties. I worked on my project and changed a boolean in my Properties (Using the VS GUI). I simply changed it from True to False, at least I didn't notice anything else.

Now my whole project is broken.
I got around 200 errors messages all the same:

Severity Code Description Project File Line Suppression State

  Error CS0234 The type or namespace name "Settings" does not exist in the "MyProject.Properties" namespace. (An assembly reference may be missing.)

Also if I type Properties.S it doesn't show "Settings" anymore. Only Resources. It's gone.

Anyone has a idea how to fix this?

PS: I tried to revert the latest changes using a shortcut, but it didn't help.

答: I fixed it. I luckily had a backup of my Properties folder. I simply replaced it. I will leave the question here, maybe someone could still give tips on this for other users, who may don't have any backup of their Properties folder.</p>

Title: C# Properties.Settings missing


问:
mysql query - clash between not in and/or
I'm trying to get all my products , from A specific categories and without some products from those categories .

i did this query:

```<code>SELECT `ps_product`.`id_product`,`ps_product_lang`.`name`
FROM `ps_product`, `ps_product_lang`
WHERE
    `ps_product`.`id_product` = `ps_product_lang`.`id_product`
    AND `ps_product`.`id_manufacturer` NOT IN (3,7,10,11,13,14,19,22,23,24,25,30,31,32,33,34,37,38,41,42,43,44,45,46,47,48,49,50)
    AND `ps_product_lang`.`name` not in ( '%OLP%' ,'%LicSAPk%' ,'%SPLA%','%SA OLP%')
</code>```

The problem is that i'm still getting products with the string 'SPLA' or 'SA OLP' - because the NOT IN clash with the categories

How to solve it ?

答:
As a starter: always use standard join (with the on keyword) rather than old-school implicit joins (with commas in the from clause): this old syntax has fallen out of favor decades ago and should not be used in new code.

Then: you need multiple like conditions rather than in. If you have many values, regexp matching comes handy to shorten the syntax:

```<code>SELECT p.id_product,pl.name
FROM ps_product p
INNER JOIN ps_product_lang pl ON p.id_product = pl.id_product
WHERE
    p.id_manufacturer not in (3, 7, 10, 11, 13, 14, 19, 22, 23, 24, 25, 30, 31, 32, 33, 34, 37, 38, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50)
    AND pl.name not regexp 'OLP|LicSAPk|SPLA|SA OLP'
</code>```

Note that I used table aliases to shorten the syntax. I also remove the backticks around identifiers: most of the time they are not needed, and just make the query less easy to follow (you can add them back if this causes issues).

Body:
I'm trying to get all my products , from A specific categories and without some products from those categories .

i did this query:

SELECT `ps_product`.`id_product`,`ps_product_lang`.`name`
FROM `ps_product`, `ps_product_lang`
WHERE
    `ps_product`.`id_product` = `ps_product_lang`.`id_product`
    AND `ps_product`.`id_manufacturer` NOT IN (3,7,10,11,13,14,19,22,23,24,25,30,31,32,33,34,37,38,41,42,43,44,45,46,47,48,49,50)
    AND `ps_product_lang`.`name` not in ( '%OLP%' ,'%LicSAPk%' ,'%SPLA%','%SA OLP%')

The problem is that i'm still getting products with the string 'SPLA' or 'SA OLP' - because the NOT IN clash with the categories

How to solve it ?

Body:
As a starter: always use standard join (with the on keyword) rather than old-school implicit joins (with commas in the from clause): this old syntax has fallen out of favor decades ago and should not be used in new code.

Then: you need multiple like conditions rather than in. If you have many values, regexp matching comes handy to shorten the syntax:

SELECT p.id_product,pl.name
FROM ps_product p
INNER JOIN ps_product_lang pl ON p.id_product = pl.id_product
WHERE
    p.id_manufacturer not in (3, 7, 10, 11, 13, 14, 19, 22, 23, 24, 25, 30, 31, 32, 33, 34, 37, 38, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50)
    AND pl.name not regexp 'OLP|LicSAPk|SPLA|SA OLP'

Note that I used table aliases to shorten the syntax. I also remove the backticks around identifiers: most of the time they are not needed, and just make the query less easy to follow (you can add them back if this causes issues).


问:
How to utilize host caches in a singularity build?
I'm looking for ways to optimize the build time of our singularity HPC containers. I know that I can save some time by building them layer by layer. But still, there is room for optimization.

What I'm interested in is using/caching whatever makes sense on the host system.

CCache for C++ build artifact caching

git repo cloning

APT package downloads

I did some experiments but haven't suceeded in any point.

What I found so far:

CCache

I install ccache in the container and instruct the build system to use it. I know that because I'm running singularity build with sudo, the cache would be under /root. But after running the build, /root/.ccache is empty. I verified the generated CMake build files, and they definitely use ccache.

I even created a test recipe containing a %post

```<code>touch "$HOME/.ccache/test"
</code>```

but the test file did not appear anywhere on the host system (not in /root and not in my user's home). Does the build step mount a container-backed directory to /root instead of the host's root dir?

Is there something more needed to be done to utilize ccache?

Git

People suggest running e.g. git-cache-http-server (https://stackoverflow.com/a/43643622/1076564) and using git config --global url."http://gitcache:1234/".insteadOf https://.

Since singularity can read parts of the host filesystem, I think there could even be a way to have it working without a proxy program. However, if the host git repos are not inside $HOME or /tmp, how can singularity access them during build? singularity build has no --bind flag to specify additional mount directories. And using the %files section in recipe sounds inefficient - to copy everything each time the build is run.

APT

People suggest to use e.g. squid-deb-proxy (https://gist.github.com/dergachev/8441335). Again, since singularity is able to read host filesystem files, I'd like to just utilize the host's /var/cache/apt. But /var is not mounted to the container by default. So the same question again - how do I mount /var/cache/apt during container build time. And is it a good idea overall? Wouldn't it damage the APT cache of the host, given both host and container are based on the same version of Ubuntu and architecture?

Or does singularity do some clever APT caching itself? I've just noticed it downloaded 420 MB of packages in 25 seconds, which is possible on my connection, but not very probable given the standard speed of ubuntu mirrors.

Edit: I've created an issue on singularity repo: https://github.com/hpcng/singularity/issues/5352 .

答:
As far as I know, there is no mechanism of caching the singularity build when building from a definition file. You can cache the download of the base image, but that's it.

There is a GitHub issue about this, where one of the main developers of Singularity gave the following reply:

You can build a Singularity container from an existing container on disk. So you could build your base container and save it and then modify the def file to build from the existing container to save time while you prototype.

But since Singularity does not create layers there is really no way to implement this as Docker does.

One point about your question:

I know that I can save some time by building them layer by layer

Singularity does not have a concept of layers, so this does not apply here. Docker uses layers, and those are cached.

The workflow I typically follow when building Singularity images is to first create a Docker image from a Dockerfile and then convert that to a Singularity image. The Docker build step has caching, so that might be useful to you.

```<code># Build Docker image
docker build --tag my_image:latest .
# Convert to Singularity format
sudo singularity build my_image.sif docker-daemon://my_image:latest
</code>```

Body:
I'm looking for ways to optimize the build time of our singularity HPC containers. I know that I can save some time by building them layer by layer. But still, there is room for optimization.

What I'm interested in is using/caching whatever makes sense on the host system.

CCache for C++ build artifact caching

git repo cloning

APT package downloads

I did some experiments but haven't suceeded in any point.

What I found so far:

CCache

I install ccache in the container and instruct the build system to use it. I know that because I'm running singularity build with sudo, the cache would be under /root. But after running the build, /root/.ccache is empty. I verified the generated CMake build files, and they definitely use ccache.

I even created a test recipe containing a %post

touch "$HOME/.ccache/test"

but the test file did not appear anywhere on the host system (not in /root and not in my user's home). Does the build step mount a container-backed directory to /root instead of the host's root dir?

Is there something more needed to be done to utilize ccache?

Git

People suggest running e.g. git-cache-http-server (https://stackoverflow.com/a/43643622/1076564) and using git config --global url."http://gitcache:1234/".insteadOf https://.

Since singularity can read parts of the host filesystem, I think there could even be a way to have it working without a proxy program. However, if the host git repos are not inside $HOME or /tmp, how can singularity access them during build? singularity build has no --bind flag to specify additional mount directories. And using the %files section in recipe sounds inefficient - to copy everything each time the build is run.

APT

People suggest to use e.g. squid-deb-proxy (https://gist.github.com/dergachev/8441335). Again, since singularity is able to read host filesystem files, I'd like to just utilize the host's /var/cache/apt. But /var is not mounted to the container by default. So the same question again - how do I mount /var/cache/apt during container build time. And is it a good idea overall? Wouldn't it damage the APT cache of the host, given both host and container are based on the same version of Ubuntu and architecture?

Or does singularity do some clever APT caching itself? I've just noticed it downloaded 420 MB of packages in 25 seconds, which is possible on my connection, but not very probable given the standard speed of ubuntu mirrors.

Edit: I've created an issue on singularity repo: https://github.com/hpcng/singularity/issues/5352 .

Body:
As far as I know, there is no mechanism of caching the singularity build when building from a definition file. You can cache the download of the base image, but that's it.

There is a GitHub issue about this, where one of the main developers of Singularity gave the following reply:

You can build a Singularity container from an existing container on disk. So you could build your base container and save it and then modify the def file to build from the existing container to save time while you prototype.

But since Singularity does not create layers there is really no way to implement this as Docker does.

One point about your question:

I know that I can save some time by building them layer by layer

Singularity does not have a concept of layers, so this does not apply here. Docker uses layers, and those are cached.

The workflow I typically follow when building Singularity images is to first create a Docker image from a Dockerfile and then convert that to a Singularity image. The Docker build step has caching, so that might be useful to you.

# Build Docker image
docker build --tag my_image:latest .
# Convert to Singularity format
sudo singularity build my_image.sif docker-daemon://my_image:latest


问:
How to use GenericArray with a limited range of length that can be detected at compile time?
For example,

struct Foo<T, N: ArrayLength<T>> {
    data: GenericArray<T, N>
}
```

I want the length of the data array to be limited within a range like 100 to 1024 bytes. Then, if the Foo is used like let f: Foo<u8, generic_array::typenum::U8> = Foo {data: GenericArray::default()};, it will cause a compilation error.

答:
I played around a little with typenum, this works:

```<code>use generic_array::{ArrayLength, GenericArray};
use typenum::{IsGreaterOrEqual, IsLessOrEqual, Same, B1, U100, U1024, U99};

struct Foo<T, N>
where
    N: ArrayLength<T>,
    N: IsGreaterOrEqual<U100, Output = True>,
    N: IsLessOrEqual<U1024, Output = True>,
{
    data: GenericArray<T, N>,
}

fn main() {
    let f: Foo<u8, U100> = Foo {
        data: GenericArray::default(),
    };
    // Does not compile
    let f: Foo<u8, U99> = Foo {
        data: GenericArray::default(),
    };
}
</code>```

The IsGreaterOrEqual<M> etc. traits, confusingly, are implemented even when N < M. You have to get their result by looking at the associated Output type. If it is B1 or its synonym True, then N is indeed greater than or equal to M.

You might try to write a trait bound like <N as IsGreaterOrEqual<U100>>::Output == B1, but that's not possible. You can constrain an associated type either like in the code example, or by using a helper trait in typenum, Same: <N as IsGreaterOrEqual<U100>>::Output: Same<B1>.

Body:
For example,

struct Foo<T, N: ArrayLength<T>> {
    data: GenericArray<T, N>
}

I want the length of the data array to be limited within a range like 100 to 1024 bytes. Then, if the Foo is used like let f: Foo<u8, generic_array::typenum::U8> = Foo {data: GenericArray::default()};, it will cause a compilation error.

Body:
I played around a little with typenum, this works:

use generic_array::{ArrayLength, GenericArray};
use typenum::{IsGreaterOrEqual, IsLessOrEqual, Same, B1, U100, U1024, U99};

struct Foo<T, N>
where
    N: ArrayLength<T>,
    N: IsGreaterOrEqual<U100, Output = True>,
    N: IsLessOrEqual<U1024, Output = True>,
{
    data: GenericArray<T, N>,
}

fn main() {
    let f: Foo<u8, U100> = Foo {
        data: GenericArray::default(),
    };
    // Does not compile
    let f: Foo<u8, U99> = Foo {
        data: GenericArray::default(),
    };
}

The IsGreaterOrEqual<M> etc. traits, confusingly, are implemented even when N < M. You have to get their result by looking at the associated Output type. If it is B1 or its synonym True, then N is indeed greater than or equal to M.

You might try to write a trait bound like <N as IsGreaterOrEqual<U100>>::Output == B1, but that's not possible. You can constrain an associated type either like in the code example, or by using a helper trait in typenum, Same: <N as IsGreaterOrEqual<U100>>::Output: Same<B1>.


问:
Flutter - flutter_blue library connection issue
I am running flutter_blue example app on an android device, but scans and find the ble devices nearby but unable to connect them. iOS build of example app can successfully connect the ble devices. Is there a missing configuration for android devices.

Note: I checked permissions, they are ok.

答:
Permissions appear not to be the issue. It finds the ble devices.

I experienced similar issues with flutter_blue on android. It even appeared to be BLE device dependent. It connected fine to some devices, and didn't for others.

In my case, it was just stuck at the connection attempt. Waiting several minutes resolved mostly in a connection, but that's not usable.

I was able to resolve my issue, by turning off autoconnect, so

```<code>device.connect(autoConnect: false);
</code>```

Then it worked for me. Maybe this helps you or other users experiencing the same issues.

Body:
Permissions appear not to be the issue. It finds the ble devices.

I experienced similar issues with flutter_blue on android. It even appeared to be BLE device dependent. It connected fine to some devices, and didn't for others.

In my case, it was just stuck at the connection attempt. Waiting several minutes resolved mostly in a connection, but that's not usable.

I was able to resolve my issue, by turning off autoconnect, so

device.connect(autoConnect: false);

Then it worked for me. Maybe this helps you or other users experiencing the same issues.


问:
How to add a role in azure ad for my application?
Im trying to add roles to users in Azure ad for my application. I've already read somethings about add AppRules in the manifest.json but than I dont see add assignment when i create a new user.

Does someone now how t fix this?

答:
please follow this guide to add app roles to your app registration, and how to assign them to users.

https://learn.microsoft.com/en-us/azure/active-directory/develop/howto-add-app-roles-in-azure-ad-apps

since its an application role, its assigned in the user assignment of the application service principal (in the enterprise applications)
I don't believe you can do it on user creation, its a separate process, since you are adding an app role assignment.


问:
Waiting for another flutter command to release the startup lock
When I run my flutter application it show

Waiting for another flutter command to release the startup lock

this messages and not proceed further.

答:
You can try to kill all flutter processes.

TL;DR - go to point 4)

1) List of the processes:

```<code>ps aux
</code>```

2) Search name containing with flutter:

```<code>ps aux | grep flutter
</code>```

where output can be like there:

```<code>stackoverflow     16697   1.5  0.0  4288316    704   ??  S    10:02PM   0:15.80 bash /flutter_path/flutter/bin/flutter --no-color build apk
stackoverflow      2800   1.5  0.0  4288316    704   ??  S     9:59PM   0:18.49 bash /flutter_path/flutter/bin/flutter --no-color pub get
stackoverflow      1215   1.5  0.0  4280124    700   ??  S     9:58PM   0:18.89 bash /flutter_path/flutter/bin/flutter --no-color config --machine
stackoverflow      8449   1.5  0.0  4296508    716   ??  S    10:00PM   0:17.20 bash /flutter_path/flutter/bin/flutter --no-color pub get
stackoverflow      1326   1.4  0.0  4288316    708   ??  S     9:58PM   0:18.97 bash /flutter_path/flutter/bin/flutter daemon
stackoverflow     16687   0.0  0.0  4279100    820   ??  S    10:02PM   0:00.01 bash /flutter_path/flutter/bin/flutter --no-color build apk
stackoverflow      8431   0.0  0.0  4288316    804   ??  S    10:00PM   0:00.02 bash /flutter_path/flutter/bin/flutter --no-color pub get
stackoverflow      2784   0.0  0.0  4288316    704   ??  S     9:59PM   0:00.01 bash /flutter_path/flutter/bin/flutter --no-color pub get
stackoverflow      1305   0.0  0.0  4280124    712   ??  S     9:58PM   0:00.01 bash /flutter_path/flutter/bin/flutter daemon
stackoverflow      1205   0.0  0.0  4279100    788   ??  S     9:58PM   0:00.01 bash /flutter_path/flutter/bin/flutter --no-color config --machine
stackoverflow     11416   0.0  0.0  4268176    536 s000  R+   10:18PM   0:00.00 grep --color flutter
</code>```

3) Get processes ID

We need content from second column (from above output):

```<code>ps aux | grep flutter | awk '{print $2}'
</code>```

4 a) Kill "automatically":

To list, search and kill all of them you can use

```<code>kill $(ps aux | grep flutter | grep -v grep  | awk '{print $2}')
</code>```

(you can run it also with sudo)

or

```<code>ps aux | grep flutter | grep -v grep | awk '{print $2}' | xargs kill -15
</code>```

4 b) Kill manually

You can kill processes one-by-one using:

```<code>sudo kill -15 <process_ID>
</code>```

e.g. to kill process with id 13245 use:

```<code>sudo kill -15 13245
</code>```

If -15 will not work, you can try -2 or -1.

Final option it is -9 which should not be used because it prevents the process from doing any cleanup work.

Body:
You can try to kill all flutter processes.

TL;DR - go to point 4)

1) List of the processes:

ps aux

2) Search name containing with flutter:

ps aux | grep flutter

where output can be like there:

stackoverflow     16697   1.5  0.0  4288316    704   ??  S    10:02PM   0:15.80 bash /flutter_path/flutter/bin/flutter --no-color build apk
stackoverflow      2800   1.5  0.0  4288316    704   ??  S     9:59PM   0:18.49 bash /flutter_path/flutter/bin/flutter --no-color pub get
stackoverflow      1215   1.5  0.0  4280124    700   ??  S     9:58PM   0:18.89 bash /flutter_path/flutter/bin/flutter --no-color config --machine
stackoverflow      8449   1.5  0.0  4296508    716   ??  S    10:00PM   0:17.20 bash /flutter_path/flutter/bin/flutter --no-color pub get
stackoverflow      1326   1.4  0.0  4288316    708   ??  S     9:58PM   0:18.97 bash /flutter_path/flutter/bin/flutter daemon
stackoverflow     16687   0.0  0.0  4279100    820   ??  S    10:02PM   0:00.01 bash /flutter_path/flutter/bin/flutter --no-color build apk
stackoverflow      8431   0.0  0.0  4288316    804   ??  S    10:00PM   0:00.02 bash /flutter_path/flutter/bin/flutter --no-color pub get
stackoverflow      2784   0.0  0.0  4288316    704   ??  S     9:59PM   0:00.01 bash /flutter_path/flutter/bin/flutter --no-color pub get
stackoverflow      1305   0.0  0.0  4280124    712   ??  S     9:58PM   0:00.01 bash /flutter_path/flutter/bin/flutter daemon
stackoverflow      1205   0.0  0.0  4279100    788   ??  S     9:58PM   0:00.01 bash /flutter_path/flutter/bin/flutter --no-color config --machine
stackoverflow     11416   0.0  0.0  4268176    536 s000  R+   10:18PM   0:00.00 grep --color flutter

3) Get processes ID

We need content from second column (from above output):

ps aux | grep flutter | awk '{print $2}'

4 a) Kill "automatically":

To list, search and kill all of them you can use

kill $(ps aux | grep flutter | grep -v grep  | awk '{print $2}')

(you can run it also with sudo)

or

ps aux | grep flutter | grep -v grep | awk '{print $2}' | xargs kill -15

4 b) Kill manually

You can kill processes one-by-one using:

sudo kill -15 <process_ID>

e.g. to kill process with id 13245 use:

sudo kill -15 13245

If -15 will not work, you can try -2 or -1.

Final option it is -9 which should not be used because it prevents the process from doing any cleanup work.


问:
How to make pthreads work concurrent without pthread_join()
I'm making a program where I have multiple threads working at the same time. After messing with the code for a while, I had an issue where I would send a string (char *) to the thread to do further operations with, and somehow the string did not send at all.

Later, I wrote a very simple code where I just send a string to a thread and the function prints it to the console. I found out that without using pthread_join(), it wouldn't work at all. I have no idea why, because I know that whenever pthread_join() is called, it blocks every other thread and waits until that one is finished.

Here's the simple program:

```<code>void* prisntstr(void* string);

int main(int argc, char *argv[])
{
    char* string = "Hello!";

    pthread_t thread;

    pthread_create(&thread, NULL, prisntstr, (void*)string);

    pthread_join(thread, NULL);

}

void* prisntstr(void* string)
{
    char* str = (char*)string;

    printf("%s\n", str);
}
</code>```

Does anyone know how I can do this without using pthread_join()?

答:
The thread calling pthread_join() just waits for another thread to finish. Please note that:

If that thread has already terminated, then pthread_join() returns immediately

It is the most elegant way for doing it, being the others more complicated, and involving IPC tecniques:

the calling thread could wait for a mutex/semaphore put by the secondary thread

the calling thread could wait for a signal sent by the secondary thread

... and so on

So basically the strategy is: synchronize threads so that

The main thread can obtain some information calculated by the child thread

The process is kept alive until the child thread has completed its action (like in this case)

The reason why without pthread_join() you dont see that message printed to stdout is that as soon as main terminate, it terminates the whole process and all children threads are terminated; in your case before the print is executed.

Body:
I'm making a program where I have multiple threads working at the same time. After messing with the code for a while, I had an issue where I would send a string (char *) to the thread to do further operations with, and somehow the string did not send at all.

Later, I wrote a very simple code where I just send a string to a thread and the function prints it to the console. I found out that without using pthread_join(), it wouldn't work at all. I have no idea why, because I know that whenever pthread_join() is called, it blocks every other thread and waits until that one is finished.

Here's the simple program:

void* prisntstr(void* string);

int main(int argc, char *argv[])
{
    char* string = "Hello!";

    pthread_t thread;

    pthread_create(&thread, NULL, prisntstr, (void*)string);

    pthread_join(thread, NULL);

}

void* prisntstr(void* string)
{
    char* str = (char*)string;

    printf("%s\n", str);
}

Does anyone know how I can do this without using pthread_join()?


问:
Maintain float precision when selecting values in a pandas dataframe using iloc
My code:

```<code>import pandas as pd

pd.set_option('display.float_format','{:.2f}'.format)

df = pd.Series([500.0, 200.0, 300.0])
df
0   500.00
1   200.00
2   300.00
dtype: float64

df.iloc[1]
200.0
</code>```

I want df.iloc[1] to return 200.00, can anyone explain what's happening here and how to get the desired result please.

答:
Indexing the way you did will return the actual value at that index, which is type float.

```<code>type(df.iloc[1]) # returns 'numpy.float64'
</code>```

What you would like to do is print the entire row, like so:

```<code>df.iloc[[1]]
</code>```

In this case, the index returns a series:

```<code>type(df.iloc[[1]]) # returns 'pandas.core.series.Series'
</code>```

Body:
My code:

import pandas as pd

pd.set_option('display.float_format','{:.2f}'.format)

df = pd.Series([500.0, 200.0, 300.0])
df
0   500.00
1   200.00
2   300.00
dtype: float64

df.iloc[1]
200.0

I want df.iloc[1] to return 200.00, can anyone explain what's happening here and how to get the desired result please.

Body:
Indexing the way you did will return the actual value at that index, which is type float.

type(df.iloc[1]) # returns 'numpy.float64'

What you would like to do is print the entire row, like so:

df.iloc[[1]]

In this case, the index returns a series:

type(df.iloc[[1]]) # returns 'pandas.core.series.Series'