问:
Implementing a C function that splits a string on a given character and returns an array of strings after the split (along with length of array)
I'm trying to implement a C function that takes a string and then breaks that string on a certain character and returns back an array of strings after the split along with the size of that array. I'm using a data structure for this since returning a 2D array (the array of strings after the split) and its length is not possible. My code is given below:

```<code>struct charArr {
    char *arr[10000];
    int size;
};

struct charArr *stringSplitter(char *str, char c) {
    struct charArr *splitString = (struct charArr *)malloc(sizeof(struct charArr));
    if (splitString == NULL) {
        fprintf(stderr, "malloc failed\n");
        exit(1);
    }
    splitString->size = 0;
    int i = 0;
    int j = 0;

    while (str[i] != '\0') {
        if (str[i] == c) {
            splitString->arr[splitString->size][j] = '\0';

            (splitString->size)++;
            j = 0;
            i++;

            while (str[i] == c) {    /* this loop is to ignore continuous occurrences of the character c */
                i++;
            }
        } else {
            splitString->arr[splitString->size][j] = str[i];
            i++;
            j++;
        }
    }
    splitString->arr[splitString->size][j] = '\0';
    return splitString;
}

int main(int argc, char *argv[]) {

    // take input from command line
    if (argc == 1) {
        //buffer to store lines
        size_t buffer_size = 128;
        char *buffer = malloc(buffer_size * sizeof(char));
        if (buffer == NULL) {
            fprintf(stderr, "malloc failed\n");
            exit(1);
        }

        // loop continuously till user exits by ctrl+c
        while (1) {
            printf("Enter Input> ");
            getline(&buffer, &buffer_size, stdin);

            char *str = strdup(buffer);

            struct charArr *splitString = stringSplitter(str, '&');

            for (int i = 0; i<splitString->size; i++) {
                printf("%s ", splitString->arr[i]);
            }
        }
    }
    return 0;
}
</code>```

On running the code on a simple input like (the input is continuously taken from the command line):

Enter Input> this & that

I expect the output to be:

this that

But, I'm getting the error:

Segmentation fault (core dumped)

If the input is as shown below (i.e; continuous occurrences of the splitting character):

Enter Input> this &&& that

then also the output must be:

this that

Edit: I'm trying to extend this to split a string on multiple delimiters as well (in one go), so instead of char c in the above function, if char *c is passed which is a string of delimiters (example c = " \t\n" to remove all white spaces from given string), then also it should work as expected and return an array of strings after the split and length of array.
For example, if input is (multiple spaces, tabs and newline):

```<code>Enter Input>      this                               that
</code>```

Then the array returned (which is a part of the returned structure) must be of size 2 and only contain the 2 strings - "this" and "that".

答:
It's been a long time since I wrote any C so I thought this would be a challenge.  Here's a rewrite of the stringSplitter function.

```<code>struct charArr* stringSplitter(char *str, char c){
    struct charArr* splitString = (struct charArr*)malloc(sizeof(struct charArr));
    if(splitString == NULL){
        fprintf(stderr, "malloc failed\n");
        exit(1);
    }
    splitString->size = 0;
    char sep[2];
    sep[0] = c;
    sep[1] = (char) 0;

    char* next;
    while( (next = strtok( str, sep )) )
    {
      str = NULL;
      splitString->arr[ splitString->size++ ] = next;
    }

    return splitString;
}
</code>```

Above, I'm simply using strtok.   Take a look at the manpage for strtok() to see it's nuances.

Body:
I'm trying to implement a C function that takes a string and then breaks that string on a certain character and returns back an array of strings after the split along with the size of that array. I'm using a data structure for this since returning a 2D array (the array of strings after the split) and its length is not possible. My code is given below:

struct charArr {
    char *arr[10000];
    int size;
};

struct charArr *stringSplitter(char *str, char c) {
    struct charArr *splitString = (struct charArr *)malloc(sizeof(struct charArr));
    if (splitString == NULL) {
        fprintf(stderr, "malloc failed\n");
        exit(1);
    }
    splitString->size = 0;
    int i = 0;
    int j = 0;

    while (str[i] != '\0') {
        if (str[i] == c) {
            splitString->arr[splitString->size][j] = '\0';

            (splitString->size)++;
            j = 0;
            i++;

            while (str[i] == c) {    /* this loop is to ignore continuous occurrences of the character c */
                i++;
            }
        } else {
            splitString->arr[splitString->size][j] = str[i];
            i++;
            j++;
        }
    }
    splitString->arr[splitString->size][j] = '\0';
    return splitString;
}

int main(int argc, char *argv[]) {

    // take input from command line
    if (argc == 1) {
        //buffer to store lines
        size_t buffer_size = 128;
        char *buffer = malloc(buffer_size * sizeof(char));
        if (buffer == NULL) {
            fprintf(stderr, "malloc failed\n");
            exit(1);
        }

        // loop continuously till user exits by ctrl+c
        while (1) {
            printf("Enter Input> ");
            getline(&buffer, &buffer_size, stdin);

            char *str = strdup(buffer);

            struct charArr *splitString = stringSplitter(str, '&');

            for (int i = 0; i<splitString->size; i++) {
                printf("%s ", splitString->arr[i]);
            }
        }
    }
    return 0;
}

On running the code on a simple input like (the input is continuously taken from the command line):

Enter Input> this & that

I expect the output to be:

this that

But, I'm getting the error:

Segmentation fault (core dumped)

If the input is as shown below (i.e; continuous occurrences of the splitting character):

Enter Input> this &&& that

then also the output must be:

this that

Edit: I'm trying to extend this to split a string on multiple delimiters as well (in one go), so instead of char c in the above function, if char *c is passed which is a string of delimiters (example c = " \t\n" to remove all white spaces from given string), then also it should work as expected and return an array of strings after the split and length of array.
For example, if input is (multiple spaces, tabs and newline):

Enter Input>      this                               that

Then the array returned (which is a part of the returned structure) must be of size 2 and only contain the 2 strings - "this" and "that".

Body:
It's been a long time since I wrote any C so I thought this would be a challenge.  Here's a rewrite of the stringSplitter function.

struct charArr* stringSplitter(char *str, char c){
    struct charArr* splitString = (struct charArr*)malloc(sizeof(struct charArr));
    if(splitString == NULL){
        fprintf(stderr, "malloc failed\n");
        exit(1);
    }
    splitString->size = 0;
    char sep[2];
    sep[0] = c;
    sep[1] = (char) 0;

    char* next;
    while( (next = strtok( str, sep )) )
    {
      str = NULL;
      splitString->arr[ splitString->size++ ] = next;
    }

    return splitString;
}

Above, I'm simply using strtok.   Take a look at the manpage for strtok() to see it's nuances.


来源: stackexchange

问:
How to deal with merge/pull in git
I have to use different computers. I updated file A, B and other files in one and B, C and other files in another.

Updates in file B are different part of code.  I have committed in both.
I pushed A and B to the github.

Questions:

Now what should I do in another?

Should I just pull? Or should I push first?

If I push, will file A be overwritten?

If I pull, will file C be overwritten?

What kind of process do I need to take?

What do I need to do with file B which has different version? Can I merge them?

答:
The usual scenario is that you do a pull before you push up your changes. But it might be the case that the current ancestor of your commits is the same since you pulled the last time (i.e. all the others haven't pushed anything yet), which means no merge is required and you can just push your changes without needing to pull.

Once someone else has pushed their changes in between, then you always have to pull their changes into yours (this is where git creates what is called a merge commit, which is a commit that hasn't been created the usual way with git add, git commit etc). Now your repository is synched with the latest changes and you can safely push to sync the central repository with yours.

In this case you have to pull first, which means that C will not be overwritten, since both repositories have the same version (remember, you only changed B on both repos).

In the case of B, where you have two divergent versions that must be merged by git, there might be conflicts. But this is exactly what a pull is, it's a fetch (to sync your repositories) and a merge between your local branch that is tracking the remote branch, e.g. master is merged with origin/master.

And finally the same thing will happen to A, the changes made in the first repo to A will be a trivial merge into A in the other repository, since the modified A is modified from the same version (identical blobs) of A in the other repo.

Hope this cleared some stuff up.

Cheers!

ContentLicense: CC BY-SA 3.0

Title: How to deal with merge/pull in git


问:
Get a list of maximum values per tuple from a list of tuples
I'm just getting into Python, and having some trouble understanding the control flow and iteration logic.

I am trying to create a function which takes a list of tuples, and I want to return a new list with the maximum element per tuple.

I know I'm missing putting the maximum element into a new list, but first I am trying to get that maximum value.

```<code>def max_element_per_tuple(tuple_list):
    maximum = tuple_list[0]

    for item in tuple_list:
        if item > maximum:
            maximum = item

    return maximum

# test it
tuple_list = [(-1,0,1), (10,20,30), (100,50,25), (55,75,65)]
print(max_element_per_tuple(tuple_list))
</code>```

This returns: (100, 50, 25)

Want returned: (1, 30, 100, 75)

Or if a list (?), then: [1, 30, 100, 75]

答:
Your function max_element_per_tuple is correct (though unnecessary, because standard function max() exists). What you did wrong was calling that function using a list of tuples as the argument. This found the biggest tuple in the list ("biggest" for tuples means "the one with first element biggest"), which happened to be the third one - (100,50,25). What you need to do is either:

```<code>result = list(map(max, tuple_list))
</code>```

or

```<code>result = [max(t) for t in tuple_list]
</code>```

This last one is roughly equivalent to:

```<code>result = []
for t in tuple_list:
    result.append(max(t))
</code>```

If you replace max with your max_element_per_tuple the results should be the same.

ContentLicense: CC BY-SA 4.0

Body:
I'm just getting into Python, and having some trouble understanding the control flow and iteration logic.

I am trying to create a function which takes a list of tuples, and I want to return a new list with the maximum element per tuple.

I know I'm missing putting the maximum element into a new list, but first I am trying to get that maximum value.

def max_element_per_tuple(tuple_list):
    maximum = tuple_list[0]

    for item in tuple_list:
        if item > maximum:
            maximum = item

    return maximum

# test it
tuple_list = [(-1,0,1), (10,20,30), (100,50,25), (55,75,65)]
print(max_element_per_tuple(tuple_list))

This returns: (100, 50, 25)

Want returned: (1, 30, 100, 75)

Or if a list (?), then: [1, 30, 100, 75]

Body:
Your function max_element_per_tuple is correct (though unnecessary, because standard function max() exists). What you did wrong was calling that function using a list of tuples as the argument. This found the biggest tuple in the list ("biggest" for tuples means "the one with first element biggest"), which happened to be the third one - (100,50,25). What you need to do is either:

result = list(map(max, tuple_list))

or

result = [max(t) for t in tuple_list]

This last one is roughly equivalent to:

result = []
for t in tuple_list:
    result.append(max(t))

If you replace max with your max_element_per_tuple the results should be the same.


问:
How to connect to a database with semicolon in the name?
I have a database which has a semicolon in the name e.g. a;a. I can't rename the database. In SQL I would use the backticks to escape the name, but how can I do it in PDO DSN?

```<code>$db = 'a;a';
$dsn = "mysql:host=localhost;dbname=$db;charset=utf8mb4";
$options = [
    \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
    \PDO::ATTR_EMULATE_PREPARES => false,
];
try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
    throw new \PDOException($e->getMessage(), (int) $e->getCode());
}
</code>```

Since ; is used as a separator in the DSN, PDO thinks my database is called a and I get this error:

Fatal error: Uncaught PDOException: SQLSTATE[HY000] [1049] Unknown database 'a'

答:
I solved it by using double semicolon. </p>

```<code>$db = 'a;;a'; // <-- means the database is called `a;a`
$dsn = "mysql:host=localhost;dbname=$db;charset=utf8mb4";
</code>```

Body:
I have a database which has a semicolon in the name e.g. a;a. I can't rename the database. In SQL I would use the backticks to escape the name, but how can I do it in PDO DSN?

$db = 'a;a';
$dsn = "mysql:host=localhost;dbname=$db;charset=utf8mb4";
$options = [
    \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
    \PDO::ATTR_EMULATE_PREPARES => false,
];
try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
    throw new \PDOException($e->getMessage(), (int) $e->getCode());
}

Since ; is used as a separator in the DSN, PDO thinks my database is called a and I get this error:

Fatal error: Uncaught PDOException: SQLSTATE[HY000] [1049] Unknown database 'a'

Body:
I solved it by using double semicolon.

$db = 'a;;a'; // <-- means the database is called `a;a`
$dsn = "mysql:host=localhost;dbname=$db;charset=utf8mb4";


问:
Running stanford moss because of institution proxy
I am running moss by Stanford.
I am using Perl script sent by Stanford at the time of registration.
but it is giving error as :

```<code>Checking files . . .
OK
Could not connect to server moss.stanford.edu: Connection refused
</code>```

I tried adding institute proxy also in the code as follows :

```<code>$sock = new IO::Socket::INET (
                                  ProxyAddr   => '10.3.100.207',
                                   ProxyPort   => '8080',
                                  PeerAddr => $server,
                                  PeerPort => $port,
                                  Proto => 'tcp',
                                 );
</code>```

But it is giving the same error as above.
One possible solution is to set up a virtual environment and run the script.
But what can be another solution ?

答:
Here is what I did and it worked.
I used Google colab for it.
I uploaded the files to be checked for plagiarism and the perl script to colab and then ran the perl script in the notebook</p>

```<code>!perl moss.pl -l python -m 53 -c "Files" ./*.py
</code>```

Body:
I am running moss by Stanford.
I am using Perl script sent by Stanford at the time of registration.
but it is giving error as :

Checking files . . .
OK
Could not connect to server moss.stanford.edu: Connection refused

I tried adding institute proxy also in the code as follows :

$sock = new IO::Socket::INET (
                                  ProxyAddr   => '10.3.100.207',
                                   ProxyPort   => '8080',
                                  PeerAddr => $server,
                                  PeerPort => $port,
                                  Proto => 'tcp',
                                 );

But it is giving the same error as above.
One possible solution is to set up a virtual environment and run the script.
But what can be another solution ?

Body:
Here is what I did and it worked.
I used Google colab for it.
I uploaded the files to be checked for plagiarism and the perl script to colab and then ran the perl script in the notebook

!perl moss.pl -l python -m 53 -c "Files" ./*.py


Title: Get a list of maximum values per tuple from a list of tuples

Body:
Simply, try this one-linear pythonic solution

>>> tuple_list = [(-1,0,1), (10,20,30), (100,50,25), (55,75,65)]
>>> [max(e) for e in tuple_list]       # List
[1, 30, 100, 75]
>>> tuple(max(e) for e in tuple_list)  # Tuple
(1, 30, 100, 75)


问:
User Data is not saving to Database in Laravel 6
User Data is not saving to Database in Laravel 6. I am using socialite to save data to the database with the following code lines.

```<code>protected $fillable = [
    'email','name','password','username','picture'
];
</code>```

In the login controller. I am able to fetch data from socialite correctly(I Checked).

```<code>$user = User::firstOrCreate(

          ['email'=> $social_user->getEmail()],
          ['username'=> $social_user->getName()],
          ['name'=> $social_user->getName()],
          ['picture'=> $social_user->getAvatar()],
          ['password'=> 'sdsdsdsad'],
          ['ip_address'=> '127.0.0.1'],

      );
</code>```

答:
In your Model you forget to add ip_address.
So Your Model :

```<code>protected $fillable = [
    'email','name','password','username','picture','ip_address'
];
</code>```

In your controller :

```<code>$user = User::firstOrCreate(
      ['email' => $social_user->getEmail()],
      [
         'username'=> $social_user->getName(),
         'name'=> $social_user->getName(),
         'picture'=> $social_user->getAvatar(),
         'password'=> 'sdsdsdsad',
         'ip_address'=> '127.0.0.1'
      ]
);
</code>```

Body:
User Data is not saving to Database in Laravel 6. I am using socialite to save data to the database with the following code lines.

protected $fillable = [
    'email','name','password','username','picture'
];

In the login controller. I am able to fetch data from socialite correctly(I Checked).

$user = User::firstOrCreate(

          ['email'=> $social_user->getEmail()],
          ['username'=> $social_user->getName()],
          ['name'=> $social_user->getName()],
          ['picture'=> $social_user->getAvatar()],
          ['password'=> 'sdsdsdsad'],
          ['ip_address'=> '127.0.0.1'],

      );

Body:
In your Model you forget to add ip_address.
So Your Model :

protected $fillable = [
    'email','name','password','username','picture','ip_address'
];

In your controller :

$user = User::firstOrCreate(
      ['email' => $social_user->getEmail()],
      [
         'username'=> $social_user->getName(),
         'name'=> $social_user->getName(),
         'picture'=> $social_user->getAvatar(),
         'password'=> 'sdsdsdsad',
         'ip_address'=> '127.0.0.1'
      ]
);


问:
Not able to set the variable correctly in a batch script
I am reading a values from the xml file using batch ,
values are like Age="18"
When the value is extracted i don't want the double quotes

```<code>for /f "tokens=2 delims= " %%b in ('type <file_name> ^| FIND "info" ) do (
echo %%b
set string =%%b
</code>```

string = Age="18" ( getting error here)

in the info tag
<info Name="xxx" Age="18"></info>

i need only the value 18 to be stored in a variable

Need assistance

答:
Instead of choosing the 2nd token with   as the delimiter, you probably want the 4th token using the " as a delimiter:

 @For /F Tokens^=4^ Delims^=^" %%G In ('^""%__AppDir%find.exe" /I "<info "^<"filename.txt"^"') Do @Set "age=%%G"
```

<p>You may also wish, for robustness, to match a more unique pattern. You can do that by choosing <code>findstr.exe</code> instead of <code>find.exe</code>:</p>

<pre class="lang-bat prettyprint-override"><code>@For /F Tokens^=4^ Delims^=^" %%G In ('^""%__AppDir%findstr.exe" /IR "<info\ Name=\"[a-Z]*\"\ Age=\"[0-9]*\">" "filename.txt"^"') Do @Set "age=%%G"
</code>```

Please note that the pattern I have used for the age, allows for superscript digits. However, this scenario is unlikely ever to be encountered, in your actual case, so I figured that this pattern should suffice.

Body:
I am reading a values from the xml file using batch ,
values are like Age="18"
When the value is extracted i don't want the double quotes

for /f "tokens=2 delims= " %%b in ('type <file_name> ^| FIND "info" ) do (
echo %%b
set string =%%b

string = Age="18" ( getting error here)

in the info tag
<info Name="xxx" Age="18"></info>

i need only the value 18 to be stored in a variable

Need assistance

Body:
Instead of choosing the 2nd token with   as the delimiter, you probably want the 4th token using the " as a delimiter:

 @For /F Tokens^=4^ Delims^=^" %%G In ('^""%__AppDir%find.exe" /I "<info "^<"filename.txt"^"') Do @Set "age=%%G"

You may also wish, for robustness, to match a more unique pattern. You can do that by choosing findstr.exe instead of find.exe:

@For /F Tokens^=4^ Delims^=^" %%G In ('^""%__AppDir%findstr.exe" /IR "<info\ Name=\"[a-Z]*\"\ Age=\"[0-9]*\">" "filename.txt"^"') Do @Set "age=%%G"

Please note that the pattern I have used for the age, allows for superscript digits. However, this scenario is unlikely ever to be encountered, in your actual case, so I figured that this pattern should suffice.


问:
DotNetNuke 5 open aspx in new window
Another issue I have in DNN5:

I'm currently creating a module that shows a GridView that has a "Edit" column.
When user clicks on "Edit" column, it should open an edit form in a new window.
This edit form is an ASPX-page inside my module folder and it expects a ModuleId parameter in order to access the module Settings; that part works fine and I'm able to retrieve the Module settings.

However, I still have the following issues:

How can I localize my Labels? I have tried DNN's label control, but no success. I also tried asp:Label with "meta:resourceKey", but it looks like it isn't able to access the local resource file.

It's very annoying to use Aspx-pages in my module since it will operate outside DotNetNuke's context. Does anybody knows an approach that allows me to use PortalModuleBase?
I have tought about displaying a DotNetNuke page in the new window, just by referencing the Control to load. However when I do that, it will show me the full page (so with navigation bar, footer, and so on) and I actually just want to show the control.
Besides, I'm only able to open my Aspx-page by referencing to /DesktopModules/MyModule/Page.aspx instead of DNN's NavigateUrl or so.

Thanks for your replies.

答:
DNN will hide all other modules on the page whenever a control (or ctl=mycontrol) is specified for the page. So,

You should change your code from an ASPX page to an ASCX control.

Add the ascx control to the Module Controls section of your module's Module Definition.

Use DNN's NavigateURL function to generate the link. You'll want to use one of the options where you specify the Control Key (i.e. NavigateURL("edit", "SkinSrc=[G]" + Globals.QueryStringEncode( DotNetNuke.UI.Skins.SkinInfo.RootSkin + "/" + Globals.glbHostSkinFolder + "/" + "No Skin" ))

In the above sample, "edit" is the control key you specified for the control.

Title: DotNetNuke 5 open aspx in new window


问:
Yahoo mail prevents links in emails
Yahoo is removing the href attribute from the  elements from emails that we send for registration approval or password reset.

We are using Sendgrid web api to send mails using nodemailer-sendgrid-transport module.

After googling possible answers, I am certain that:

We are using complete urls (starting with https:// at the start of the url).

We have added target="_blank" attribute to our  elements.

Our emails don't go in to spam. So it's not related with disabling links in spam issue.

However these didn't solve our problem.
Is there any way to prevent yahoo from disabling links by removing href attribute?

Issue is not occurring when on other mail providers such as gmail etc.

答:
Given that the email is NOT in the SPAM folder, then adding rel="nofollow" to your  tags and also being sure to use the full url (including the http or https) should fix the issue.

```<code><a rel="nofollow" href="https://www.myurl.com">Some Text</a>
</code>```

Title: Yahoo mail prevents links in emails

Body:
Given that the email is NOT in the SPAM folder, then adding rel="nofollow" to your <a> tags and also being sure to use the full url (including the http or https) should fix the issue.

<a rel="nofollow" href="https://www.myurl.com">Some Text</a>


问:
Making a "fluid grid" with divs & css/bootstrap

Is it possible to create something like this with either raw css or bootstrap? I want to have it set up where each button is a fixed size and is written in a list format where I don't have to define a specific row or column length. Ex:

```

But like I said, each box item needs to be a square with an exact side length. Can someone help me with this?

答:
Please take a look at flexbox in css:

.grid {
  display: flex;
  flex-wrap: wrap;
}

.box {
  width: 50px;
  height: 50px;
  border: solid orange 3px;
  margin: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div></code>```

Body:
Is it possible to create something like this with either raw css or bootstrap? I want to have it set up where each button is a fixed size and is written in a list format where I don't have to define a specific row or column length. Ex:

But like I said, each box item needs to be a square with an exact side length. Can someone help me with this?

Body:
Please take a look at flexbox in css:

.grid {
  display: flex;
  flex-wrap: wrap;
}

.box {
  width: 50px;
  height: 50px;
  border: solid orange 3px;
  margin: 10px;
}

<div class="grid">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>


问:
Submit checked Atlaskit Dropdown(@atlaskit/dropdown-menu) menu checkboxes on Item click
I am using @atlaskit/dropdown-menu (https://atlaskit.atlassian.com/packages/core/dropdown-menu). I would like to submit a small form on Item click, I need to submit values of DropdownItemCheckbox.

Here is a code to render needed components: https://codesandbox.io/s/py8qoo64mq

```<code>import React from "react";
import Dropdown, {
  DropdownItemCheckbox,
  DropdownItemGroupCheckbox,
  DropdownItem
} from "@atlaskit/dropdown-menu";

export default () => (
  <Dropdown defaultOpen triggerType="button" trigger="Drop menu">
    <DropdownItemGroupCheckbox id="languages2" title="Languages">
      <DropdownItemCheckbox defaultSelected id="js-check">
        JavaScript
      </DropdownItemCheckbox>
      <DropdownItemCheckbox id="java">Java</DropdownItemCheckbox>
      <DropdownItemCheckbox defaultSelected id="ruby">
        Ruby
      </DropdownItemCheckbox>
    </DropdownItemGroupCheckbox>
    <DropdownItem>Submit</DropdownItem>
  </Dropdown>
);
</code>```

I don't want to use Select because I want to trigger dropdown list with a custom button, and use layering advantages of DropdownMenu

答:
I had the same issue, and after a lot of research i found that the problem was caused by styled-components package, but it works with if the version is <=3.5.0-0. So my solution was to downgrade styled-components package to 3.5.0-0. This does not explain why it doesn't work because they are just styles. But for now this is a workaround.

After i raised an issue, Atlassian sent me the following response that i think will answer your questions.

Atlaskit doesn’t officially support styled-components v4 and above. We currently require that our consumers use SC v3.2.6 as per our peer dependency. However, recently there has been some ongoing work to upgrade / migrate Atlaskit to a more modern css-in-js library and we’re working through the decision making process internally at the moment.
  Please feel free to follow this ticket for status updates: https://ecosystem.atlassian.net/browse/DS-6836

Body:
I am using @atlaskit/dropdown-menu (https://atlaskit.atlassian.com/packages/core/dropdown-menu). I would like to submit a small form on Item click, I need to submit values of DropdownItemCheckbox.

Here is a code to render needed components: https://codesandbox.io/s/py8qoo64mq

import React from "react";
import Dropdown, {
  DropdownItemCheckbox,
  DropdownItemGroupCheckbox,
  DropdownItem
} from "@atlaskit/dropdown-menu";

export default () => (
  <Dropdown defaultOpen triggerType="button" trigger="Drop menu">
    <DropdownItemGroupCheckbox id="languages2" title="Languages">
      <DropdownItemCheckbox defaultSelected id="js-check">
        JavaScript
      </DropdownItemCheckbox>
      <DropdownItemCheckbox id="java">Java</DropdownItemCheckbox>
      <DropdownItemCheckbox defaultSelected id="ruby">
        Ruby
      </DropdownItemCheckbox>
    </DropdownItemGroupCheckbox>
    <DropdownItem>Submit</DropdownItem>
  </Dropdown>
);

I don't want to use Select because I want to trigger dropdown list with a custom button, and use layering advantages of DropdownMenu


问:
installation app blocked by play protect
When trying to install a signed application (app-release.apk), a "Blocked by Play Protect" alert is shown and the app is not installed. However, an unsigned application  (app-debug.apk) can be installed without problems.

The error message:

Play Protect doesn't recognise this app's developer. Apps from unknown developers can sometimes be unsafe.

Why this error happened? What's the solution?

答:
it is due to expired of debug certificate
simply delete the debug.keystore located at

```<code>C:\Users\.android\
</code>```

after that build your project the build tools will regenerate a new key and it will work fine.
here is a reference:

```<code>https://developer.android.com/studio/publish/app-signing
</code>```

Body:
it is due to expired of debug certificate
simply delete the debug.keystore located at

C:\Users\.android\

after that build your project the build tools will regenerate a new key and it will work fine.
here is a reference:

https://developer.android.com/studio/publish/app-signing


答:
This should work

```<code>def max_element_per_tuple(tuple_list):
    maximum = []

    for item in tuple_list:
        maximum.append(max(item))

    return maximum
</code>```

will give this output : [1, 30, 100, 75]

Body:
This should work

def max_element_per_tuple(tuple_list):
    maximum = []

    for item in tuple_list:
        maximum.append(max(item))

    return maximum

will give this output : [1, 30, 100, 75]


问:
Unity project failed to build using Mono
I cannot build my project In mono mode. It works but no Il2cpp please help

1. ERROR

Failed running C: \ Program Files \ Unity 2019.3.0b4 \ Editor \ Data \ il2cpp \ build / UnityLinker.exe -out = C: / shamstest / Temp / StagingArea / assets / bin / Data / Managed / tempStrip -x = C: /shamstest/Temp/StagingArea/assets/bin/Data/Managed/../platform_native_link.xml -x = C: /shamstest/Temp/StagingArea/assets/bin/Data/Managed/TypesInScenes.xml -d = C: / shamstest / Temp / StagingArea / assets / bin / Data / Managed --dotnetruntime = il2cpp --dotnetprofile = unityaot --use-editor-options --include-directory = C: / shamstest / Temp / StagingArea / assets / bin / Data / Managed --rule-set = Conservative --editor-data-file = C: /shamstest/Temp/StagingArea/assets/bin/Data/Managed/EditorToUnityLinkerData.json --platform = Android --enable-engine-module- stripping --engine-stripping-flag = EnableUnityConnect --engine-modules-asset-file = "C: / Program Files / Unity 2019.3.0b4 / Editor / Data / PlaybackEngines / AndroidPlayer / Whitelists /../ modules.asset"

stdout: stderr:

√ 2.0.0.0, Culture = neutral, PublicKeyToken = cc7b13ffcd2ddd51 "���� ���� �� �� ����ᨬ��⥩. �� 㤠 ���� ���� 㪠 ����� 䠩 �.     � Unity.Linker.UnityDriver..ctor (String [] args)     � Unity.Linker.Program.Main (String [] args)

UnityEngine.Debug: LogError (Object) UnityEditorInternal.Runner: RunProgram (Program, String, String, String, CompilerOutputParserBase) UnityEditorInternal.Runner: RunManagedProgram (String, String, String, CompilerOutputParserBase, Action1) UnityEditorInternal.AssemblyStripper: RunAssemblyLinker (IEnumerable1, String &, String &, String, String) UnityEditorInternal.AssemblyStripper: StripAssembliesTo (String, String &, String &, IEnumerable1, UnityLinkerRunInformation) UnityEditorInternal.AssemblyStripper: RunAssemblyStripper (UnityLinkerRunInformation) UnityEditorInternal.AssemblyStripper: StripAssemblies (String, BaseUnityLinkerPlatformProvider, IIl2CppPlatformProvider, RuntimeClassRegistry, ManagedStrippingLevel) UnityEditorInternal.IL2CPPBuilder: Run () UnityEditorInternal.IL2CPPUtils: RunIl2Cpp (String, String, IIl2CppPlatformProvider, Action1, RuntimeClassRegistry) UnityEngine.GUIUtility: ProcessEvent (Int32, IntPtr)

2.ERROR

Exception: C: \ Program Files \ Unity 2019.3.0b4 \ Editor \ Data \ il2cpp \ build / UnityLinker.exe did not run properly! UnityEditorInternal.Runner.RunProgram (UnityEditor.Utils.Program p, System.String exe, System.String args, System.String workingDirectory, UnityEditor.Scripting.Compilers.CompilerOutputParserBase parser) (at <5f8e991dd2b8dbbddbbdbbd441) UnityEditorInternal.Runner.RunManagedProgram (System.String exe, System.String args, System.String workingDirectory, UnityEditor.Scripting.Compilers.CompilerOutputParserBase parser, System.Action1 [T] setupStartInfo) (at <5f8e8d7a2d2e2a2d2e1d2e2a2d2e1d2a2d2e2d1d2a2d1d2a2d1d2a2d1d2a2d1d2a2d1d2a2d1d2d1d2a7d2d2a7e2d1d2a7d2a) UnityEditorInternal.AssemblyStripper.RunAssemblyLinker (System.Collections.Generic.IEnumerable1 [T] args, System.String & out, System.String & err, System.String linkerPath, System.String workingDirectory) (at 0a8a8a8a8aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa UnityEditorInternal.AssemblyStripper.StripAssembliesTo (System.String outputFolder, System.String & output, System.String & error, System.Collections.Generic.IEnumerable1 [T] linkXmlFiles, UnityEditorInternal.UnityLinkerRa88dd1e8ad8ad1a8ad1a8bd1d1a8bd1d8ad1e8ad1a8bd1d1a_db8d1_8bd1_db1d1_fd2_db_db_db_db_db_db_db_file_function_files UnityEditorInternal.AssemblyStripper.RunAssemblyStripper (UnityEditorInternal.UnityLinkerRunInformation runInformation) (at : 0) UnityEditorInternal.AssemblyStripper.StripAssemblies (System.String managedAssemblyFolderPath, UnityEditorInternal.BaseUnityLinkerPlatformProvider unityLinkerPlatformProvider, UnityEditorInternal.IIl2CppPlatformProvider il2cppPlatformProvider, UnityEditor.RuntimeClassRegistry rcr, UnityEditor.ManagedStrippingLevel managedStrippingLevel) (at : 0) UnityEditorInternal.IL2CPPBuilder.Run () (at : 0) UnityEditorInternal.IL2CPPUtils.RunIl2Cpp (System.String tempFolder, System.String stagingAreaData, UnityEditorInternal.IIl2CppPlatformProvider platformProvider, System.Action1 [T] modifyityutfd8e8dre1drreg1dreme8dreg1dre1dremelass_megregor UnityEditor.Android.PostProcessor.Tasks.RunIl2Cpp.Execute (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at : 0) UnityEditor.Android.PostProcessor.PostProcessRunner.RunAllTasks (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at : 0) UnityEditor.Android.PostProcessAndroidPlayer.PostProcess (UnityEditor.BuildTarget target, System.String stagingAreaData, System.String stagingArea, System.String playerPackage, System.String installPath, System.String companyName, System.String productName, UnityEptions, Unitityptor

答:
Install Net Framework 4.

https://dotnet.microsoft.com/download/dotnet-framework/thank-you/net472-developer-pack-offline-installer

It worked for me

OwnerDisplayName: Jasur


问:
Linearing programming with Pulp: Error with LpAffineExpression
I'm currently using the pulp package to work on linear programming.
I tried to set the dependent variable which varies with the decision variable but failed...
What I did was:

```<code>opt = LpProblem(name="OPT")

# Data
df={"A":[5,4,3,4,6]}
a=df["A"]

# Set decision variable
var=LpVariable.dicts("Var", df.index, lowBound=-3.3, upBound=3.3, cat="Continuous")

# Set dependent variable
k={}
for i in df.index:
    k[i]=math.tanh(-var[i])

# Set constraints
opt += a[i]-var[i] >= 0

# Define the objective function
opt += lpSum ((a[i]-var[i])*k[i]) for i in df.index)

opt_model.solve()
</code>```

And I got "TypeError: must be real number, not LpAffineExpression".
I am wondering how can I set the decision variable in the tanh function.

答:
There are two related errors here.

math.tanh does not know about decision variables. It can only take numbers as an argument.

Even if it was allowed, this is still non-sensical as this would make the problem non-linear. PuLP is only for linear models.

Body:
I'm currently using the pulp package to work on linear programming.
I tried to set the dependent variable which varies with the decision variable but failed...
What I did was:

opt = LpProblem(name="OPT")

# Data
df={"A":[5,4,3,4,6]}
a=df["A"]

# Set decision variable
var=LpVariable.dicts("Var", df.index, lowBound=-3.3, upBound=3.3, cat="Continuous")

# Set dependent variable
k={}
for i in df.index:
    k[i]=math.tanh(-var[i])

# Set constraints
opt += a[i]-var[i] >= 0

# Define the objective function
opt += lpSum ((a[i]-var[i])*k[i]) for i in df.index)

opt_model.solve()

And I got "TypeError: must be real number, not LpAffineExpression".
I am wondering how can I set the decision variable in the tanh function.


答:
This task can be done with:

```<code>for /F "tokens=5 delims==> " %%I in ('%SystemRoot%\System32\findstr.exe /R /C:"<info .* Age=\"[0123456789][0123456789]*\"" "XmlFile.xml"') do echo %%~I& set "string=%%~I"
</code>```

FOR executes in this case in background one more command process with %ComSpec% /c and the command line between ' appended as additional arguments. So executed is in background with Windows installed to C:\Windows:

```<code>C:\Windows\System32\cmd.exe /c C:\Windows\System32\findstr.exe /R /C:"<info .* Age=\"[0123456789][0123456789]*\"" "XmlFile.xml"
</code>```

FINDSTR runs a case-sensitive regular expression search for a line containing <info containing the attribute Age and the attribute value being a number. The found line is output to handle STDOUT (standard output) of the background command process captured by FOR.

After started cmd.exe closed itself after findstr.exe terminated, FOR processes the captured output line by line with skipping empty lines.

The line is split up into substrings using = and > and space as string delimiters because of delims==> . The fifth substring is the value of attribute Age enclosed in double quotes which is assigned to the specified loop variable I because of tokens=5. The double quotes are removed because of using modifier %~I.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

echo /?

findstr /?

for /?

set /?

Title: Not able to set the variable correctly in a batch script

Body:
This task can be done with:

for /F "tokens=5 delims==> " %%I in ('%SystemRoot%\System32\findstr.exe /R /C:"<info .* Age=\"[0123456789][0123456789]*\"" "XmlFile.xml"') do echo %%~I& set "string=%%~I"

FOR executes in this case in background one more command process with %ComSpec% /c and the command line between ' appended as additional arguments. So executed is in background with Windows installed to C:\Windows:

C:\Windows\System32\cmd.exe /c C:\Windows\System32\findstr.exe /R /C:"<info .* Age=\"[0123456789][0123456789]*\"" "XmlFile.xml"

FINDSTR runs a case-sensitive regular expression search for a line containing <info containing the attribute Age and the attribute value being a number. The found line is output to handle STDOUT (standard output) of the background command process captured by FOR.

After started cmd.exe closed itself after findstr.exe terminated, FOR processes the captured output line by line with skipping empty lines.

The line is split up into substrings using = and > and space as string delimiters because of delims==> . The fifth substring is the value of attribute Age enclosed in double quotes which is assigned to the specified loop variable I because of tokens=5. The double quotes are removed because of using modifier %~I.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

echo /?

findstr /?

for /?

set /?


问:
How can we set context variables for IBM Watson from backend
I want to pass some values to frontend in form of context variables in IBM Watson through my Node app. How can I achieve it?

I tried to add the value I want to add to current context variable object and sent that back. Still no help. Is there any way I can do it?

Edit:

Right now, I am adding the required value as a new key-value pair to the context object from Node app as follows.

```<code>...
let user_name = "MJ"
context.user_name = user_name
response.send({
    output: output,
    context: JSON.stringfy(context)
})
...
</code>```

And in Watson Console, in one of the dialogue nodes I have used like,

```<code>Hey $user_name, How are you?
</code>```

But the output I am getting is,

```<code>Hey , How are you?
</code>```

I can see user_name value in the context object, but I can't use it in the way I mentioned above. Is there any other way to do so?

Any help is appreciated. Thanks in advance!

答:
```<code>var payload = {
    assistantId: assistantId,
    sessionId: req.body.session_id,
    context: {
        skills: {
           "main skill": {
              user_defined: {
                 username: 'John Doe'
               }
            }
         }
    },
    input: {
      message_type: 'text',
      text: "blah",
    },
  };
</code>```

works for me. Seen here: https://medium.com/@pranavbhatia_26901/watson-assistant-v2-context-sharing-3ca18626ed0d

Body:
I want to pass some values to frontend in form of context variables in IBM Watson through my Node app. How can I achieve it?

I tried to add the value I want to add to current context variable object and sent that back. Still no help. Is there any way I can do it?

Edit:

Right now, I am adding the required value as a new key-value pair to the context object from Node app as follows.

...
let user_name = "MJ"
context.user_name = user_name
response.send({
    output: output,
    context: JSON.stringfy(context)
})
...

And in Watson Console, in one of the dialogue nodes I have used like,

Hey $user_name, How are you?

But the output I am getting is,

Hey , How are you?

I can see user_name value in the context object, but I can't use it in the way I mentioned above. Is there any other way to do so?

Any help is appreciated. Thanks in advance!

Body:
var payload = {
    assistantId: assistantId,
    sessionId: req.body.session_id,
    context: {
        skills: {
           "main skill": {
              user_defined: {
                 username: 'John Doe'
               }
            }
         }
    },
    input: {
      message_type: 'text',
      text: "blah",
    },
  };

works for me. Seen here: https://medium.com/@pranavbhatia_26901/watson-assistant-v2-context-sharing-3ca18626ed0d


问:
How to set a custom objects attribute with Powershell?
How do I add String data to the array of the class OnePerson in order to group the data?

```<code>$people = import-csv "./people.csv"

class OnePerson {
  [String] $Info

  people () { }
}

$myPerson = New-Object -TypeName OnePerson

$manyPeople = New-Object System.Object

$myArray = @()

ForEach ($person in $people) {

  if ($person -match '[0-9]') {
    Write-host $person
    #add $person string to the array $Info of $myPerson
  }
  else {
    write-host "new person"
    write-host $person
    $myArray += $myPerson
    $myPerson = New-Object -TypeName OnePerson
  }
}

write-host $myArray
</code>```

output:

```<code>thufir@dur:~/flwor/people$
thufir@dur:~/flwor/people$ pwsh foo.ps1
new person
@{people=joe}
@{people=phone1}
@{people=phone2}
@{people=phone3}
new person
@{people=sue}
@{people=cell4}
@{people=home5}
new person
@{people=alice}
@{people=atrib6}
@{people=x7}
@{people=y9}
@{people=z10}
OnePerson OnePerson OnePerson
thufir@dur:~/flwor/people$
</code>```

答:
Example on how you can use OnePerson class and adding that element to your array is,

```<code>class OnePerson {
  [String] $Info

  OnePerson () { }
  OnePerson ([String]$newinfo) { $this.Info = $newInfo }
}

$myArray = @()
$myArray += [OnePerson]::new("John")
$myArray += [OnePerson]::new("Smith")
</code>```

Constructors you use in class have to have the same name as your class itself. Once the person has been created and added to myArray, it no longer exists on it's own, only available via reference from myArray

Body:
How do I add String data to the array of the class OnePerson in order to group the data?

$people = import-csv "./people.csv"

class OnePerson {
  [String] $Info

  people () { }
}

$myPerson = New-Object -TypeName OnePerson

$manyPeople = New-Object System.Object

$myArray = @()

ForEach ($person in $people) {

  if ($person -match '[0-9]') {
    Write-host $person
    #add $person string to the array $Info of $myPerson
  }
  else {
    write-host "new person"
    write-host $person
    $myArray += $myPerson
    $myPerson = New-Object -TypeName OnePerson
  }
}

write-host $myArray

output:

thufir@dur:~/flwor/people$
thufir@dur:~/flwor/people$ pwsh foo.ps1
new person
@{people=joe}
@{people=phone1}
@{people=phone2}
@{people=phone3}
new person
@{people=sue}
@{people=cell4}
@{people=home5}
new person
@{people=alice}
@{people=atrib6}
@{people=x7}
@{people=y9}
@{people=z10}
OnePerson OnePerson OnePerson
thufir@dur:~/flwor/people$

Body:
Example on how you can use OnePerson class and adding that element to your array is,

class OnePerson {
  [String] $Info

  OnePerson () { }
  OnePerson ([String]$newinfo) { $this.Info = $newInfo }
}

$myArray = @()
$myArray += [OnePerson]::new("John")
$myArray += [OnePerson]::new("Smith")

Constructors you use in class have to have the same name as your class itself. Once the person has been created and added to myArray, it no longer exists on it's own, only available via reference from myArray


问:
A function to check for hill or valley in a given list, without usage of Numpy or zip?

A list of numbers is identified as 'hill' if it has an ascending sequence followed by a descending sequence. Similarly, it'll be 'valley hill' if it consists of a descending sequence followed by an ascending one. Each of the sequences should be of length of at least two.

For example, a list [1,2,3,5,4] will be a hill or a list [5,4,1,2,3] will be a valley.

I'm trying to write a function, without the usage of either numpy arrays or zip function that returns a true if it identifies a hill or valley and false if it doesn't.

The code I've come up with is:

```<code>def hillovalley(n):
  if len(n)<=2:
    return False
  c = n[0]<n[1]
  x=0
  for i in range(len(n)-1):
    if c!=(n[i]<n[i+1]):
      c=n[i]<n[i+1]
      x=x+1
    if x==1:
      return True
    else:
      return False
</code>```

However, this code would fail if the input is something like [1,2,3,5,4,3,2,1] or [9,5,4,-1,-2,3,7].

Thank you for your help!

答:
def hillvalley(l):
    flag=[]
    inc=0
    for i in range(len(l)-1):
        if l[i]<=l[i+1]:
            flag.append(0)
        elif l[i]>=l[i+1]:
            flag.append(1)
    #print(flag)
    for j in range(len(flag)-1):
        if flag[j]<flag[j+1]:
            inc+=1
        elif flag[j]>flag[j+1]:
            inc+=1
    if inc==1:
        return True
    else:
        return False
```

Body:
A list of numbers is identified as 'hill' if it has an ascending sequence followed by a descending sequence. Similarly, it'll be 'valley hill' if it consists of a descending sequence followed by an ascending one. Each of the sequences should be of length of at least two.

For example, a list [1,2,3,5,4] will be a hill or a list [5,4,1,2,3] will be a valley.

I'm trying to write a function, without the usage of either numpy arrays or zip function that returns a true if it identifies a hill or valley and false if it doesn't.

The code I've come up with is:

def hillovalley(n):
  if len(n)<=2:
    return False
  c = n[0]<n[1]
  x=0
  for i in range(len(n)-1):
    if c!=(n[i]<n[i+1]):
      c=n[i]<n[i+1]
      x=x+1
    if x==1:
      return True
    else:
      return False

However, this code would fail if the input is something like [1,2,3,5,4,3,2,1] or [9,5,4,-1,-2,3,7].

Thank you for your help!


问:
How can I compare the size of three arraylists in Java?
I have three ArrayLists, let's say a, b, and c, each of which contains some elements, and I want to compare their size to see if their sizes are equal, how can I do this? Is it like as follows:

if (a.size() == b.size() == c.size()) {

  // do-something

}
```

答:
```<code>if (A.size() == B.size() && B.size() == C.size()) {
    // do something
}
</code>```

Mathematically, if a=b and b=c then a=c. So, the above condition precisely filfils your requirement.

Alternatively,

```<code>if (A.size() == B.size()) {
    if (B.size() == C.size()) {
        // do something
    }
}
</code>```

Body:
if (A.size() == B.size() && B.size() == C.size()) {
    // do something
}

Mathematically, if a=b and b=c then a=c. So, the above condition precisely filfils your requirement.

Alternatively,

if (A.size() == B.size()) {
    if (B.size() == C.size()) {
        // do something
    }
}


问:
How to count a multidimensional arrays values belongs to a certain key?
I have below array;

```<code>Array
(
    [2019-11-01] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 1
                    [category] => cat1
                )
        [1] => stdClass Object
            (
                [id] => 2
                [category] => cat2
            )

        [2] => stdClass Object
            (
                [id] => 3
                [category] => cat1
            )

        [3] => stdClass Object
            (
                [id] => 4
                [category] => cat2
            )

        [4] => stdClass Object
            (
                [id] => 5
                [category] => cat1
            )

        [5] => stdClass Object
            (
                [id] => 6
                [category] => cat2
            )

    )

[2019-11-03] => Array
    (
        [0] => stdClass Object
            (
                [id] => 7
                [category] => cat1
            )

    )

)
</code>```

And I want to found out statistics of categories.

like:

cat1 count: 4

cat2 count: 3

I am able to get the result for cat1 with the code I use below:

```<code>$cat1count = 0;

foreach ($myArray as $date => $content) {

    foreach ($content as $value) {
        if ($value->category == "cat1") {
            $cat1count++;
        }
    }
}

echo "Cat1 count:".$cat1count;
#Outputs: Cat1 count:4
</code>```

But I'm wondering,

how to get same results without hardcoding the category name as I did above "cat1"

and for each category (cat1,cat2)?

Thanks in advance!

答:
You can use a combination of array_column() to extract the category values from the data and then use array_count_values() to count how many there are in each date.

This code just displays the date and then the counts of the values...

```<code>foreach ( $myArray as $date => $content) {
    $categories = array_column($content, "category");
    echo $date.PHP_EOL;
    print_r(array_count_values($categories));
}
</code>```

If you want totals across all dates, then just add them to a totals array...

```<code>$totals = [];
foreach ( $myArray as $date => $content) {
    $categories = array_column($content, "category");
    foreach (array_count_values($categories) as $category => $count )  {
        $totals[$category] = ($totals[$category]??0) + $count;
    }
}
</code>```

Body:
I have below array;

Array
(
    [2019-11-01] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 1
                    [category] => cat1
                )
        [1] => stdClass Object
            (
                [id] => 2
                [category] => cat2
            )

        [2] => stdClass Object
            (
                [id] => 3
                [category] => cat1
            )

        [3] => stdClass Object
            (
                [id] => 4
                [category] => cat2
            )

        [4] => stdClass Object
            (
                [id] => 5
                [category] => cat1
            )

        [5] => stdClass Object
            (
                [id] => 6
                [category] => cat2
            )

    )

[2019-11-03] => Array
    (
        [0] => stdClass Object
            (
                [id] => 7
                [category] => cat1
            )

    )

)

And I want to found out statistics of categories.

like:

cat1 count: 4

cat2 count: 3

I am able to get the result for cat1 with the code I use below:

$cat1count = 0;

foreach ($myArray as $date => $content) {

    foreach ($content as $value) {
        if ($value->category == "cat1") {
            $cat1count++;
        }
    }
}

echo "Cat1 count:".$cat1count;
#Outputs: Cat1 count:4

But I'm wondering,

how to get same results without hardcoding the category name as I did above "cat1"

and for each category (cat1,cat2)?

Thanks in advance!

Body:
You can use a combination of array_column() to extract the category values from the data and then use array_count_values() to count how many there are in each date.

This code just displays the date and then the counts of the values...

foreach ( $myArray as $date => $content) {
    $categories = array_column($content, "category");
    echo $date.PHP_EOL;
    print_r(array_count_values($categories));
}

If you want totals across all dates, then just add them to a totals array...

$totals = [];
foreach ( $myArray as $date => $content) {
    $categories = array_column($content, "category");
    foreach (array_count_values($categories) as $category => $count )  {
        $totals[$category] = ($totals[$category]??0) + $count;
    }
}


问:
Query with paging by cursor causes error because of limitations for "IN filter" in cursor() method... What should be the alternative?
I am developing a twitter like microblogging system by using the following models:

```<code>class Member(db.Model):
    user = db.UserProperty(required=True)
    follower_count = db.IntegerProperty(default=0) # members following you
    following_count = db.IntegerProperty(default=0) # members you are following

class NewsItem(db.Model):
    text = db.StringProperty(required=True)
    posted_by = db.ReferenceProperty(reference_class=Member,required=True,collection_name="posted_items")
    posted_on = db.DateTimeProperty(auto_now_add=True)
    status = db.IntegerProperty(default=1) # 0: deleted

class Follow(db.Model):
    member = db.ReferenceProperty(reference_class=Member,required=True,collection_name="followings")
    followed_member = db.ReferenceProperty(reference_class=Member,required=True,collection_name="followers")
    added_on = db.DateTimeProperty(auto_now_add=True)
</code>```

In this model structure I retrieve the messages of the members that the current user follows with the following code below:

```<code>follow_log_list = Follow.gql('WHERE member = :1 ', member)
followed_member_list = []
for follow_log in follow_log_list:
    followed_member_list.append(follow_log.followed_member)

query = NewsItem.all()
query.filter('posted_by IN', followed_member_list)
query.filter('status =', 1)
query.order('-posted_on')
query.with_cursor(cursor)
newsList = query.fetch(10)

template_values['cursor'] = query.cursor()
</code>```

When query.cursor() method is called I get the following error:

"No cursor available for a MultiQuery
  (queries using "IN" or "!="
  operators)"

This is normal since in the documentation of cursors this limitation is stated clearly as:

http://code.google.com/appengine/docs/python/datastore/queries.html

"You cannot use cursors with queries that use the IN or != filter operators."

What is the alternative way of getting the posts of followed members?

Thank you,

EDIT: The posted messages were filtered by their status and ordered by their posted date... But the sample did not show it in here, I've changed it...

答:
The reason for this restriction is that IN and != queries are executed by splitting the query into multiple underlying queries, which are executed individually by the datastore, then merged together in sorted order.

If you want to do a query like this in a paginated fashion, you would have to execute the queries yourself, and do the merge yourself. To fetch a cursor, you'd need to fetch cursors from the individual sub-queries and concatenate them together. Further, you'd need to keep track of how many fetched but un-consumed results you had, so you can pick up exactly from where you left off.

As you can see, this is complicated and leads to excessively long cursor values, which is why it isn't implemented by the SDK currently. Unfortunately, it's the only practical way to do it, unless you can find a way to avoid the use of an IN clause, or drop your requirement for ordering by another one (in which case you could just execute the queries serially, paginating each).

Body:
I am developing a twitter like microblogging system by using the following models:

class Member(db.Model):
    user = db.UserProperty(required=True)
    follower_count = db.IntegerProperty(default=0) # members following you
    following_count = db.IntegerProperty(default=0) # members you are following

class NewsItem(db.Model):
    text = db.StringProperty(required=True)
    posted_by = db.ReferenceProperty(reference_class=Member,required=True,collection_name="posted_items")
    posted_on = db.DateTimeProperty(auto_now_add=True)
    status = db.IntegerProperty(default=1) # 0: deleted

class Follow(db.Model):
    member = db.ReferenceProperty(reference_class=Member,required=True,collection_name="followings")
    followed_member = db.ReferenceProperty(reference_class=Member,required=True,collection_name="followers")
    added_on = db.DateTimeProperty(auto_now_add=True)

In this model structure I retrieve the messages of the members that the current user follows with the following code below:

follow_log_list = Follow.gql('WHERE member = :1 ', member)
followed_member_list = []
for follow_log in follow_log_list:
    followed_member_list.append(follow_log.followed_member)

query = NewsItem.all()
query.filter('posted_by IN', followed_member_list)
query.filter('status =', 1)
query.order('-posted_on')
query.with_cursor(cursor)
newsList = query.fetch(10)

template_values['cursor'] = query.cursor()

When query.cursor() method is called I get the following error:

"No cursor available for a MultiQuery
  (queries using "IN" or "!="
  operators)"

This is normal since in the documentation of cursors this limitation is stated clearly as:

http://code.google.com/appengine/docs/python/datastore/queries.html

"You cannot use cursors with queries that use the IN or != filter operators."

What is the alternative way of getting the posts of followed members?

Thank you,

EDIT: The posted messages were filtered by their status and ordered by their posted date... But the sample did not show it in here, I've changed it...


问:
Spring Scheduler does not work
I have a problem with Spring's annotation based task scheduler - I can't get it working, I don't see any problem here...

application-context.xml

```<code><task:scheduler id="taskScheduler" />
<task:executor id="taskExecutor" pool-size="1" />
<task:annotation-driven executor="taskExecutor" scheduler="taskScheduler" />
</code>```

bean

```<code>@Service
public final class SchedulingTest {

    private static final Logger logger = Logger.getLogger(SchedulingTest.class);

    @Scheduled(fixedRate = 1000)
    public void test() {
        logger.debug(">>> Scheduled test service <<<");
    }

}
</code>```

答: After configuring the Schedulers, add @EnableScheduling in your main class.

ContentLicense: CC BY-SA 2.5

Title: Spring Scheduler does not work

Body:
I have a problem with Spring's annotation based task scheduler - I can't get it working, I don't see any problem here...

application-context.xml

<task:scheduler id="taskScheduler" />
<task:executor id="taskExecutor" pool-size="1" />
<task:annotation-driven executor="taskExecutor" scheduler="taskScheduler" />

bean

@Service
public final class SchedulingTest {

    private static final Logger logger = Logger.getLogger(SchedulingTest.class);

    @Scheduled(fixedRate = 1000)
    public void test() {
        logger.debug(">>> Scheduled test service <<<");
    }

}


问:
HAProxy integration with Eureka
Is it possible to integrate HAProxy with Eureka, so that Eureka Service Registry serves as list of available servers for HAProxy to load balance?
 As per this HAProxy can be configured to dynamically get list of available servers using name-servers? Can Eureka serve the purpose of a name-server?

答:
Kinda late but still:

You can scrape app hostnames and ports from eureka's rest api and dynamically update your haproxy config and then reload.

cronjob/systemd-timer to periodically call your config generation

script

systemctl reload haproxy.service

profit

Title: HAProxy integration with Eureka


问:
Not able to create List of String object in java12
```<code>List<Object> al = Arrays.asList("ABC", "XYZ");
</code>```

This code works fine in Java11 but when I try this in Java12, it gives an error Cannot cast from List to ArrayList

Any hint what I am missing?

Thanks for the help.

答:
First, we need to check whether the value of setValues is a list or nested list

ValueRange body=new ValueRange().setValues(Arrays.asList(Arrays.asList("ABC", "XYZ")));
the above will give the results [[ABC, XYZ]] -> Nested array

Instead, try like this

ValueRange body=new ValueRange().setValues(new ArrayList<>(Arrays.asList("ABC", "XYZ")));

This gives results - > [ABC, XYZ]

Body:
List<Object> al = Arrays.asList("ABC", "XYZ");

This code works fine in Java11 but when I try this in Java12, it gives an error Cannot cast from List to ArrayList

Any hint what I am missing?

Thanks for the help.


问:
Symfony 4.4 Add current locale to generateURL function
I have route configuration like this

```<code>controllers:
 resource: '../src/Controller/'
 type: annotation
 prefix:
  en: ''
  '*': '/{_locale}'
</code>```

this works very good, attribute override locale

but when i use generateURL i must always add code to get current locale and set it

how to do it automatically?

答:
```<code>controllers:
     resource: '../src/Controller/'
     type: annotation
     prefix:
       en: ''
       de: '/{_locale}'
       es: '/{_locale}'
       fr: '/{_locale}'
       hu: '/{_locale}'
       it: '/{_locale}'
       nl: '/{_locale}'
       pl: '/{_locale}'
       pt: '/{_locale}'
       ro: '/{_locale}'
       ru: '/{_locale}'
       tr: '/{_locale}'
</code>```

it work, but how to clean this code?

Body:
I have route configuration like this

controllers:
 resource: '../src/Controller/'
 type: annotation
 prefix:
  en: ''
  '*': '/{_locale}'

this works very good, attribute override locale

but when i use generateURL i must always add code to get current locale and set it

how to do it automatically?

Body:
controllers:
     resource: '../src/Controller/'
     type: annotation
     prefix:
       en: ''
       de: '/{_locale}'
       es: '/{_locale}'
       fr: '/{_locale}'
       hu: '/{_locale}'
       it: '/{_locale}'
       nl: '/{_locale}'
       pl: '/{_locale}'
       pt: '/{_locale}'
       ro: '/{_locale}'
       ru: '/{_locale}'
       tr: '/{_locale}'

it work, but how to clean this code?


问:
Variable named i386 generated by Matlab Coder
I'm generating code for a function with several variable-sized arrays. The code needs to be compiled in both linux (with gcc) and windows machines (with MinGW).

To "ensure capacity" in those variables, Matlab creates several counter variables, named i349, i350, ..., i386, ... i400. Apparently, the windows compiler doesn't like this. It throws two errors that say :

line x:   error: expected identifier or '(' before numeric constant

line y:   error: lvalue required as left operand of assignment

line y+1: error: lvalue required as increment operand

These are all solved by manually picking other variable names. While I could use some script to automatically do so, I'd rather avoid it.

Two questions:

Why does these variable names cause a problem with the compiler?

How can I tell Matlab not to generate variables with these names?

答:
If you get a name collision that isn't fixable with compiler flags you can use the ReservedNameArray config setting with MATLAB Coder:

cfg = coder.config('lib');
cfg.ReservedNameArray = 'Name1;Name2';

codegen foo.m -config cfg
```

That will cause Coder to mangle identifiers to not collide with the provided names.

Body:
If you get a name collision that isn't fixable with compiler flags you can use the ReservedNameArray config setting with MATLAB Coder:

cfg = coder.config('lib');
cfg.ReservedNameArray = 'Name1;Name2';

codegen foo.m -config cfg

That will cause Coder to mangle identifiers to not collide with the provided names.


问:
How to merge result from multiple tables in efficient way Laravel
I have to merge results from multiple tables in Laravel. Currently I am using the following way:

```<code>public function getMachines(Request $request) {
        $vendor_id = Auth::id();
        $ml_8_machine=ML8Machine::where('vendor_id','=',$vendor_id)->get();
        $ml_16_machine=ML16Machine::where('vendor_id','=',$vendor_id)->get();
        $ml_32_machine=ML32Machine::where('vendor_id','=',$vendor_id)->get();
        $ml_64_machine=ML64Machine::where('vendor_id','=',$vendor_id)->get();
        $ml_96_machine=ML96Machine::where('vendor_id','=',$vendor_id)->get();
        $ml_128_machine=ML128Machine::where('vendor_id','=',$vendor_id)->get();
        $machines = collect($ml_8_machine)
                        ->merge($ml_16_machine)
                        ->merge($ml_32_machine)
                        ->merge($ml_64_machine)
                        ->merge($ml_96_machine)
                        ->merge($ml_128_machine);
        return view('vendor.machines', compact('machines'));
    }
</code>```

I am looking for an efficient way to do the query and merge result in one collection.

答:
maybe One of these ways may help you

```<code>$vendor_id = Auth::id();

$ml_8_machine=ML8Machine::where('vendor_id','=',$vendor_id)->get();
$ml_16_machine=ML16Machine::where('vendor_id','=',$vendor_id)->get();
$ml_32_machine=ML32Machine::where('vendor_id','=',$vendor_id)->get();
$ml_64_machine=ML64Machine::where('vendor_id','=',$vendor_id)->get();
$ml_96_machine=ML96Machine::where('vendor_id','=',$vendor_id)->get();
$machines = ML128Machine::where('vendor_id','=',$vendor_id)
        ->union($ml_8_machine)
        ->union($ml_16_machine)
        ->union($ml_32_machine)
        ->union($ml_64_machine)
        ->union($ml_96_machine)
        ->get();

return view('vendor.machines', compact('machines'));
</code>```

or use raw query methods

```<code>(SELECT * from ml_8_machine where `vendor_id` = '?')
UNION
(SELECT * from ml_16_machine where `vendor_id` = '?')
</code>```

or

```<code>SELECT * from ml_8_machine, ml_16_machine where `ml_8_machine.vendor_id` = '?' AND `ml_16_machine.vendor_id` = '?'
</code>```

Body:
I have to merge results from multiple tables in Laravel. Currently I am using the following way:

public function getMachines(Request $request) {
        $vendor_id = Auth::id();
        $ml_8_machine=ML8Machine::where('vendor_id','=',$vendor_id)->get();
        $ml_16_machine=ML16Machine::where('vendor_id','=',$vendor_id)->get();
        $ml_32_machine=ML32Machine::where('vendor_id','=',$vendor_id)->get();
        $ml_64_machine=ML64Machine::where('vendor_id','=',$vendor_id)->get();
        $ml_96_machine=ML96Machine::where('vendor_id','=',$vendor_id)->get();
        $ml_128_machine=ML128Machine::where('vendor_id','=',$vendor_id)->get();
        $machines = collect($ml_8_machine)
                        ->merge($ml_16_machine)
                        ->merge($ml_32_machine)
                        ->merge($ml_64_machine)
                        ->merge($ml_96_machine)
                        ->merge($ml_128_machine);
        return view('vendor.machines', compact('machines'));
    }

I am looking for an efficient way to do the query and merge result in one collection.

Body:
maybe One of these ways may help you

$vendor_id = Auth::id();

$ml_8_machine=ML8Machine::where('vendor_id','=',$vendor_id)->get();
$ml_16_machine=ML16Machine::where('vendor_id','=',$vendor_id)->get();
$ml_32_machine=ML32Machine::where('vendor_id','=',$vendor_id)->get();
$ml_64_machine=ML64Machine::where('vendor_id','=',$vendor_id)->get();
$ml_96_machine=ML96Machine::where('vendor_id','=',$vendor_id)->get();
$machines = ML128Machine::where('vendor_id','=',$vendor_id)
        ->union($ml_8_machine)
        ->union($ml_16_machine)
        ->union($ml_32_machine)
        ->union($ml_64_machine)
        ->union($ml_96_machine)
        ->get();

return view('vendor.machines', compact('machines'));

or use raw query methods

(SELECT * from ml_8_machine where `vendor_id` = '?')
UNION
(SELECT * from ml_16_machine where `vendor_id` = '?')

or

SELECT * from ml_8_machine, ml_16_machine where `ml_8_machine.vendor_id` = '?' AND `ml_16_machine.vendor_id` = '?'


问:
Parse JSON from mixed array with Decodable Swift
```<code>JSON link https://raw.githubusercontent.com/shimuldn/Todoey/master/file.json
</code>```

JSON code

```<code>{
"report": [
     [
        {
           "name": "Delhi"
         },
        63,
        7
      ]
   ]
}
</code>```

my code

```<code>struct ApiData: Codable {
    let report: [[Details]]
}
struct Details: Codable {
    let name: String
}
</code>```

I want to access the value
decodeData.report[0][0].name

As soon as i run the code

```<code>debugDescription: "Expected to decode Dictionary<String, Any> but found a number instead.", underlyingError: nil
</code>```

When i remove

```<code>let name: String
</code>```

There is no error.

I want to get the value from the key "name" and value 63

答:
First, I'm assuming this is the data structure you want. If it's not, please update the question with your expected output data structure. (report[0][0].name is fragile and awkward to use in Swift. Create a struct that matches the data you would like to have. Then decode into that struct.)

```<code>struct ApiData: Decodable {
    let report: [Details]
}

struct Details {
    let name: String
    let value1: Int
    let value2: Int
}
</code>```

So each Details has exactly a name object and two integer values. And a report is a list of Details.

given that, you can hand-decode Details using a unkeyedContainer. To get the name field out, it is handy to make a helper struct:

```<code>extension Details: Decodable {
    struct NameField: Decodable {
        let name: String
    }

    init(from decoder: Decoder) throws {
        var container = try decoder.unkeyedContainer()
        self.name = try container.decode(NameField.self).name
        self.value1 = try container.decode(Int.self)
        self.value2 = try container.decode(Int.self)
    }
}
</code>```

Your comment notes "there is some more below name." In that case, you may want an object rather than a string here. In that case, it would look like this:

```<code>struct Person: Decodable {
    let name: String
}

struct Details {
    let person: Person
    let value1: Int
    let value2: Int
}

extension Details: Decodable {

    init(from decoder: Decoder) throws {
        var container = try decoder.unkeyedContainer()
        self.person = try container.decode(Person.self)
        self.value1 = try container.decode(Int.self)
        self.value2 = try container.decode(Int.self)
    }
}
</code>```

Finally, it's possible that the list of values is unbounded, and you want an array:

```<code>struct Details {
    let person: Person
    let values: [Int]
}
</code>```

In that case you'd decode by extracting all the values out of the unkeyedContainer:

```<code>extension Details: Decodable {
    init(from decoder: Decoder) throws {
        var container = try decoder.unkeyedContainer()
        self.person = try container.decode(Person.self)
        var values: [Int] = []
        while !container.isAtEnd {
            values.append(try container.decode(Int.self))
        }
        self.values = values
    }
}
</code>```

There are lots of ways to approach this. It all depends on how you want to use the data, and how much structure the data has.

Body:
JSON link https://raw.githubusercontent.com/shimuldn/Todoey/master/file.json

JSON code

{
"report": [
     [
        {
           "name": "Delhi"
         },
        63,
        7
      ]
   ]
}

my code

struct ApiData: Codable {
    let report: [[Details]]
}
struct Details: Codable {
    let name: String
}

I want to access the value
decodeData.report[0][0].name

As soon as i run the code

debugDescription: "Expected to decode Dictionary<String, Any> but found a number instead.", underlyingError: nil

When i remove

let name: String

There is no error.

I want to get the value from the key "name" and value 63

Body:
First, I'm assuming this is the data structure you want. If it's not, please update the question with your expected output data structure. (report[0][0].name is fragile and awkward to use in Swift. Create a struct that matches the data you would like to have. Then decode into that struct.)

struct ApiData: Decodable {
    let report: [Details]
}

struct Details {
    let name: String
    let value1: Int
    let value2: Int
}

So each Details has exactly a name object and two integer values. And a report is a list of Details.

given that, you can hand-decode Details using a unkeyedContainer. To get the name field out, it is handy to make a helper struct:

extension Details: Decodable {
    struct NameField: Decodable {
        let name: String
    }

    init(from decoder: Decoder) throws {
        var container = try decoder.unkeyedContainer()
        self.name = try container.decode(NameField.self).name
        self.value1 = try container.decode(Int.self)
        self.value2 = try container.decode(Int.self)
    }
}

Your comment notes "there is some more below name." In that case, you may want an object rather than a string here. In that case, it would look like this:

struct Person: Decodable {
    let name: String
}

struct Details {
    let person: Person
    let value1: Int
    let value2: Int
}

extension Details: Decodable {

    init(from decoder: Decoder) throws {
        var container = try decoder.unkeyedContainer()
        self.person = try container.decode(Person.self)
        self.value1 = try container.decode(Int.self)
        self.value2 = try container.decode(Int.self)
    }
}

Finally, it's possible that the list of values is unbounded, and you want an array:

struct Details {
    let person: Person
    let values: [Int]
}

In that case you'd decode by extracting all the values out of the unkeyedContainer:

extension Details: Decodable {
    init(from decoder: Decoder) throws {
        var container = try decoder.unkeyedContainer()
        self.person = try container.decode(Person.self)
        var values: [Int] = []
        while !container.isAtEnd {
            values.append(try container.decode(Int.self))
        }
        self.values = values
    }
}

There are lots of ways to approach this. It all depends on how you want to use the data, and how much structure the data has.


问:
Print a value in Python from oracle database
I have an issue when displaying  a value in python retrieved from oracle table into CLOB field:

Oracle query:

```<code>SELECT EXTRACTVALUE(xmltype(t.xml), '/DCResponse/ResponseInfo/ApplicationId')
  FROM table t
 WHERE id = 2
</code>```

Value displayed in Oracle Client

```<code>5701200
</code>```

Python code

```<code>import cx_Oracle
conn = cx_Oracle.Connection("user/pwd@localhost:1521/orcl")
cursor = conn.cursor()
cursor.execute("""SELECT EXTRACTVALUE(xmltype(t.xml),'/DCResponse/ResponseInfo/ApplicationId') FROM table t where id = 2""")
for row in cursor:
print(row)
</code>```

Python Console: Nothing is displayed!!! I want to show:5701200

Please Help.
Best Regards
Giancarlo

答:
There are only a few issues with your code :

Replace cx_Oracle.Connection with cx_Oracle.connect

Be careful about the indentation related to the print(row)

Triple double-quotes, within the SELECT statement, are redundant,
replace them with Single double-quotes

Prefer Using print(row[0]) in order to return the desired number rather than
a tuple printed.

```<code>import cx_Oracle
conn = cx_Oracle.connect('user/pwd@localhost:1521/orcl')
cursor = conn.cursor()

query  = "SELECT EXTRACTVALUE(xmltype(t.xml),'/DCResponse/ResponseInfo/ApplicationId')"
query += "  FROM tab t "
query += " WHERE t.ID = 2 "

cursor.execute( query )
for row in cursor:
    print(row[0])
</code>```

Assigning a query to a variable not required, as stated in my case, but preferable to use in order to display the long SELECT statement decently.

Body:
I have an issue when displaying  a value in python retrieved from oracle table into CLOB field:

Oracle query:

SELECT EXTRACTVALUE(xmltype(t.xml), '/DCResponse/ResponseInfo/ApplicationId')
  FROM table t
 WHERE id = 2

Value displayed in Oracle Client

5701200

Python code

import cx_Oracle
conn = cx_Oracle.Connection("user/pwd@localhost:1521/orcl")
cursor = conn.cursor()
cursor.execute("""SELECT EXTRACTVALUE(xmltype(t.xml),'/DCResponse/ResponseInfo/ApplicationId') FROM table t where id = 2""")
for row in cursor:
print(row)

Python Console: Nothing is displayed!!! I want to show:5701200

Please Help.
Best Regards
Giancarlo

Body:
There are only a few issues with your code :

Replace cx_Oracle.Connection with cx_Oracle.connect

Be careful about the indentation related to the print(row)

Triple double-quotes, within the SELECT statement, are redundant,
replace them with Single double-quotes

Prefer Using print(row[0]) in order to return the desired number rather than
a tuple printed.

import cx_Oracle
conn = cx_Oracle.connect('user/pwd@localhost:1521/orcl')
cursor = conn.cursor()

query  = "SELECT EXTRACTVALUE(xmltype(t.xml),'/DCResponse/ResponseInfo/ApplicationId')"
query += "  FROM tab t "
query += " WHERE t.ID = 2 "

cursor.execute( query )
for row in cursor:
    print(row[0])

Assigning a query to a variable not required, as stated in my case, but preferable to use in order to display the long SELECT statement decently.


问:
Cloud build permission denied when deploy to cloud run with "--set-sql-instance" argument
I'm trying to configure cloud build triggers which build maven springboot project and then deploy to cloud runs. I run into a problem where it works when i don't specify the cloud sql instance to be connected with, but when I add "--set-cloudsql-instances", "${_DATABASE_CONNECTION_NAME}" as one of the args, it throws error on cloud build as follows:

```<code>Step #1: ERROR: (gcloud.beta.run.deploy) PERMISSION_DENIED: The caller does not have permission
Finished Step #1
ERROR
ERROR: build step 1 "gcr.io/cloud-builders/gcloud" failed: exit status 1
</code>```

Following is my cloudbuild.yml

```<code>steps:
  - name: 'gcr.io/kaniko-project/executor:latest'
    args:
      - --destination=gcr.io/$PROJECT_ID/${_IMAGE_NAME}
      - --cache=true
  - name: 'gcr.io/cloud-builders/gcloud'
    args: [
      "beta", "run",
      "deploy", "${_SERVICE_NAME}-${_PROFILE}",
      "--image", "gcr.io/${PROJECT_ID}/${_IMAGE_NAME}",
      "--region", "${_REGION}",
      "--platform", "managed",
      "--set-cloudsql-instances", "${_DATABASE_CONNECTION_NAME}",
      "--allow-unauthenticated",
      "--set-env-vars", "SPRING_PROFILES_ACTIVE=${_SPRING_PROFILE},DATABASE_CONNECTION_NAME=${_DATABASE_CONNECTION_NAME},DATABASE_NAME=${_DATABASE_NAME},DATABASE_USERNAME=${_DATABASE_USERNAME},DATABASE_PASSWORD=${_DATABASE_PASSWORD},MINIO_ACCESS_KEY=${_MINIO_ACCESS_KEY},MINIO_SECRET_KEY=${_MINIO_SECRET_KEY},MINIO_HOSTNAME=${_MINIO_HOSTNAME},MINIO_PORT=${_MINIO_PORT}"
    ]
images:
  - gcr.io/${PROJECT_ID}/${_IMAGE_NAME}
</code>```

and I already set roles/permission for service account as follow:

{PROJECT_ID}-compute@developer.gserviceaccount.com : Editor, Cloud Sql Client <-- Default SA

<Cloud run service agent> : Cloud Run Service Agent, Cloud SQL Client

<Cloud Build SA> : Cloud Build SA, Cloud Run Admin

My Cloud Run service also use default service account as its SA

答:
I am using a service account to deploy a cloud run function with sql connections. I found that the service account needs the following permissions:

serviceusage.quotas.get

serviceusage.services.get

serviceusage.services.list

Body:
I'm trying to configure cloud build triggers which build maven springboot project and then deploy to cloud runs. I run into a problem where it works when i don't specify the cloud sql instance to be connected with, but when I add "--set-cloudsql-instances", "${_DATABASE_CONNECTION_NAME}" as one of the args, it throws error on cloud build as follows:

Step #1: ERROR: (gcloud.beta.run.deploy) PERMISSION_DENIED: The caller does not have permission
Finished Step #1
ERROR
ERROR: build step 1 "gcr.io/cloud-builders/gcloud" failed: exit status 1

Following is my cloudbuild.yml

steps:
  - name: 'gcr.io/kaniko-project/executor:latest'
    args:
      - --destination=gcr.io/$PROJECT_ID/${_IMAGE_NAME}
      - --cache=true
  - name: 'gcr.io/cloud-builders/gcloud'
    args: [
      "beta", "run",
      "deploy", "${_SERVICE_NAME}-${_PROFILE}",
      "--image", "gcr.io/${PROJECT_ID}/${_IMAGE_NAME}",
      "--region", "${_REGION}",
      "--platform", "managed",
      "--set-cloudsql-instances", "${_DATABASE_CONNECTION_NAME}",
      "--allow-unauthenticated",
      "--set-env-vars", "SPRING_PROFILES_ACTIVE=${_SPRING_PROFILE},DATABASE_CONNECTION_NAME=${_DATABASE_CONNECTION_NAME},DATABASE_NAME=${_DATABASE_NAME},DATABASE_USERNAME=${_DATABASE_USERNAME},DATABASE_PASSWORD=${_DATABASE_PASSWORD},MINIO_ACCESS_KEY=${_MINIO_ACCESS_KEY},MINIO_SECRET_KEY=${_MINIO_SECRET_KEY},MINIO_HOSTNAME=${_MINIO_HOSTNAME},MINIO_PORT=${_MINIO_PORT}"
    ]
images:
  - gcr.io/${PROJECT_ID}/${_IMAGE_NAME}

and I already set roles/permission for service account as follow:

{PROJECT_ID}-compute@developer.gserviceaccount.com : Editor, Cloud Sql Client <-- Default SA

<Cloud run service agent> : Cloud Run Service Agent, Cloud SQL Client

<Cloud Build SA> : Cloud Build SA, Cloud Run Admin

My Cloud Run service also use default service account as its SA


问:
How to display an array like a hypertext in node.js
I want to display rooms array like hypertext but after the first room is created it gives an error.</p>

```<code>
let rooms = [];
app.get("/rooms", function(req, res) {
    for(let i=0;i<rooms.length;i++) {
        res.send('<a href="/room/'+rooms[i]+'">'+rooms[i]+'</a> <br>');
    }
    res.send(200)
});
app.get("/room/:roomName", function(req, res) {
    let roomName = req.params.roomName;
    rooms.push(roomName);
    res.send(roomName);
});
</code>```

答:
Actually the problem is with res.send since it shows that server have responded to client. So you can try following code

app.get("/rooms", function(req, res) {
    let responseString = "";
    for(let i=0;i<rooms.length;i++) {
        responseString += (''+rooms[i]+'
');
    }
    res.status(200).send(responseString)
});
```

Body:
I want to display rooms array like hypertext but after the first room is created it gives an error.

let rooms = [];
app.get("/rooms", function(req, res) {
    for(let i=0;i<rooms.length;i++) {
        res.send(''+rooms[i]+'
');
    }
    res.send(200)
});
app.get("/room/:roomName", function(req, res) {
    let roomName = req.params.roomName;
    rooms.push(roomName);
    res.send(roomName);
});

Body:
Actually the problem is with res.send since it shows that server have responded to client. So you can try following code

app.get("/rooms", function(req, res) {
    let responseString = "";
    for(let i=0;i<rooms.length;i++) {
        responseString += ('<a href="/room/'+rooms[i]+'">'+rooms[i]+'</a> <br>');
    }
    res.status(200).send(responseString)
});


问:
Merge images into one file without creating the full image in memory
I would need to "chunk process" some Bitmaps of any size in Android. I can easily use BitmapRegionDecoder to create smaller chunks for processing, but once done, I need to reassemble them into one file. Because the final image can be any size, creating the corresponding Bitmap in memory and writing on it using a Canvas is not an option.

I have seen this thread but I would like to do this without external library (I am limited with these as using Android). Ideally I am after some kind of BitmapRegionEncoder. I do not really care about the output format as long as it is image (PNG, JPG or even BMP). I am also happy to do it in C using JNI if not possible in Java.

答:
A simple way of doing this is to store the chunks in a table structure, then read them back and write the data to back to file as image file.

Here is a sample table structure.

```<code>public class Chunk
{
    private int chunkId;
    private byte[] chunkdata;
    private int nextchunkId;
}
</code>```

Method to read a chunk from the table

```<code>private Chunk getChunk(int index){
   Chunk chunk = null;
   if(index == 1){ // this assumes that the chunk id starts from 1
      //get and return Chunk where chunkId == 1 from the table
   }
   else{
      // get and return Chunk where nextchunkId == index from the table
   }
   return chunk
}
</code>```

Now write the chunks to a binary file directly

```<code>private void mergeChunksToFile(){
   int index = 1; // this assumes that the chunk id starts from 1
   // Create a binary file in append mode to store the data, which is the image
   Chunk chunk = getChunk(index);
   while(chunk != null){
      // Here, write chunk.chunkdata to the binary file

      index = chunk.nextchunkId;

      // get the next chunk
      chunk = getChunk(index);
   }
}
</code>```

This might not be the best solution, but it should assist you have an idea of how to go about it without using any external library

Body:
A simple way of doing this is to store the chunks in a table structure, then read them back and write the data to back to file as image file.

Here is a sample table structure.

public class Chunk
{
    private int chunkId;
    private byte[] chunkdata;
    private int nextchunkId;
}

Method to read a chunk from the table

private Chunk getChunk(int index){
   Chunk chunk = null;
   if(index == 1){ // this assumes that the chunk id starts from 1
      //get and return Chunk where chunkId == 1 from the table
   }
   else{
      // get and return Chunk where nextchunkId == index from the table
   }
   return chunk
}

Now write the chunks to a binary file directly

private void mergeChunksToFile(){
   int index = 1; // this assumes that the chunk id starts from 1
   // Create a binary file in append mode to store the data, which is the image
   Chunk chunk = getChunk(index);
   while(chunk != null){
      // Here, write chunk.chunkdata to the binary file

      index = chunk.nextchunkId;

      // get the next chunk
      chunk = getChunk(index);
   }
}

This might not be the best solution, but it should assist you have an idea of how to go about it without using any external library


问:
UICollectionView inside UITableViewCell how pass data to Uicollectionviewcell
I have a tableview controller with a collectionview inside it , in the tableviewcell i implemented a collection view with horizontal scrolling, the data appears not correct

```<code>   func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = friendsCollectionView.dequeueReusableCell(withReuseIdentifier: "friends", for: indexPath) as! friendCollectioncell
    friendsCollectionView.delegate = self
    friendsCollectionView.dataSource = self

    let ava = Myfriends[indexPath.item]["ava"] as! String
    let firstname = Myfriends[indexPath.row]["firstName"] as! String
    let lastname = Myfriends[indexPath.row]["lastName"] as! String

    return cell
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return Myfriends.count
   }
</code>```

problem is in
    return Myfriends.count
always empty so not thing appears but if a change to 1 or 2. it works ok

in uitableviewcontroller:

```<code>var myFriends: [Dictionary<String, Any>] = []
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    // section 1 which includes 1 cell that shows my friends
    if indexPath.section == 0 {

        // accessing cell in main.storyboard that has id "friends". This cell stores my friends
        let cell = tableView.dequeueReusableCell(withIdentifier: "friends", for: indexPath) as! friends

        cell.Myfriends = myFriends

       }

        return cell

        // section 2 (or any other sections) that shows all the posts of the user
    } else {
return cell
}
</code>```

Thank You in advance

答:
Edit:

If I understand this right:

problem is in return Myfriends.count always empty so not thing appears but if a change to 1 or 2. it works ok

probably your collectionView(_:numberOfItemsInSection:) is called before you this cell.Myfriends = myFriends is set.

In your friends tableViewCell:

```<code>class friends: UITableViewCell .. {
    ...
    var Myfriends: [Friend] {
        didSet {
            friendsCollectionView.reloadData()
        }
    }
}
</code>```

Imho your collectionView(_:numberOfItemsInSection:) isn't called at all.

This code

```<code>friendsCollectionView.delegate = self
friendsCollectionView.dataSource = self
</code>```

in your collectionView(_:cellForItemAt:) is useless, because if this method is called, dataSource (and probably delegate) are already set correctly.

Instead, change your tableView(_:cellForRowAt:) to

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.section == 0 {
        let cell = tableView...

        cell.friendsCollectionView.delegate = cell
        cell.friendsCollectionView.dataSource = cell

        return cell
    } else {
        ...
    }
}
</code>```

or set friendsCollectionView dataSource and delegate in your friends cell, where you init your collectionView.

If that shouldn't help you, check where and how you populate your myFriends dictionary.

Besides that, I'd recommend that you create a struct Friend:

```<code>struct Friend {
    let ava: String
    let firstName: String
    let lastName: String
}
</code>```

and change your var myFriends to

var myFriends: [Friend] = []

That would make it easier and safer to access the values for your friendsCollectionCell:

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = friendsCollectionView...

    let friend = MyFriends[indexPath.item]
    let ava = friend.ava
    ...

    return cell
}
</code>```

Body:
I have a tableview controller with a collectionview inside it , in the tableviewcell i implemented a collection view with horizontal scrolling, the data appears not correct

   func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = friendsCollectionView.dequeueReusableCell(withReuseIdentifier: "friends", for: indexPath) as! friendCollectioncell
    friendsCollectionView.delegate = self
    friendsCollectionView.dataSource = self

    let ava = Myfriends[indexPath.item]["ava"] as! String
    let firstname = Myfriends[indexPath.row]["firstName"] as! String
    let lastname = Myfriends[indexPath.row]["lastName"] as! String

    return cell
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return Myfriends.count
   }

problem is in
    return Myfriends.count
always empty so not thing appears but if a change to 1 or 2. it works ok

in uitableviewcontroller:

var myFriends: [Dictionary<String, Any>] = []
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    // section 1 which includes 1 cell that shows my friends
    if indexPath.section == 0 {

        // accessing cell in main.storyboard that has id "friends". This cell stores my friends
        let cell = tableView.dequeueReusableCell(withIdentifier: "friends", for: indexPath) as! friends

        cell.Myfriends = myFriends

       }

        return cell

        // section 2 (or any other sections) that shows all the posts of the user
    } else {
return cell
}

Thank You in advance

Body:
Edit:

If I understand this right:

problem is in return Myfriends.count always empty so not thing appears but if a change to 1 or 2. it works ok

probably your collectionView(_:numberOfItemsInSection:) is called before you this cell.Myfriends = myFriends is set.

In your friends tableViewCell:

class friends: UITableViewCell .. {
    ...
    var Myfriends: [Friend] {
        didSet {
            friendsCollectionView.reloadData()
        }
    }
}

Imho your collectionView(_:numberOfItemsInSection:) isn't called at all.

This code

friendsCollectionView.delegate = self
friendsCollectionView.dataSource = self

in your collectionView(_:cellForItemAt:) is useless, because if this method is called, dataSource (and probably delegate) are already set correctly.

Instead, change your tableView(_:cellForRowAt:) to

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.section == 0 {
        let cell = tableView...

        cell.friendsCollectionView.delegate = cell
        cell.friendsCollectionView.dataSource = cell

        return cell
    } else {
        ...
    }
}

or set friendsCollectionView dataSource and delegate in your friends cell, where you init your collectionView.

If that shouldn't help you, check where and how you populate your myFriends dictionary.

Besides that, I'd recommend that you create a struct Friend:

struct Friend {
    let ava: String
    let firstName: String
    let lastName: String
}

and change your var myFriends to

var myFriends: [Friend] = []

That would make it easier and safer to access the values for your friendsCollectionCell:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = friendsCollectionView...

    let friend = MyFriends[indexPath.item]
    let ava = friend.ava
    ...

    return cell
}


答:
I think the code below fixes your problem,</p>

```<code>// Rooms must be const, didn't modified, push is enumerating not overriding.
const rooms = []

// Prefer arrow functions for better looking code
// If you don't use req, just _
app.get('/rooms', (_, res) => {
  // Map over rooms,
  const response = rooms.map(room => `<a href="${room}">${room}</a>`)
  res.send(response)
})

app.get('/room/:name', (req, res) => {
  const { name } = req.params
  rooms.push(name)
  res.send(name)
})
</code>```

Title: How to display an array like a hypertext in node.js

Body:
I think the code below fixes your problem,

// Rooms must be const, didn't modified, push is enumerating not overriding.
const rooms = []

// Prefer arrow functions for better looking code
// If you don't use req, just _
app.get('/rooms', (_, res) => {
  // Map over rooms,
  const response = rooms.map(room => `<a href="${room}">${room}</a>`)
  res.send(response)
})

app.get('/room/:name', (req, res) => {
  const { name } = req.params
  rooms.push(name)
  res.send(name)
})