问:
MySQL GROUP BY/ORDER BY problem
I have an MySQL query like this:

```<code>   SELECT
         MAX(messages.ID) as maxID,
         messages.from,
         messages.read,
               users.userName
      FROM
         messages
      LEFT OUTER JOIN
         users
              ON
              users.ID = messages.from
      WHERE
       messages.to = ?
      GROUP BY
       messages.from
      ORDER BY
       maxID DESC
</code>```

While this works fine and the messages are group by the user who sent them in DESCENDING order, I now have a problem when I want to ORDER BY the messages.read row. My code is as follows:

```<code>   SELECT
         MAX(messages.ID) as maxID,
         messages.from,
         messages.read,
               users.userName
      FROM
         messages
      LEFT OUTER JOIN
         users
              ON
              users.ID = messages.from
      WHERE
       messages.to = ?
      GROUP BY
       messages.from
      ORDER BY
             messages.read ASC,
       maxID DESC
</code>```

Now, messages.read returns the value of the row of the first message that the user send. But I need the value of the newest (highest ID) that the user send.
I know that GROUP BY groups by the first in the table, so how can I get around doing this?

Thank you very much in advance,
Fischer

答:
i don't exactly understand the meaning of the the sql, but you could use a subslect without group and group afterwords in the main select. try this:</p>

```<code>SELECT
    *
FROM
    (
        SELECT
            MAX(messages.ID) as maxID,
            messages.from,
            messages.read,
            users.userName
        FROM
            messages
        LEFT OUTER JOIN
            users
            ON
            users.ID = messages.from
        WHERE
            messages.to = ?
        ORDER BY
            messages.read ASC,
            maxID DESC
    ) AS msg
GROUP BY
   msg.from
</code>```

Title: MySQL GROUP BY/ORDER BY problem

Body:
I have an MySQL query like this:

   SELECT
         MAX(messages.ID) as maxID,
         messages.from,
         messages.read,
               users.userName
      FROM
         messages
      LEFT OUTER JOIN
         users
              ON
              users.ID = messages.from
      WHERE
       messages.to = ?
      GROUP BY
       messages.from
      ORDER BY
       maxID DESC

While this works fine and the messages are group by the user who sent them in DESCENDING order, I now have a problem when I want to ORDER BY the messages.read row. My code is as follows:

   SELECT
         MAX(messages.ID) as maxID,
         messages.from,
         messages.read,
               users.userName
      FROM
         messages
      LEFT OUTER JOIN
         users
              ON
              users.ID = messages.from
      WHERE
       messages.to = ?
      GROUP BY
       messages.from
      ORDER BY
             messages.read ASC,
       maxID DESC

Now, messages.read returns the value of the row of the first message that the user send. But I need the value of the newest (highest ID) that the user send.
I know that GROUP BY groups by the first in the table, so how can I get around doing this?

Thank you very much in advance,
Fischer

Body:
i don't exactly understand the meaning of the the sql, but you could use a subslect without group and group afterwords in the main select. try this:

SELECT
    *
FROM
    (
        SELECT
            MAX(messages.ID) as maxID,
            messages.from,
            messages.read,
            users.userName
        FROM
            messages
        LEFT OUTER JOIN
            users
            ON
            users.ID = messages.from
        WHERE
            messages.to = ?
        ORDER BY
            messages.read ASC,
            maxID DESC
    ) AS msg
GROUP BY
   msg.from


来源: stackexchange

问:
Cant read file name when Input through cmd in C ( through args[1] )
This is how I am reading my text files in cmd. It is a constraint.

```<code>>gcc -std=c99 myproject.c -o myproject
>myproject<1.txt
</code>```

What I'm trying to achieve is the file name "1.txt" as a string so that I can read the number for lines in the file.
I looked through a bunch of solutions and all of them suggest argv[1] but when I do this:

```<code>int main(int args, char*argv[]) {
printf("File: %s\n", argv[1]); }
</code>```

it prints null.

args gives 1 and argv[0] gives myproject.
I don't know what else I could try. All I want to achieve the number of lines in the given input file. Please help. Thanks!

答:
Using redirection (<) gives the data to the program on the standard input (the program sees the data just as if they were typed in by the keyboard), if you want to pass just the parameter simply delete the redirection.

```<code>myproject 1.txt
</code>```

... if you just want to 'count lines' give a try to the command wc -l, if it's a homework, just check you're dealing with the file in the correct way: Use fscanf, fgetc,  fputs, fputc, ... instead of the 'standard input' ones scanf, gets, getc, putc, ...

ContentLicense: CC BY-SA 3.0

Body:
This is how I am reading my text files in cmd. It is a constraint.

>gcc -std=c99 myproject.c -o myproject
>myproject<1.txt

What I'm trying to achieve is the file name "1.txt" as a string so that I can read the number for lines in the file.
I looked through a bunch of solutions and all of them suggest argv[1] but when I do this:

int main(int args, char*argv[]) {
printf("File: %s\n", argv[1]); }

it prints null.

args gives 1 and argv[0] gives myproject.
I don't know what else I could try. All I want to achieve the number of lines in the given input file. Please help. Thanks!

Body:
Using redirection (<) gives the data to the program on the standard input (the program sees the data just as if they were typed in by the keyboard), if you want to pass just the parameter simply delete the redirection.

myproject 1.txt

... if you just want to 'count lines' give a try to the command wc -l, if it's a homework, just check you're dealing with the file in the correct way: Use fscanf, fgetc,  fputs, fputc, ... instead of the 'standard input' ones scanf, gets, getc, putc, ...


问:
How to properly catch exceptions from C#'s HttpClient getAsync so the error says more than "One or more errors occurred"?
The following is some code that downloads a file using System.Net.Http.HttpClient

```<code>try
{
    var responseResult = new System.Net.Http.HttpClient().GetAsync(fileUrl);
    using (var memStream = responseResult.Result.Content.ReadAsStreamAsync().Result)
    {
        using (var fileStream = File.Create(saveToPath))
        {
            memStream.CopyTo(fileStream);
        }

    }
}
catch (Exception e)
{
    Console.WriteLine(e.StackTrace);
}
</code>```

Sometimes I call this and a file fails to download. In that situation, the catch is called but doesn't contain any information of the issue:

```<code>One or more errors occurred.
    at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
    at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
    at System.Threading.Tasks.Task`1.get_Result()
    at SpPrefetchIndexBuilder.FileDownloader.StartDownloads(Int32 timeout)
</code>```

How can I get it to the cause of this exception?

答:
Since you're calling .Result on the task, original exception will be held in InnerException property of catched exception. You could access it with following construct:

```<code>string message = e?.InnerException.Message ?? e.Message;
</code>```

Body:
The following is some code that downloads a file using System.Net.Http.HttpClient

try
{
    var responseResult = new System.Net.Http.HttpClient().GetAsync(fileUrl);
    using (var memStream = responseResult.Result.Content.ReadAsStreamAsync().Result)
    {
        using (var fileStream = File.Create(saveToPath))
        {
            memStream.CopyTo(fileStream);
        }

    }
}
catch (Exception e)
{
    Console.WriteLine(e.StackTrace);
}

Sometimes I call this and a file fails to download. In that situation, the catch is called but doesn't contain any information of the issue:

One or more errors occurred.
    at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
    at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
    at System.Threading.Tasks.Task`1.get_Result()
    at SpPrefetchIndexBuilder.FileDownloader.StartDownloads(Int32 timeout)

How can I get it to the cause of this exception?

Body:
Since you're calling .Result on the task, original exception will be held in InnerException property of catched exception. You could access it with following construct:

string message = e?.InnerException.Message ?? e.Message;


问:
SQL Server 2005 - character encoding issue
I'm trying to store this value : țșșțșțșțșîăâ./,șllkoăîâ= into a column in SQL Server.

The column is nvarchar(1000) and the insert statement looks like

```<code>N'țșșțșțșțșîăâ./,șllkoăîâ='
</code>```

But the data inside is still showing up like : ?????????îaâ./,?llkoaîâ=

Any ideas on what I could try ?

EDIT

I just realized that I had changed the datatype in the database , but the linq2sql mapping remained with varchar instead of nvarchar.

That's what was causing the issue - I only saw that after trying the manual insert.

Thanks.

答:
How are you adding this to your table?? In Mgmt Studio??? What statement do you use??

If you have NVARCHAR columns, you must use the N'...' syntax with the leading N prefix for this to work:

```<code>INSERT INTO dbo.YourTable(someColumn)
 VALUES(N'țșșțșțșțșîăâ')
</code>```

If you omit the N prefix, Mgmt Studio will convert this to non-Unicode VARCHAR temporarily....

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to store this value : țșșțșțșțșîăâ./,șllkoăîâ= into a column in SQL Server.

The column is nvarchar(1000) and the insert statement looks like

N'țșșțșțșțșîăâ./,șllkoăîâ='

But the data inside is still showing up like : ?????????îaâ./,?llkoaîâ=

Any ideas on what I could try ?

EDIT

I just realized that I had changed the datatype in the database , but the linq2sql mapping remained with varchar instead of nvarchar.

That's what was causing the issue - I only saw that after trying the manual insert.

Thanks.

Body:
How are you adding this to your table?? In Mgmt Studio??? What statement do you use??

If you have NVARCHAR columns, you must use the N'...' syntax with the leading N prefix for this to work:

INSERT INTO dbo.YourTable(someColumn)
 VALUES(N'țșșțșțșțșîăâ')

If you omit the N prefix, Mgmt Studio will convert this to non-Unicode VARCHAR temporarily....


问:
Easiest way to share development secrets in aspnetcore application
I want to store a development-time secret somewhere outside of my code repository, that developers are able to use without any manual tasks. (As close to Build, Run, and it will just work).

The secrets have to be configured in the aspnetcore Configuration Builder like this:

```<code>var builder = new ConfigurationBuilder();
builder.AddJsonFile("appsettings.json";
builder.AddDevelopmentSecrets(...);
</code>```

The official recommendation by the aspnetcore team seems to be to use the Secret Manager Tool. But this requires every developer to configure the secrets manually. For example, they'd have to run dotnet user-secrets set key value for every secret.

The 2nd thing I looked at was Azure KeyVault. This seemed ideal, because I'd only have to call builder.AddAzureKeyVault(...). The only problem is that I'd have to store the clientId and clientSecret to access the keyvault somewhere.

Ideally I want something that the AWS Toolkit for Visual Studio extension does. Once the extension is installed, you simply login with your AWS credentials and the extension simply injects your credentials into every official AWS call that is used.

Does Azure have anything like this? Something that allows me to inject (or access) my Azure credentials, so they can be used in the call to AddAzureKeyVault(...)? And if not, what's the closest solution that comes close to this?

答:
To extend on @juunas his answer: Visual Studio 15.5 was just released which makes this even easier. If you've logged onto your Azure account from Visual Studio (and you have installed the currently in preview Azure Services Authentication Extension), Visual Studio will simply take care of the Azure KeyVault authentication.

You only need to specify the KeyVault url in launchSettings.json under the environement variables. No need for Azure CLI, or the AppAuthentication library.

This even works on the full .NET Framework, not just ASP.NET Core.

See:

General: https://blogs.msdn.microsoft.com/visualstudio/2017/11/17/managing-secrets-securely-in-the-cloud/

ASP.NET Core Example: https://github.com/CawaMS/aspnetcore-msi-keyvault

Body:
I want to store a development-time secret somewhere outside of my code repository, that developers are able to use without any manual tasks. (As close to Build, Run, and it will just work).

The secrets have to be configured in the aspnetcore Configuration Builder like this:

var builder = new ConfigurationBuilder();
builder.AddJsonFile("appsettings.json";
builder.AddDevelopmentSecrets(...);

The official recommendation by the aspnetcore team seems to be to use the Secret Manager Tool. But this requires every developer to configure the secrets manually. For example, they'd have to run dotnet user-secrets set key value for every secret.

The 2nd thing I looked at was Azure KeyVault. This seemed ideal, because I'd only have to call builder.AddAzureKeyVault(...). The only problem is that I'd have to store the clientId and clientSecret to access the keyvault somewhere.

Ideally I want something that the AWS Toolkit for Visual Studio extension does. Once the extension is installed, you simply login with your AWS credentials and the extension simply injects your credentials into every official AWS call that is used.

Does Azure have anything like this? Something that allows me to inject (or access) my Azure credentials, so they can be used in the call to AddAzureKeyVault(...)? And if not, what's the closest solution that comes close to this?


问:
Visual Studio freezes or hangs on startup
I have been using Visual Studio for a while and found that when I open visual studio and open the project all the files that were open last time remain open.

This causes my Visual Studio to freeze or crash on startup.

I am using a lot of plugins in my installation and wonder if there is a way to prevent this from happening.

答:
I was having this issue when using the Git source-control plugin.

I ran devenv.exe /SafeMode

And then in Options -> Source Control -> Plug-in Selection made sure "None" or "Visual Studio Team Foundation Server" was selected.  After that, VS started normally.

ContentLicense: CC BY-SA 4.0


问:
There's a space when I strcpy a string into another string
I have a kind of logical assignment here in my class. So my question is when I try to strcpy() a string into another string, There's a (like space) in my new string. I don't know how to delete that, perhaps my mistake. Please help me, thank you.

This program let's you type whatever letters or symbol on your keyboard and try to capture it and count the symbol. Then, return it.

Here's my code in C

```<code>#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <string.h>
#define N 25
typedef char string[N];

int main(int argc, char *argv[])
{
    int i,j;
    int jumlah[10];

    string inputan;
    string temp;
    int counter;

    //Init
    for(i=0;i<10;i++) {
        jumlah[i]=0;
    }

    for(i=0;i<10;i++) {
        temp[i]='-';
    }

    for(i=0;i<10;i++) {
        inputan[i]='-';
    }

    do {

        system("cls");
        printf("\nMasukan kalimat: ");fflush(stdin);gets(inputan);

        if(strcmpi(inputan,"0")!=0) {
            strcpy(temp,inputan);
        }
        getch();

    }while(strcmpi(inputan,"0")!=0);

    printf("Hasil Analisa:\n\n");

    for(i=0;i<10;i++) {

        if(temp[i]!='-') {

            char c = temp[i];
            for(j=0;j<10;j++) {

                if(temp[j]!='-') {

                    if(c == temp[j])
                        counter+=1;

                }

            }

            jumlah[i] = counter;
            counter = 0;
        }

    }

    for(i=0;i<10;i++) {

        if(temp[i]!=' ' && temp[i]!='-' && temp) {
            printf("\t%c terdapat %d\n",temp[i],jumlah[i]);
        }

    }

    getch();

}
</code>```

And here's my console result:

So that's make the program will show the space symbol and count it.

And if I can ask again, how to display only one char if there's a symbol again in another index that have same symbol. Thx, forgive me if my English is not fluent.

答:
The space(s) showing up at the end of your printout are because the list of test conditions you include:

```<code>if(temp[i]!=' ' && temp[i]!='-' && temp)
</code>```

May be missing some additional conditions that need to be excluded:

1) added additional test: test[i] != 0

2) changed temp[i] != ' ' to !isspace(temp[i]), which will test against all white space.

Once these are added:

```<code>if(!isspace(temp[i]) && temp[i]!='-' && temp && (temp[i] != 0))
</code>```

The text entered is printed only down to the last non-whitespace character.

Code modifications:

I added some other minor modifications to the following code that allowed the code to be compiled in my environment.  Because my modifications use functions that are part of the C standard libraries, this should compile for you as well.
Changes also include expanding for(...) loops to accommodate the array sizes you created, enabling input up to N-1 characters as opposed to only 10.  Most of what I did includes commented explanations.

```<code>int main(int argc, char *argv[])
{
    int i,j;
    //int jumlah[10];
    int jumlah[N]; // probably meant to use N here?

    string inputan = {0};
    string temp = {0};
    int counter = 0;// initialize

    for(i=0;i<N;i++) {
        jumlah[i]=0;
    }

    for(i=0;i<N-1;i++) {
        temp[i]='-';
    }

    for(i=0;i<N-1;i++) {
        inputan[i]='-';
    }

    do {

        //system("cls");  This is fine, just does not work in my environment, so commented.
        //printf("\nMasukan kalimat: ");fflush(stdin);gets(inputan);
        printf("\nPut Sentence (or \"0\" to process): ");fflush(stdin);gets(inputan);// clarified instructions.

        if(stricmp(inputan,"0")!=0) {  //strcmpi
            strcpy(temp,inputan);
        }
        //getch(); this (or getchar()) is really not necessary here to support
        //         the flow of your application.

    }while(stricmp(inputan,"0")!=0);

    printf("Hasil Analisa:\n\n");

    for(i=0;i<N;i++) { //replace 10 with N

        if(temp[i]!='-') {

            char c = temp[i];
            for(j=0;j<N;j++) {  //replace 10 with N

                if(temp[j]!='-') {

                    if(c == temp[j])
                        //counter+=1;
                        counter++; // var++ equivalent var += 1

                }

            }

            jumlah[i] = counter;
            counter = 0;
        }

    }

    for(i=0;i<N;i++) {

        //if(temp[i]!=' ' && temp[i]!='-' && temp) { // only spaces ?
        if(!isspace(temp[i]) && temp[i]!='-' && temp && (temp[i] != 0)) { // temp[i] != 0, and exclude all white space
            printf("\t%c terdapat %d\n",temp[i],jumlah[i]);
        }

    }

    getchar();    //orig getch() not standard

}
</code>```

Addressing your question: how to display only one char if there's a symbol again in another index that have same symbol.

Displaying a list of the characters used, and the number of times used might be better handled in a separate function.  The one below can be adapted to be called in your original main function by inserting the following lines:

```<code>char *res = letterCounter("this is the string");
printf(res);
free(res);
</code>```

Just under your existing line: printf("Hasil Analisa:\n\n");
(i.e. replace all your code under that line down to the getch(); function;

```<code>char * letterCounter(const char *string)
{
    int i, j;
    int len = strlen(string);
    char *dup = StrDup(string);
    if(!dup) return NULL;
    int viewableAscii = '~' - '!'; /// range of ASCII from ! to ~ (33 - 126)
    char buf[20];
    char * results = calloc(100*strlen(string), 1);//ensure enough room
    if(!results) return NULL;
    /// caps 'A' == 65, 'Z' == 90
    /// lowr 'a' == 97, 'z' == 122
    /// all visable printables: 33 - 126
    unsigned char characterUsageCounter[viewableAscii];
    memset(characterUsageCounter, 0,viewableAscii);

    for(i=0;i<len;i++)
    {
        for(j=0;j<viewableAscii;j++)
        {
            if(dup[i]  == 33 + j)
            {
                characterUsageCounter[j]++;
            }
        }
    }
    for(i=0;i<viewableAscii;i++)
    {
        if(characterUsageCounter[i] > 0)
        {
            if(characterUsageCounter[i] == 1) sprintf(buf, "%c occurs %d time\n", i+33, characterUsageCounter[i]);
            else sprintf(buf, "%c occurs %d times\n", i+33, characterUsageCounter[i]);
            strcat(results, buf);
        }
    }

    return results;
}
</code>```

For example, if the string "this is the string" were passed as the argument to that function, the following would be output:

Body:
I have a kind of logical assignment here in my class. So my question is when I try to strcpy() a string into another string, There's a (like space) in my new string. I don't know how to delete that, perhaps my mistake. Please help me, thank you.

This program let's you type whatever letters or symbol on your keyboard and try to capture it and count the symbol. Then, return it.

Here's my code in C

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <string.h>
#define N 25
typedef char string[N];

int main(int argc, char *argv[])
{
    int i,j;
    int jumlah[10];

    string inputan;
    string temp;
    int counter;

    //Init
    for(i=0;i<10;i++) {
        jumlah[i]=0;
    }

    for(i=0;i<10;i++) {
        temp[i]='-';
    }

    for(i=0;i<10;i++) {
        inputan[i]='-';
    }

    do {

        system("cls");
        printf("\nMasukan kalimat: ");fflush(stdin);gets(inputan);

        if(strcmpi(inputan,"0")!=0) {
            strcpy(temp,inputan);
        }
        getch();

    }while(strcmpi(inputan,"0")!=0);

    printf("Hasil Analisa:\n\n");

    for(i=0;i<10;i++) {

        if(temp[i]!='-') {

            char c = temp[i];
            for(j=0;j<10;j++) {

                if(temp[j]!='-') {

                    if(c == temp[j])
                        counter+=1;

                }

            }

            jumlah[i] = counter;
            counter = 0;
        }

    }

    for(i=0;i<10;i++) {

        if(temp[i]!=' ' && temp[i]!='-' && temp) {
            printf("\t%c terdapat %d\n",temp[i],jumlah[i]);
        }

    }

    getch();

}

And here's my console result:

So that's make the program will show the space symbol and count it.

And if I can ask again, how to display only one char if there's a symbol again in another index that have same symbol. Thx, forgive me if my English is not fluent.

Body:
The space(s) showing up at the end of your printout are because the list of test conditions you include:

if(temp[i]!=' ' && temp[i]!='-' && temp)

May be missing some additional conditions that need to be excluded:

1) added additional test: test[i] != 0

2) changed temp[i] != ' ' to !isspace(temp[i]), which will test against all white space.

Once these are added:

if(!isspace(temp[i]) && temp[i]!='-' && temp && (temp[i] != 0))

The text entered is printed only down to the last non-whitespace character.

Code modifications:

I added some other minor modifications to the following code that allowed the code to be compiled in my environment.  Because my modifications use functions that are part of the C standard libraries, this should compile for you as well.
Changes also include expanding for(...) loops to accommodate the array sizes you created, enabling input up to N-1 characters as opposed to only 10.  Most of what I did includes commented explanations.

int main(int argc, char *argv[])
{
    int i,j;
    //int jumlah[10];
    int jumlah[N]; // probably meant to use N here?

    string inputan = {0};
    string temp = {0};
    int counter = 0;// initialize

    for(i=0;i<N;i++) {
        jumlah[i]=0;
    }

    for(i=0;i<N-1;i++) {
        temp[i]='-';
    }

    for(i=0;i<N-1;i++) {
        inputan[i]='-';
    }

    do {

        //system("cls");  This is fine, just does not work in my environment, so commented.
        //printf("\nMasukan kalimat: ");fflush(stdin);gets(inputan);
        printf("\nPut Sentence (or \"0\" to process): ");fflush(stdin);gets(inputan);// clarified instructions.

        if(stricmp(inputan,"0")!=0) {  //strcmpi
            strcpy(temp,inputan);
        }
        //getch(); this (or getchar()) is really not necessary here to support
        //         the flow of your application.

    }while(stricmp(inputan,"0")!=0);

    printf("Hasil Analisa:\n\n");

    for(i=0;i<N;i++) { //replace 10 with N

        if(temp[i]!='-') {

            char c = temp[i];
            for(j=0;j<N;j++) {  //replace 10 with N

                if(temp[j]!='-') {

                    if(c == temp[j])
                        //counter+=1;
                        counter++; // var++ equivalent var += 1

                }

            }

            jumlah[i] = counter;
            counter = 0;
        }

    }

    for(i=0;i<N;i++) {

        //if(temp[i]!=' ' && temp[i]!='-' && temp) { // only spaces ?
        if(!isspace(temp[i]) && temp[i]!='-' && temp && (temp[i] != 0)) { // temp[i] != 0, and exclude all white space
            printf("\t%c terdapat %d\n",temp[i],jumlah[i]);
        }

    }

    getchar();    //orig getch() not standard

}

Addressing your question: how to display only one char if there's a symbol again in another index that have same symbol.

Displaying a list of the characters used, and the number of times used might be better handled in a separate function.  The one below can be adapted to be called in your original main function by inserting the following lines:

char *res = letterCounter("this is the string");
printf(res);
free(res);

Just under your existing line: printf("Hasil Analisa:\n\n");
(i.e. replace all your code under that line down to the getch(); function;

char * letterCounter(const char *string)
{
    int i, j;
    int len = strlen(string);
    char *dup = StrDup(string);
    if(!dup) return NULL;
    int viewableAscii = '~' - '!'; /// range of ASCII from ! to ~ (33 - 126)
    char buf[20];
    char * results = calloc(100*strlen(string), 1);//ensure enough room
    if(!results) return NULL;
    /// caps 'A' == 65, 'Z' == 90
    /// lowr 'a' == 97, 'z' == 122
    /// all visable printables: 33 - 126
    unsigned char characterUsageCounter[viewableAscii];
    memset(characterUsageCounter, 0,viewableAscii);

    for(i=0;i<len;i++)
    {
        for(j=0;j<viewableAscii;j++)
        {
            if(dup[i]  == 33 + j)
            {
                characterUsageCounter[j]++;
            }
        }
    }
    for(i=0;i<viewableAscii;i++)
    {
        if(characterUsageCounter[i] > 0)
        {
            if(characterUsageCounter[i] == 1) sprintf(buf, "%c occurs %d time\n", i+33, characterUsageCounter[i]);
            else sprintf(buf, "%c occurs %d times\n", i+33, characterUsageCounter[i]);
            strcat(results, buf);
        }
    }

    return results;
}

For example, if the string "this is the string" were passed as the argument to that function, the following would be output:


问:
What happens when I import a namespace in XAML?
I have a software project I am working on in WPF with several other "Helper" assemblies, structured as follows:

Controls (WPF Custom Control Library)

Library (C# Class Library)

Main Project (WPF Application)

Within the "Controls" assembly, I have several namespaces grouping related types of controls together. This makes it easy to manage which code is where in this assembly, since the namespaces are the same as the folder names.

However, when I am using these controls in other parts of the project, this can get a little confusing, particularly as I sometimes have to use multiple namespace declarations in the same file to reference different parts of the "Controls" assembly.

I have been wondering whether it would make more sense to put all of my controls into a more centralised namespace that I can use everywhere. The barrier against doing this is that every time I use that namespace it would reference all of the controls in the assembly. However, it would make my XAML a lot cleaner.

So, what actually happens when I import a namespace reference in XAML? Does it work the same way as in C#? What happens if I have a bunch of unused references sitting around? And would it be okay from a performance perspective if I put all of my controls into the same namespace?

Alternatively, am I just being silly and asking completely the wrong question?

答:
I have been wondering whether it would make more sense to put all of my controls into a more centralised namespace that I can use everywhere.

There's really no need to do that.

The barrier against doing this is that every time I use that namespace it would reference all of the controls in the assembly. [...] So, what actually happens when I import a namespace reference in XAML? [...] What happens if I have a bunch of unused references sitting around?

Nothing significant. XAML namespaces are just the mechanism by which object references get resolved at compile-time. Any unused references are ultimately ignored by the compiler. It has no impact upon performance.

And would it be okay from a performance perspective if I put all of my controls into the same namespace?

Performance wouldn't be affected either way, but I would suggest keeping your existing file & folder structure.

What you could do is make use of an XmlnsDefinitionAttribute to put controls from different C# namespaces into the same logical XAML namespace. This attribute is placed in the AssemblyInfo.cs file, like so:

```<code>[assembly: XmlnsDefinition("http://mycompany.com/controls", "MyCompany.Controls.Core")]
[assembly: XmlnsDefinition("http://mycompany.com/controls", "MyCompany.Controls.Primitives")]
</code>```

In an assembly that references this assembly, you can then do something like the following:

```<code>...
xmlns:mycontrols="http://mycompany.com/controls"
...
<mycontrols:Foo ... />
<mycontrols:Bar ... />
</code>```

Hence the Foo control could live in the C# namespace MyCompany.Controls.Core and the Bar control could live in the C# namespace MyCompany.Controls.Primitives, but both could be referenced using the same XAML namespace (http://mycompany.com/controls, here aliased with the mycontrols prefix).

Body:
I have been wondering whether it would make more sense to put all of my controls into a more centralised namespace that I can use everywhere.

There's really no need to do that.

The barrier against doing this is that every time I use that namespace it would reference all of the controls in the assembly. [...] So, what actually happens when I import a namespace reference in XAML? [...] What happens if I have a bunch of unused references sitting around?

Nothing significant. XAML namespaces are just the mechanism by which object references get resolved at compile-time. Any unused references are ultimately ignored by the compiler. It has no impact upon performance.

And would it be okay from a performance perspective if I put all of my controls into the same namespace?

Performance wouldn't be affected either way, but I would suggest keeping your existing file & folder structure.

What you could do is make use of an XmlnsDefinitionAttribute to put controls from different C# namespaces into the same logical XAML namespace. This attribute is placed in the AssemblyInfo.cs file, like so:

[assembly: XmlnsDefinition("http://mycompany.com/controls", "MyCompany.Controls.Core")]
[assembly: XmlnsDefinition("http://mycompany.com/controls", "MyCompany.Controls.Primitives")]

In an assembly that references this assembly, you can then do something like the following:

...
xmlns:mycontrols="http://mycompany.com/controls"
...
<mycontrols:Foo ... />
<mycontrols:Bar ... />

Hence the Foo control could live in the C# namespace MyCompany.Controls.Core and the Bar control could live in the C# namespace MyCompany.Controls.Primitives, but both could be referenced using the same XAML namespace (http://mycompany.com/controls, here aliased with the mycontrols prefix).


问:
Can't install PEAR on Windows 7, Structures/Graph error
I just did a clean install of Windows 7. I've installed Apache, Mysql
and PHP 5.3.5 all separated (not using XAMPP/others).

I'm getting the following error in the install: ERROR: unable to unpack phar://C:/Web/php-5.3.5/PEAR/go-pear.phar/PEAR/go-pear-tarballs/Structures_Graph-1.0.2.tar

The full stack trace is:

```<code>C:\Web\php-5.3.5>go-pear.bat

Are you installing a system-wide PEAR or a local copy?
(system|local) [system] : system

Below is a suggested file layout for your new PEAR installation.  To change individual locations, type the number in front of the directory.  Type 'all' to change all of them or simply press Enter to accept these locations.

 1. Installation base ($prefix)                   : C:\Web\php-5.3.5
 2. Temporary directory for processing            : C:\Web\php-5.3.5\tmp
 3. Temporary directory for downloads             : C:\Web\php-5.3.5\tmp
 4. Binaries directory                            : C:\Web\php-5.3.5
 5. PHP code directory ($php_dir)                 : C:\Web\php-5.3.5\pear
 6. Documentation directory                       : C:\Web\php-5.3.5\docs
 7. Data directory                                : C:\Web\php-5.3.5\data
 8. User-modifiable configuration files directory : C:\Web\php-5.3.5\cfg
 9. Public Web Files directory                    : C:\Web\php-5.3.5\www
10. Tests directory                               : C:\Web\php-5.3.5\tests
11. Name of configuration file                    : C:\Web\php-5.3.5\pear.ini
12. Path to CLI php.exe                           : C:\Web\php-5.3.5

1-12, 'all' or Enter to continue:
Beginning install...
Configuration written to C:\Web\php-5.3.5\pear.ini...
Initialized registry...
Preparing to install...
installing phar://C:/Web/php-5.3.5/PEAR/go-pear.phar/PEAR/go-pear-tarballs/Archive_Tar-1.3.3.tar...
installing phar://C:/Web/php-5.3.5/PEAR/go-pear.phar/PEAR/go-pear-tarballs/Console_Getopt-1.2.3.tar...
installing phar://C:/Web/php-5.3.5/PEAR/go-pear.phar/PEAR/go-pear-tarballs/PEAR-1.8.0.tar...
installing phar://C:/Web/php-5.3.5/PEAR/go-pear.phar/PEAR/go-pear-tarballs/Structures_Graph-1.0.2.tar...
installing phar://C:/Web/php-5.3.5/PEAR/go-pear.phar/PEAR/go-pear-tarballs/XML_Util-1.2.1.tar...
install ok: channel://pear.php.net/Archive_Tar-1.3.3
install ok: channel://pear.php.net/Console_Getopt-1.2.3
ERROR: unable to unpack phar://C:/Web/php-5.3.5/PEAR/go-pear.phar/PEAR/go-pear-tarballs/Structures_Graph-1.0.2.tar
install ok: channel://pear.php.net/XML_Util-1.2.1
install ok: channel://pear.php.net/PEAR-1.8.0
PEAR: Optional feature webinstaller available (PEAR's web-based installer)
PEAR: Optional feature gtkinstaller available (PEAR's PHP-GTK-based installer)
PEAR: Optional feature gtk2installer available (PEAR's' PHP-GTK2-based installer)

PEAR: To install optional features use "pear install pear/PEAR#featurename"

** WARNING! Old version found at C:\Web\php-5.3.5, please remove it or be sure t
o use the new c:\web\php-5.3.5\pear.bat command

The 'pear' command is now at your service at c:\web\php-5.3.5\pear.bat

* WINDOWS ENVIRONMENT VARIABLES *
For convenience, a REG file is available under C:\Web\php-5.3.5\PEAR_ENV.reg .
This file creates ENV variables for the current user.

Double-click this file to add it to the current user registry.

C:\Web\php-5.3.5>
</code>```

答:
I've been having many issues after upgrading my wampserver which now comes with php 5.3.5.

I have solved the problem by installing php 5.3.0 alongside and using it to run the installer found at http://pear.php.net/go-pear. I set the php cli setting to the php5.3.5 folder without any issues.

This might be wampserver specific. To gauge if you are experiencing a similar problem here are some of the issues I encountered:

Using the go-pear.bat packaged with php5.3.5 i had the same unable to unpack error as the original poster.

Using the go-pear.bat packaged with php5.3.0 i was able to complete the installation but the pear installer was v1.8.0

Using the installer on the pear site mentioned previously with php5.3.5 i had an error "Warning: rmdir(D:\temp): Directory not empty in D:\go-pear.php on line 1237". Looking at the stack trace the Archive_Tar class was throwing an error and the installer was failing to clean up after itself.

Body:
I just did a clean install of Windows 7. I've installed Apache, Mysql
and PHP 5.3.5 all separated (not using XAMPP/others).

I'm getting the following error in the install: ERROR: unable to unpack phar://C:/Web/php-5.3.5/PEAR/go-pear.phar/PEAR/go-pear-tarballs/Structures_Graph-1.0.2.tar

The full stack trace is:

C:\Web\php-5.3.5>go-pear.bat

Are you installing a system-wide PEAR or a local copy?
(system|local) [system] : system

Below is a suggested file layout for your new PEAR installation.  To change individual locations, type the number in front of the directory.  Type 'all' to change all of them or simply press Enter to accept these locations.

 1. Installation base ($prefix)                   : C:\Web\php-5.3.5
 2. Temporary directory for processing            : C:\Web\php-5.3.5\tmp
 3. Temporary directory for downloads             : C:\Web\php-5.3.5\tmp
 4. Binaries directory                            : C:\Web\php-5.3.5
 5. PHP code directory ($php_dir)                 : C:\Web\php-5.3.5\pear
 6. Documentation directory                       : C:\Web\php-5.3.5\docs
 7. Data directory                                : C:\Web\php-5.3.5\data
 8. User-modifiable configuration files directory : C:\Web\php-5.3.5\cfg
 9. Public Web Files directory                    : C:\Web\php-5.3.5\www
10. Tests directory                               : C:\Web\php-5.3.5\tests
11. Name of configuration file                    : C:\Web\php-5.3.5\pear.ini
12. Path to CLI php.exe                           : C:\Web\php-5.3.5

1-12, 'all' or Enter to continue:
Beginning install...
Configuration written to C:\Web\php-5.3.5\pear.ini...
Initialized registry...
Preparing to install...
installing phar://C:/Web/php-5.3.5/PEAR/go-pear.phar/PEAR/go-pear-tarballs/Archive_Tar-1.3.3.tar...
installing phar://C:/Web/php-5.3.5/PEAR/go-pear.phar/PEAR/go-pear-tarballs/Console_Getopt-1.2.3.tar...
installing phar://C:/Web/php-5.3.5/PEAR/go-pear.phar/PEAR/go-pear-tarballs/PEAR-1.8.0.tar...
installing phar://C:/Web/php-5.3.5/PEAR/go-pear.phar/PEAR/go-pear-tarballs/Structures_Graph-1.0.2.tar...
installing phar://C:/Web/php-5.3.5/PEAR/go-pear.phar/PEAR/go-pear-tarballs/XML_Util-1.2.1.tar...
install ok: channel://pear.php.net/Archive_Tar-1.3.3
install ok: channel://pear.php.net/Console_Getopt-1.2.3
ERROR: unable to unpack phar://C:/Web/php-5.3.5/PEAR/go-pear.phar/PEAR/go-pear-tarballs/Structures_Graph-1.0.2.tar
install ok: channel://pear.php.net/XML_Util-1.2.1
install ok: channel://pear.php.net/PEAR-1.8.0
PEAR: Optional feature webinstaller available (PEAR's web-based installer)
PEAR: Optional feature gtkinstaller available (PEAR's PHP-GTK-based installer)
PEAR: Optional feature gtk2installer available (PEAR's' PHP-GTK2-based installer)

PEAR: To install optional features use "pear install pear/PEAR#featurename"

** WARNING! Old version found at C:\Web\php-5.3.5, please remove it or be sure t
o use the new c:\web\php-5.3.5\pear.bat command

The 'pear' command is now at your service at c:\web\php-5.3.5\pear.bat

* WINDOWS ENVIRONMENT VARIABLES *
For convenience, a REG file is available under C:\Web\php-5.3.5\PEAR_ENV.reg .
This file creates ENV variables for the current user.

Double-click this file to add it to the current user registry.

C:\Web\php-5.3.5>


问:
SSRS Custom Assemblies could not be loaded under Visual Studio 2017
I have just installed VS 2017 and moved my SSRS project from VS 2015 to 2017. I have a custom assembly which is working fine under VS 2015, but not 2017. It says

Error while loading code module: 'CustomLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. Details: Could not load file or assembly 'CustomLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

I had exact same problem under VS 2015 and the solution was moving my custom dll under

C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\PrivateAssemblies

So, I have moved my custom dll under

C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\PrivateAssemblies

which I believe is the correct path for VS 2017 and check file/folder permissions and set them identical, but no way, it still throws same error.

What am I missing?

答:
This now requires two locations for the dll - the first works for new VS2017 RS projects, but upgraded projects also need the dll in the second location:

```<code>C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\CommonExtensions\Microsoft\SSRS
</code>```

```<code>C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\PrivateAssemblies
</code>```

Body:
This now requires two locations for the dll - the first works for new VS2017 RS projects, but upgraded projects also need the dll in the second location:

C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\CommonExtensions\Microsoft\SSRS

C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\PrivateAssemblies


问:
Ionic 3 App - Best way to work with non-ionic html components
Ionic library offers a big collection of components and the documentation is great. So, if you need a button with a custom function called onClick, you quickly find the best way to do it by placing the button into a page.html (home.html in my case)

```<code><button ion-button (click)="logEvent(this)"> Button</button>
</code>```

and adding a function to the into a page.ts (home.ts in my case)

```<code>import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController) {

  }

  logEvent(event) {
    console.log(event);
  }
}
</code>```

But what is the best way to work with non-ionic elements such as a standard html checkbox element? Because Ionic 3 does not have a star rating element, I have to import a third-party solution for this element.

The rendering works well and the star rating looks like this

Now my problem is, I need to bind an onClick function to the inputs of the checkbox element. Having some minor experience in JavaScript, I tend to simply define a script section in the page.html and do some regular JavaScript binding. This, however, does not feel right, and, does not even seem to work.

I would appreciate if someone with experience could point out the most likely obvious way to do it as I could not google it. Obviously I am searching the wrong direction.

The checkbox element looks like this:

```<code><div class="wrapper">
  <input type="checkbox" id="st1" value="1" />
  <label for="st1"></label>
  <input type="checkbox" id="st2" value="2" />
  <label for="st2"></label>
  <input type="checkbox" id="st3" value="3" />
  <label for="st3"></label>
  <input type="checkbox" id="st4" value="4" />
  <label for="st4"></label>
  <input type="checkbox" id="st5" value="5" />
  <label for="st5"></label>
</div>
</code>```

答:
I highly recommend using ionic2-rating component. I have used it one of my Ionic 3 / Angular 5 app and it is working perfectly fine.If you have any issues with it please let me know.

.html

```<code><rating [(ngModel)]="rate"
        readOnly="false" <!--default value-->
        max="5" <!--default value-->
        emptyStarIconName="star-outline" <!--default value-->
        halfStarIconName="star-half" <!--default value-->
        starIconName="star" <!--default value-->
        nullable="false" <!--default value-->
        (ngModelChange)="onModelChange($event)"> <!--use it when you need to do something when user clicks on a star. in case you only need to change ngModel property, this property can be ommited.-->
</rating>
</code>```

Body:
Ionic library offers a big collection of components and the documentation is great. So, if you need a button with a custom function called onClick, you quickly find the best way to do it by placing the button into a page.html (home.html in my case)

<button ion-button (click)="logEvent(this)"> Button</button>

and adding a function to the into a page.ts (home.ts in my case)

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController) {

  }

  logEvent(event) {
    console.log(event);
  }
}

But what is the best way to work with non-ionic elements such as a standard html checkbox element? Because Ionic 3 does not have a star rating element, I have to import a third-party solution for this element.

The rendering works well and the star rating looks like this

Now my problem is, I need to bind an onClick function to the inputs of the checkbox element. Having some minor experience in JavaScript, I tend to simply define a script section in the page.html and do some regular JavaScript binding. This, however, does not feel right, and, does not even seem to work.

I would appreciate if someone with experience could point out the most likely obvious way to do it as I could not google it. Obviously I am searching the wrong direction.

The checkbox element looks like this:

  <input type="checkbox" id="st1" value="1" />

  <input type="checkbox" id="st2" value="2" />

  <input type="checkbox" id="st3" value="3" />

  <input type="checkbox" id="st4" value="4" />

  <input type="checkbox" id="st5" value="5" />

Body:
I highly recommend using ionic2-rating component. I have used it one of my Ionic 3 / Angular 5 app and it is working perfectly fine.If you have any issues with it please let me know.

.html

<rating [(ngModel)]="rate"
        readOnly="false" <!--default value-->
        max="5" <!--default value-->
        emptyStarIconName="star-outline" <!--default value-->
        halfStarIconName="star-half" <!--default value-->
        starIconName="star" <!--default value-->
        nullable="false" <!--default value-->
        (ngModelChange)="onModelChange($event)"> <!--use it when you need to do something when user clicks on a star. in case you only need to change ngModel property, this property can be ommited.-->
</rating>


问:
Test used bean instead mock object
I start work with Spring and Mockito.
I use JUnit, Mockito, Spring boot.
I have test for controller, and try to make it work.

```<code>@RunWith(SpringRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = CommonConfiguration.class)
@ActiveProfiles(profiles = "embedded")
public class UserController_IntegrationWContainer_Tests {

private MockMvc mockMvc;

@Autowired
private WebApplicationContext wac;

@MockBean(name = "SignatureValidator")
private SignatureValidator signatureValidator;

private ObjectMapper objectMapper;
...

@Before
public void before() {
    MockitoAnnotations.initMocks(this);
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).dispatchOptions(true).build();
    this.objectMapper = new ObjectMapper();
}

@Test
public void createConfirmation() throws Exception {

    ...

    ConfirmationDetails signature = new ConfirmationDetails("signature");
    when(this.signatureValidator.validateAndEnforceSignature(signature))
            .thenReturn("advanced");

    mockMvc.perform(post("/distributions/1/receive")
            .content(this.objectMapper.writeValueAsBytes(signature))
            .contentType(MediaType.APPLICATION_JSON)
    .andExpect(status().is(201));
}
</code>```

This test class used for test UserController.

```<code>@RestController
@Validated
@Transactional
public class UserController {

    private final static Logger logger = LoggerFactory.getLogger(UserController.class);
    private UserService userService;
    private SignatureValidator signatureValidator;
    ...

    @Autowired
    public UserController(UserService userService, SignatureValidator signatureValidator, ...) {
        this.userService = userService;
        this.signatureValidator = signatureValidator;
        ...
    }
    @RequestMapping(
            value = "/distributions/{distributionId}/receive",
            method = RequestMethod.POST,
            produces = "application/json")
    public ResponseEntity<Object> confirmReceipt(
            @RequestBody ConfirmationDetails signature,
            @Context HttpServletRequest request,
            @Digits(fraction = 0, integer = 19, message = "ID cannot exceed 19 digits")
            @Min(value = 1, message = "ID must be > 0")
            @PathVariable("distributionId") Long distributionId) {

        logger.info("Processing request confirmReceipt");

        /*for this string I want to use stub. but stub doesn't work*/
        String advancedSignature = signatureValidator.validateAndEnforceSignature(signature);

        ...

        Map<String, String> resultsMap = new HashMap<>();
        resultsMap.put("code", "RECEIPT_SIGNED");
        resultsMap.put("message", "Distribution download confirmed");

        return new ResponseEntity<>(resultsMap, HttpStatus.CREATED);
    }
}
</code>```

SignatureValidator interface:

```<code>public interface SignatureValidator {

    @SuppressWarnings("unchecked")
    String validateAndEnforceSignature(ConfirmationDetails signature);
}
</code>```

Two implementations of SignatureValidator:

```<code>@Component
public class SignatureValidatorIml extends WebServiceGatewaySupport implements SignatureValidator {
...
}

@Component
public class SignatureValidatorJinn extends WebServiceGatewaySupport implements SignatureValidator {
...
}
</code>```

Spring decide what implementation of bean need to inject using JinnServerConfiguration:

```<code>@Configuration
public class JinnServerConfiguration {

    final Environment env;

    @Autowired
    public JinnServerConfiguration(Environment env) {
        this.env = env;
    }

    @Bean
    public Jaxb2Marshaller marshaller() {
        ...
        return marshaller;
    }

    @Bean
    public HttpComponentsMessageSender messageSender() {
        ...
        return messageSender;
    }

    @Bean
    @Profile("!local")
    public SignatureValidator signatureValidator(Jaxb2Marshaller marshaller,
                                                 HttpComponentsMessageSender messageSender) {
        SignatureValidatorJinn signatureValidatorJinn = new SignatureValidatorJinn(env);
        signatureValidatorJinn.setDefaultUri("http://.../SignatureValidationService");
        signatureValidatorJinn.setMarshaller(marshaller);
        signatureValidatorJinn.setUnmarshaller(marshaller);
        signatureValidatorJinn.setMessageSender(messageSender);
        return signatureValidatorJinn;
    }

    @Bean
    @Profile("local")
    public SignatureValidator signatureValidatorLocal(){
        return new SignatureValidatorIml();
    }

}
</code>```

For all services in UserController mock works fine.
But when I want to mock SignatureValidator, it is not work.
In debug mode I see, that in test it used mocked bean, but then UserController runs it used Spring bean (SignatureValidatorJinn) instead mocked bean.

Why it used SignatureValidatorJinn? I think it so because test class has annotation: @ActiveProfiles(profiles = "embedded"). And according to JinnServerConfiguration "@Profile("!local")" spring made this decision.

This test worked fine, until annotation @Component has been added to SignatureValidatorIml class and to SignatureValidatorJinn class.

I can't understand, why it used Spring bean. Because other service mock work fine. I found many information about mock, but can't find a solution of this problem.

I try to do next thing, but they didn't help:

don't use MockitoAnnotations.initMocks(this);

qualify current bean for SignatureValidator: Jinn or Iml;

use @InjectMocks UserController userController;

EDIT

If I delete @Component annotation in SignatureValidatorJinn and SignatureValidatorIml, it works nice. But I can't understand why is it so.

For example, class UserService annotated with "@Service". And it is successfully mocking.

So, maybe somebody can explain, why "@Component" doesn't allow to create mock object in this case?

EDIT2

The problem was solved

I can't delete annotation component, because without this annotation, DI in my application will not work.
I find decision. Bean is called signatureValidator. And I use name SignatureValidator to specificate bean to mock. That was mistake ) So with follow construction it works fine:

```<code>@MockBean(name = "signatureValidator")
private SignatureValidator signatureValidator;
</code>```

Thanks everyone for replies :)

答:
You must not call

```<code>MockitoAnnotations.initMocks(this);
</code>```

because the SpringRunner already initializes the mocks. By calling initMocks you assign a new object to signatureValidator. All Mockito actions like when and verify are performed on the new object, but Spring still uses the "old" SignatureValidator that was created by the SpringRunner.

Title: Test used bean instead mock object

Body:
I start work with Spring and Mockito.
I use JUnit, Mockito, Spring boot.
I have test for controller, and try to make it work.

@RunWith(SpringRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = CommonConfiguration.class)
@ActiveProfiles(profiles = "embedded")
public class UserController_IntegrationWContainer_Tests {

private MockMvc mockMvc;

@Autowired
private WebApplicationContext wac;

@MockBean(name = "SignatureValidator")
private SignatureValidator signatureValidator;

private ObjectMapper objectMapper;
...

@Before
public void before() {
    MockitoAnnotations.initMocks(this);
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).dispatchOptions(true).build();
    this.objectMapper = new ObjectMapper();
}

@Test
public void createConfirmation() throws Exception {

    ...

    ConfirmationDetails signature = new ConfirmationDetails("signature");
    when(this.signatureValidator.validateAndEnforceSignature(signature))
            .thenReturn("advanced");

    mockMvc.perform(post("/distributions/1/receive")
            .content(this.objectMapper.writeValueAsBytes(signature))
            .contentType(MediaType.APPLICATION_JSON)
    .andExpect(status().is(201));
}

This test class used for test UserController.

@RestController
@Validated
@Transactional
public class UserController {

    private final static Logger logger = LoggerFactory.getLogger(UserController.class);
    private UserService userService;
    private SignatureValidator signatureValidator;
    ...

    @Autowired
    public UserController(UserService userService, SignatureValidator signatureValidator, ...) {
        this.userService = userService;
        this.signatureValidator = signatureValidator;
        ...
    }
    @RequestMapping(
            value = "/distributions/{distributionId}/receive",
            method = RequestMethod.POST,
            produces = "application/json")
    public ResponseEntity<Object> confirmReceipt(
            @RequestBody ConfirmationDetails signature,
            @Context HttpServletRequest request,
            @Digits(fraction = 0, integer = 19, message = "ID cannot exceed 19 digits")
            @Min(value = 1, message = "ID must be > 0")
            @PathVariable("distributionId") Long distributionId) {

        logger.info("Processing request confirmReceipt");

        /*for this string I want to use stub. but stub doesn't work*/
        String advancedSignature = signatureValidator.validateAndEnforceSignature(signature);

        ...

        Map<String, String> resultsMap = new HashMap<>();
        resultsMap.put("code", "RECEIPT_SIGNED");
        resultsMap.put("message", "Distribution download confirmed");

        return new ResponseEntity<>(resultsMap, HttpStatus.CREATED);
    }
}

SignatureValidator interface:

public interface SignatureValidator {

    @SuppressWarnings("unchecked")
    String validateAndEnforceSignature(ConfirmationDetails signature);
}

Two implementations of SignatureValidator:

@Component
public class SignatureValidatorIml extends WebServiceGatewaySupport implements SignatureValidator {
...
}

@Component
public class SignatureValidatorJinn extends WebServiceGatewaySupport implements SignatureValidator {
...
}

Spring decide what implementation of bean need to inject using JinnServerConfiguration:

@Configuration
public class JinnServerConfiguration {

    final Environment env;

    @Autowired
    public JinnServerConfiguration(Environment env) {
        this.env = env;
    }

    @Bean
    public Jaxb2Marshaller marshaller() {
        ...
        return marshaller;
    }

    @Bean
    public HttpComponentsMessageSender messageSender() {
        ...
        return messageSender;
    }

    @Bean
    @Profile("!local")
    public SignatureValidator signatureValidator(Jaxb2Marshaller marshaller,
                                                 HttpComponentsMessageSender messageSender) {
        SignatureValidatorJinn signatureValidatorJinn = new SignatureValidatorJinn(env);
        signatureValidatorJinn.setDefaultUri("http://.../SignatureValidationService");
        signatureValidatorJinn.setMarshaller(marshaller);
        signatureValidatorJinn.setUnmarshaller(marshaller);
        signatureValidatorJinn.setMessageSender(messageSender);
        return signatureValidatorJinn;
    }

    @Bean
    @Profile("local")
    public SignatureValidator signatureValidatorLocal(){
        return new SignatureValidatorIml();
    }

}

For all services in UserController mock works fine.
But when I want to mock SignatureValidator, it is not work.
In debug mode I see, that in test it used mocked bean, but then UserController runs it used Spring bean (SignatureValidatorJinn) instead mocked bean.

Why it used SignatureValidatorJinn? I think it so because test class has annotation: @ActiveProfiles(profiles = "embedded"). And according to JinnServerConfiguration "@Profile("!local")" spring made this decision.

This test worked fine, until annotation @Component has been added to SignatureValidatorIml class and to SignatureValidatorJinn class.

I can't understand, why it used Spring bean. Because other service mock work fine. I found many information about mock, but can't find a solution of this problem.

I try to do next thing, but they didn't help:

don't use MockitoAnnotations.initMocks(this);

qualify current bean for SignatureValidator: Jinn or Iml;

use @InjectMocks UserController userController;

EDIT

If I delete @Component annotation in SignatureValidatorJinn and SignatureValidatorIml, it works nice. But I can't understand why is it so.

For example, class UserService annotated with "@Service". And it is successfully mocking.

So, maybe somebody can explain, why "@Component" doesn't allow to create mock object in this case?

EDIT2

The problem was solved

I can't delete annotation component, because without this annotation, DI in my application will not work.
I find decision. Bean is called signatureValidator. And I use name SignatureValidator to specificate bean to mock. That was mistake ) So with follow construction it works fine:

@MockBean(name = "signatureValidator")
private SignatureValidator signatureValidator;

Thanks everyone for replies :)

Body:
You must not call

MockitoAnnotations.initMocks(this);

because the SpringRunner already initializes the mocks. By calling initMocks you assign a new object to signatureValidator. All Mockito actions like when and verify are performed on the new object, but Spring still uses the "old" SignatureValidator that was created by the SpringRunner.


问:
Make rotation stop realisticly in Swift
I have a square = SKSpriteNode() that turns that rotates 360° when you touch it. I want to stop the spinning when you touch it again.
Now I would make square rotate through the SKAction.rotate but how can I stop the spinning realisticly meaning that I want the sprite to spin slower and slower until it stands still.

答:
You may want to consider using a physicsbody  and applying an angular force.

```<code>let square = SKSpriteNode(color:.white,size:CGSize(10,10))
if let physicsBody = SKPhysicsBody(rectangleOf:square.frame.size)
{
   physicsBody.isDynamic = true
   physicsBody.allowsRotation = true
   physicsBody.affectedByGravity = false
   physicsBody.angularDamping  = 0.1 //Adjust this to speed up or slow down the resistance of the spin
   square.physicsBody = physicsBody
}
</code>```

...

When you need to spin:

```<code>square.physicsBody!.angularImpulse(1) //Adjust this to change the amount of force applied to the spin
</code>```

Title: Make rotation stop realisticly in Swift

Body:
You may want to consider using a physicsbody  and applying an angular force.

let square = SKSpriteNode(color:.white,size:CGSize(10,10))
if let physicsBody = SKPhysicsBody(rectangleOf:square.frame.size)
{
   physicsBody.isDynamic = true
   physicsBody.allowsRotation = true
   physicsBody.affectedByGravity = false
   physicsBody.angularDamping  = 0.1 //Adjust this to speed up or slow down the resistance of the spin
   square.physicsBody = physicsBody
}

...

When you need to spin:

square.physicsBody!.angularImpulse(1) //Adjust this to change the amount of force applied to the spin


答:
toArray() will return numpy array. we can convert to list and then collect the dataframe.</p>

```<code>from pyspark.sql.types import *
vector_udf = udf(lambda vector: vector.toArray().tolist(),ArrayType(DoubleType()))

df.show() ## my sample dataframe
+-------------------+
|           features|
+-------------------+
|(4,[1,3],[3.0,4.0])|
|(4,[1,3],[3.0,4.0])|
|(4,[1,3],[3.0,4.0])|
+-------------------+

colvalues = df.select(vector_udf('features').alias('features')).collect()

list(map(lambda x:x.features,colvalues))
[[0.0, 3.0, 0.0, 4.0], [0.0, 3.0, 0.0, 4.0], [0.0, 3.0, 0.0, 4.0]]
</code>```

Title: PySpark - SparseVector Column to Matrix

Body:
I am very new to using PySpark. I have a column of SparseVectors in my PySpark dataframe.

rescaledData.select('features').show(5,False)

+--------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|features                                                                                |
+--------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|(262144,[43953,62425,66522,148962,174441,249180],[3.9219733362813143,3.9219733362813143,1.213923135179104,3.9219733362813143,3.9219733362813143,0.5720692490067093])|
|(262144,[57925,66522,90939,249180],[3.5165082281731497,1.213923135179104,3.9219733362813143,0.5720692490067093])                                                    |
|(262144,[23366,45531,73408,211290],[2.6692103677859462,3.005682604407159,3.5165082281731497,3.228826155721369])                                                     |
|(262144,[30913,81939,99546,137643,162885,249180],[3.228826155721369,3.9219733362813143,3.005682604407159,3.005682604407159,3.228826155721369,1.1441384980134186])   |
|(262144,[108134,152329,249180],[3.9219733362813143,2.6692103677859462,2.8603462450335466])                                                                          |
+--------------------------------------------------------------------------------------------------------------------------------------------------------------------+

I need to convert the above dataframe into a matrix where every row in the matrix corresponds to a SparseVector in that exact row in the dataframe.

for example,

+-----------------+
|features         |
+-----------------+
|(7,[1,2],[45,63])|
|(7,[3,5],[85,69])|
|(7,[1,2],[89,56])|
+-----------------+

Must be converted to

[[0,45,63,0,0,0,0]
[0,0,0,85,0,69,0]
[0,89,56,0,0,0,0]]

I have read the link below, which shows that there is a function toArray() which does exactly what I want.
https://mingchen0919.github.io/learning-apache-spark/pyspark-vectors.html

However, I am having trouble using it.

vector_udf = udf(lambda vector: vector.toArray())
rescaledData.withColumn('features_', vector_udf(rescaledData.features)).first()

I need it to convert every row into an array and then convert the PySpark dataframe into a matrix.

Body:
toArray() will return numpy array. we can convert to list and then collect the dataframe.

from pyspark.sql.types import *
vector_udf = udf(lambda vector: vector.toArray().tolist(),ArrayType(DoubleType()))

df.show() ## my sample dataframe
+-------------------+
|           features|
+-------------------+
|(4,[1,3],[3.0,4.0])|
|(4,[1,3],[3.0,4.0])|
|(4,[1,3],[3.0,4.0])|
+-------------------+

colvalues = df.select(vector_udf('features').alias('features')).collect()

list(map(lambda x:x.features,colvalues))
[[0.0, 3.0, 0.0, 4.0], [0.0, 3.0, 0.0, 4.0], [0.0, 3.0, 0.0, 4.0]]


问:
Rails 5 - Google Page Speed Insights - Leverage Browser Caching
I've got a Rails 5 development site running on a public server. The project is also in development mode. I have been scanning the site with Google Page Speed Insights and one of the largest suggestions has been to leverage browser caching. So, I looked around on google and every answer says to use this code:

```<code>config.public_file_server.headers = {
  'Cache-Control' => 'public, s-maxage=31536000, maxage=15552000',
  'Expires' => "#{1.year.from_now.to_formatted_s(:rfc822)}"
}
</code>```

Because the project is in development mode I put this code in my development.rb file rather than production.rb. I haven't been able to get any different results by doing this. No errors either. I could use some guidance! Thanks in advance.

答:
Testing a rails server in development is like trying to empty the oceans of water. The main changes in the production environment are performance enhancing configurations (caching, class reloading, asset compilation, etc).

I'd suggest copying the default production configurations over to your development config if you want to test performance in development mode. This will probably make development painful for you, however.

Or switch environments to production.

What's your real goal here?

Body:
I've got a Rails 5 development site running on a public server. The project is also in development mode. I have been scanning the site with Google Page Speed Insights and one of the largest suggestions has been to leverage browser caching. So, I looked around on google and every answer says to use this code:

config.public_file_server.headers = {
  'Cache-Control' => 'public, s-maxage=31536000, maxage=15552000',
  'Expires' => "#{1.year.from_now.to_formatted_s(:rfc822)}"
}

Because the project is in development mode I put this code in my development.rb file rather than production.rb. I haven't been able to get any different results by doing this. No errors either. I could use some guidance! Thanks in advance.


问:
Moved TFS change build agent
We moved our TFS on-premise to new servers, and now I have to change the build-agents (on Windows) so that they also link to the new server. Is there a more easy way to do this than to remove it and reconfigure it?</p>

答:
I found the answer via Unconfig remove service registration should be best effort  (after a bit of reading between the lines).

Edit the setting.json file in your Agent directory and restart the Agent service.

Title: Moved TFS change build agent


问:
One liner for iterating through two lists and removing item from one if exists in the other
Have two lists:

```<code>one = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
two = ['aaa', 'qqq', 'rrr', 'bbb', 'zzz']
</code>```

Currently I searched through both and if one exists in the other it is removed like so:

```<code>for i in one:
    for j in two:
        if j in i:
            one.remove(i)
</code>```

This returns

```<code>a = ['ccc', 'ddd', 'eee']
</code>```

Just wondering if there's a more pythonic way of doing it than how I currently am?

答:
Use filter() built in function:

```<code>one = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
two = ['aaa', 'qqq', 'rrr', 'bbb', 'zzz']

list(filter(lambda a: a not in two, one))
</code>```

Body:
Have two lists:

one = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
two = ['aaa', 'qqq', 'rrr', 'bbb', 'zzz']

Currently I searched through both and if one exists in the other it is removed like so:

for i in one:
    for j in two:
        if j in i:
            one.remove(i)

This returns

a = ['ccc', 'ddd', 'eee']

Just wondering if there's a more pythonic way of doing it than how I currently am?

Body:
Use filter() built in function:

one = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
two = ['aaa', 'qqq', 'rrr', 'bbb', 'zzz']

list(filter(lambda a: a not in two, one))


问:
How to transfer basic objects between Ruby and Python?
Currently I'm using JSON as a serialization format to transfer a simple hash containing strings, numbers and an array from Ruby into a Python script:

```<code>IO.popen('./convert.py', 'w') do |w|
    w.write({ :height => height, :width => width, :id => job_id, :data => pix }.to_json)
    w.write "\n"
    w.close_write
end
</code>```

In this case height, width and job_id are all numbers and pix is an array of arrays of integers.

The python script this is running is:

```<code>#!/usr/bin/env python

from PIL import Image
import json
import sys

output = json.load(sys.stdin)

width = output['width']
height = output['height']
name = 'images/' + str(output['id']) + '/image.bmp'
data = [ tuple(datum) for datum in output['data'] ]

img = Image.new("RGB", (width, height))

img.putdata(data)

img.save(name)
</code>```

A bit of quick testing utilising an array with 3.9 million values (probably around 1/4 of the size that will normally be used) revealed the script to take around 105 seconds, and  90 seconds with all lines below output = ... commented out.  Obviously it would be good if the serialisation didn't take 85% of the processing time for such a simple script.

The only method to speed this up that I can think of is to find some form of binary serialisation/marshalling that could be utilised to transfer the data from Ruby to Python.  Unfortunately I have been unable to find any such system, only RMarshal which appears to be able to work the other way.

答:
It certainly appears generating and (especially) parsing the JSON could be improved, as a simple custom format led to a huge difference, without resorting to a non-text format.  I had to change your use of putdata (specifically the format of data passed into it), otherwise the below test isn't significantly different.

```<code>$ time ./gen-json.py 1500 900 json | ./read-json.py

real    0m50.727s
user    0m50.131s
sys     0m0.164s
$ time ./gen.py 1500 900 custom | ./read.py

real    0m3.786s
user    0m6.076s
sys     0m0.064s
</code>```

Forgive the general hackiness in these, as they were written in about 5 minutes just to start determining where the problem might lie.  However, everything seems to work fine in them; at least I can open the BMPs created. :)

gen-json.py

```<code>#!/usr/bin/env python2.6
import sys

width, height, img_id = sys.argv[1:]
width = int(width)
height = int(height)
print """{"width": %s, "height": %s, "id": "%s", "data": [""" % (width, height, img_id)
row = str([0 for _ in xrange(width)])
first = True
for _ in xrange(height):
  if first:
    first = False
  else:
    print ","
  print row,
print "]}"
</code>```

read-json.py

```<code>#!/usr/bin/env python2.6
import json
import sys
from PIL import Image

output = json.load(sys.stdin)

width = output['width']
height = output['height']
name = 'image-%s.bmp' % output['id']
data = []
assert len(output['data']) == height
for x in output['data']:
  assert len(x) == width
  data.extend(x)

img = Image.new("RGB", (width, height))
img.putdata(data)
img.save(name)
</code>```

gen.py

```<code>#!/usr/bin/env python2.6
import sys

width, height, img_id = sys.argv[1:]
width = int(width)
height = int(height)
print img_id, width, height
for _ in xrange(height):
  for _ in xrange(width):
    print 0,
  print
</code>```

read.py

```<code>#!/usr/bin/env python2.6
import sys
from PIL import Image

img_id, width, height = raw_input().split()
width = int(width)
height = int(height)
name = "image-%s.bmp" % img_id
data = [int(x) for row in sys.stdin for x in row.split()]
assert len(data) == width * height

img = Image.new("RGB", (width, height))
img.putdata(data)
img.save(name)
</code>```

Body:
Currently I'm using JSON as a serialization format to transfer a simple hash containing strings, numbers and an array from Ruby into a Python script:

IO.popen('./convert.py', 'w') do |w|
    w.write({ :height => height, :width => width, :id => job_id, :data => pix }.to_json)
    w.write "\n"
    w.close_write
end

In this case height, width and job_id are all numbers and pix is an array of arrays of integers.

The python script this is running is:

#!/usr/bin/env python

from PIL import Image
import json
import sys

output = json.load(sys.stdin)

width = output['width']
height = output['height']
name = 'images/' + str(output['id']) + '/image.bmp'
data = [ tuple(datum) for datum in output['data'] ]

img = Image.new("RGB", (width, height))

img.putdata(data)

img.save(name)

A bit of quick testing utilising an array with 3.9 million values (probably around 1/4 of the size that will normally be used) revealed the script to take around 105 seconds, and  90 seconds with all lines below output = ... commented out.  Obviously it would be good if the serialisation didn't take 85% of the processing time for such a simple script.

The only method to speed this up that I can think of is to find some form of binary serialisation/marshalling that could be utilised to transfer the data from Ruby to Python.  Unfortunately I have been unable to find any such system, only RMarshal which appears to be able to work the other way.

Body:
It certainly appears generating and (especially) parsing the JSON could be improved, as a simple custom format led to a huge difference, without resorting to a non-text format.  I had to change your use of putdata (specifically the format of data passed into it), otherwise the below test isn't significantly different.

$ time ./gen-json.py 1500 900 json | ./read-json.py

real    0m50.727s
user    0m50.131s
sys     0m0.164s
$ time ./gen.py 1500 900 custom | ./read.py

real    0m3.786s
user    0m6.076s
sys     0m0.064s

Forgive the general hackiness in these, as they were written in about 5 minutes just to start determining where the problem might lie.  However, everything seems to work fine in them; at least I can open the BMPs created. :)

gen-json.py

#!/usr/bin/env python2.6
import sys

width, height, img_id = sys.argv[1:]
width = int(width)
height = int(height)
print """{"width": %s, "height": %s, "id": "%s", "data": [""" % (width, height, img_id)
row = str([0 for _ in xrange(width)])
first = True
for _ in xrange(height):
  if first:
    first = False
  else:
    print ","
  print row,
print "]}"

read-json.py

#!/usr/bin/env python2.6
import json
import sys
from PIL import Image

output = json.load(sys.stdin)

width = output['width']
height = output['height']
name = 'image-%s.bmp' % output['id']
data = []
assert len(output['data']) == height
for x in output['data']:
  assert len(x) == width
  data.extend(x)

img = Image.new("RGB", (width, height))
img.putdata(data)
img.save(name)

gen.py

#!/usr/bin/env python2.6
import sys

width, height, img_id = sys.argv[1:]
width = int(width)
height = int(height)
print img_id, width, height
for _ in xrange(height):
  for _ in xrange(width):
    print 0,
  print

read.py

#!/usr/bin/env python2.6
import sys
from PIL import Image

img_id, width, height = raw_input().split()
width = int(width)
height = int(height)
name = "image-%s.bmp" % img_id
data = [int(x) for row in sys.stdin for x in row.split()]
assert len(data) == width * height

img = Image.new("RGB", (width, height))
img.putdata(data)
img.save(name)


问:
How to fetch/pull changes from shallow branch (--depth 1)
I'm working on a MEAN framework project.
MEAN github repository link

I used following command to clone the MEAN repository as shown in their documentation.

```<code>git clone --depth 1 https://github.com/linnovate/mean.git
</code>```

I did it few weeks later and now I need to update my local repository from this original repository. Their official repository is 30 commits ahead. So I used following command.

```<code>git fetch
</code>```

Normally it suppose to fetch all the changes and update my repository. But this time, it did nothing.

Then I used following command.

```<code> git fetch --depth 1
</code>```

And then it showed me this.

```<code>remote: Total 0 (delta 0), reused 0 (delta 0), pack-reused 0
</code>```

Can anyone please tell me how to fetch all the changes from official repository. Here is my forked repository.
https://github.com/chanakaDe/mean

I used following 2 commands also. But no good results.

```<code>git pull
git pull --depth 1
</code>```

Please help me on this. :-)

答:
As stated in this very good answer to the same question:

git fetch

git reset --hard origin/master

(git clean -dfx)

Body:
I'm working on a MEAN framework project.
MEAN github repository link

I used following command to clone the MEAN repository as shown in their documentation.

git clone --depth 1 https://github.com/linnovate/mean.git

I did it few weeks later and now I need to update my local repository from this original repository. Their official repository is 30 commits ahead. So I used following command.

git fetch

Normally it suppose to fetch all the changes and update my repository. But this time, it did nothing.

Then I used following command.

 git fetch --depth 1

And then it showed me this.

remote: Total 0 (delta 0), reused 0 (delta 0), pack-reused 0

Can anyone please tell me how to fetch all the changes from official repository. Here is my forked repository.
https://github.com/chanakaDe/mean

I used following 2 commands also. But no good results.

git pull
git pull --depth 1

Please help me on this. :-)


问:
Could not find destination file during file copy
We've seen this issue described elsewhere when it relates to the source file, but not the destination file.

We're trying to copy a 70MB file from a local path on the source server to a share on the destination server. The entire process is iterating over many files on the main thread and other files have successfully copied before we see the issue.  However, we occasionally see this error:

```<code>Could not find file 'DestinationFileFullPath'.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.File.InternalCopy(String sourceFileName, String destFileName, Boolean overwrite, Boolean checkHost)
</code>```

I need to emphasize this point: the error refers to the destination file name, not the source. And we're certain that we haven't mixed up the variables. This is the code:

```<code>ConsoleLog(String.Format("Copying file from {0} to {1}", source, dest));
File.Copy(source, dest);
</code>```

Does anyone have any idea what's causing this?

答:
A possibility for anyone who might end up on this thread:

You will get this error in both File.Move and File.Copy if the 'source' and 'destination' arguments are the same.

Body:
We've seen this issue described elsewhere when it relates to the source file, but not the destination file.

We're trying to copy a 70MB file from a local path on the source server to a share on the destination server. The entire process is iterating over many files on the main thread and other files have successfully copied before we see the issue.  However, we occasionally see this error:

Could not find file 'DestinationFileFullPath'.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.File.InternalCopy(String sourceFileName, String destFileName, Boolean overwrite, Boolean checkHost)

I need to emphasize this point: the error refers to the destination file name, not the source. And we're certain that we haven't mixed up the variables. This is the code:

ConsoleLog(String.Format("Copying file from {0} to {1}", source, dest));
File.Copy(source, dest);

Does anyone have any idea what's causing this?


问:
Show gene names on heatmap
here is my script:

```<code>heatmap.2(
as.matrix(data[,2:7]),
trace="none",
dendrogram="row",
cexRow=0.5, cexCol=0.95,
)
</code>```

The gene names appear as numbers as I excluded the first column that contains gene names.
How can I replace the numbering by gene names?

Many thanks

答:
if you have a matrix object (named m) and a vector of genes (named g), you can add row names like this:

```<code>rownames(m) <- g
</code>```

you can similarly add the names of columns:

```<code>colnames(m) <- vector
</code>```

then you can re-plot the heatmap of matrix m

Hope this helps. Cheers!

Title: Show gene names on heatmap

Body:
here is my script:

heatmap.2(
as.matrix(data[,2:7]),
trace="none",
dendrogram="row",
cexRow=0.5, cexCol=0.95,
)

The gene names appear as numbers as I excluded the first column that contains gene names.
How can I replace the numbering by gene names?

Many thanks

Body:
if you have a matrix object (named m) and a vector of genes (named g), you can add row names like this:

rownames(m) <- g

you can similarly add the names of columns:

colnames(m) <- vector

then you can re-plot the heatmap of matrix m

Hope this helps. Cheers!


问:
How to convert object to array to get the data?
My array coming like this

```<code>Array ( [0] => stdClass Object ( [ID] => 578 [post_author] => 1 [post_date] => 2011-01-18 07:23:17 [post_date_gmt] => 2011-01-18 07:23:17 [post_content] => Home WordPress is web software you can use to create a beautiful website or blog. We like to say that WordPress is both free and priceless at the same time. The core software is built by hundreds of community volunteers, and when you’re ready for more there are thousands of plugins and themes available to transform your site into almost anything you can imagine. Over 25 million people have chosen WordPress to power the place on the web they call “home” — we’d love you to join the family [post_title] => second post [post_excerpt] => [post_status] => publish [comment_status] => open
</code>```

when i write like this

```<code>$myposts = get_posts( $args );
$arrDt = (array) $myposts;
print_r($arrDt);
</code>```

but my problem is how can i get the values inside that object array.

please help.
Thnx
print_r($arrDt);

答:
It's very simple:

You have an Array Array ( [0] => stdClass Object ( [ID]

This array have one KEY, that can be identified by the "[0]" (but more keys may exist))
Accessing the key:

```<code>foreach ( $arrDt as $value ): //Look, whe are inside the first key. (currently is '0').
   echo $value->ID;
   echo $value->post_author;
endforeach;
</code>```

Or, if you want to convert object to array ( like $value['ID'], for example ), you just needs this:

```<code>    function objectToArray($obj)
    {
         if (is_object($obj)):
             $object = get_object_vars($obj);
         endif;

         return array_map('objectToArray', $object); // return the object, converted in array.
    }

$objArray = objectToArray($arrDt);
print_r($objArray);
</code>```

Body:
My array coming like this

Array ( [0] => stdClass Object ( [ID] => 578 [post_author] => 1 [post_date] => 2011-01-18 07:23:17 [post_date_gmt] => 2011-01-18 07:23:17 [post_content] => Home WordPress is web software you can use to create a beautiful website or blog. We like to say that WordPress is both free and priceless at the same time. The core software is built by hundreds of community volunteers, and when you’re ready for more there are thousands of plugins and themes available to transform your site into almost anything you can imagine. Over 25 million people have chosen WordPress to power the place on the web they call “home” — we’d love you to join the family [post_title] => second post [post_excerpt] => [post_status] => publish [comment_status] => open

when i write like this

$myposts = get_posts( $args );
$arrDt = (array) $myposts;
print_r($arrDt);

but my problem is how can i get the values inside that object array.

please help.
Thnx
print_r($arrDt);

Body:
It's very simple:

You have an Array Array ( [0] => stdClass Object ( [ID]

This array have one KEY, that can be identified by the "[0]" (but more keys may exist))
Accessing the key:

foreach ( $arrDt as $value ): //Look, whe are inside the first key. (currently is '0').
   echo $value->ID;
   echo $value->post_author;
endforeach;

Or, if you want to convert object to array ( like $value['ID'], for example ), you just needs this:

    function objectToArray($obj)
    {
         if (is_object($obj)):
             $object = get_object_vars($obj);
         endif;

         return array_map('objectToArray', $object); // return the object, converted in array.
    }

$objArray = objectToArray($arrDt);
print_r($objArray);


问:
How do I mutate existing data with GraphQL, Graphene and Relay?
I feel like it should be documented somewhere but I cant find it. I can add data to my db with a mutation but I cant change it.

Graphene works with Django and my db is SQLite

Its quite specific, I hope someone knows the answer. Among other things I tried:

```<code>mutation AppMutation(
  $input: AddSchoolNodeInput!
  ) {
    addSchool(input: $input) {
      school {
        id
        name
        description
     }
    }
  }
</code>```

where AddSchoolNodeInput! is ("U2Nob29sTm9kZToxMQ==" is an existing id):

```<code>{
  "name": "edit kaas",
  "description": "edit fails",
  "clientMutationId":"U2Nob29sTm9kZToxMQ=="
 }
</code>```

it create a new item and returns this:

```<code>{
  "data": {
    "addSchool": {
      "school": {
        "id": "U2Nob29sTm9kZToxNA==",
        "name": "edit kaas",
        "description": "edit fails"
      }
    }
  }
}
</code>```

答:
I was able to edit an existing school by providing the ID to the above mentioned mutation and doing this in the schema:

```<code>class AddSchool(relay.ClientIDMutation):
    class Input:
        name = String()
        description = String()
        id = String()

    school = Field(SchoolNode)

    @classmethod
    def mutate_and_get_payload(cls, input, context, info):
        name = input.get("name")
        description = input.get("description")
        id = input.get("id")

        if id:
            id = from_global_id(id)[1]
            school = School.objects.get(id=id)
            if name:
                school.name = name
            if description:
                school.description = description

        else:
            school = School(
                name=name,
                description=description
            )

        school.save()

        return AddSchool(school=school)
</code>```

It grabs the ID, puts it trough an if statement, transfers it from the graphene ID to the django ID with from_global_id and then grabs it from the db. If it can find it an error will occur, so no new school will be created, only if no id is provided.

Not sure if its best practice but it works.

Body:
I feel like it should be documented somewhere but I cant find it. I can add data to my db with a mutation but I cant change it.

Graphene works with Django and my db is SQLite

Its quite specific, I hope someone knows the answer. Among other things I tried:

mutation AppMutation(
  $input: AddSchoolNodeInput!
  ) {
    addSchool(input: $input) {
      school {
        id
        name
        description
     }
    }
  }

where AddSchoolNodeInput! is ("U2Nob29sTm9kZToxMQ==" is an existing id):

{
  "name": "edit kaas",
  "description": "edit fails",
  "clientMutationId":"U2Nob29sTm9kZToxMQ=="
 }

it create a new item and returns this:

{
  "data": {
    "addSchool": {
      "school": {
        "id": "U2Nob29sTm9kZToxNA==",
        "name": "edit kaas",
        "description": "edit fails"
      }
    }
  }
}

Body:
I was able to edit an existing school by providing the ID to the above mentioned mutation and doing this in the schema:

class AddSchool(relay.ClientIDMutation):
    class Input:
        name = String()
        description = String()
        id = String()

    school = Field(SchoolNode)

    @classmethod
    def mutate_and_get_payload(cls, input, context, info):
        name = input.get("name")
        description = input.get("description")
        id = input.get("id")

        if id:
            id = from_global_id(id)[1]
            school = School.objects.get(id=id)
            if name:
                school.name = name
            if description:
                school.description = description

        else:
            school = School(
                name=name,
                description=description
            )

        school.save()

        return AddSchool(school=school)

It grabs the ID, puts it trough an if statement, transfers it from the graphene ID to the django ID with from_global_id and then grabs it from the db. If it can find it an error will occur, so no new school will be created, only if no id is provided.

Not sure if its best practice but it works.


问:
removing tags for a string with recursion
I have the following function which should remove tags from an input string.

example in:

```<code>'<strong>hello <em>my name <strong>is</strong> </em></strong>'
</code>```

result:

```<code>'hello my name is'
</code>```

Currently I have this code, but not sure how to make it work with recursion.

```<code>const clean= (str) => {
    const tags = ['<strong>', '</strong>', '<em>', '</em>', '<del>', '</del>']
    let strSanited = ''
    tags.forEach(tag => {
        if (str.includes(tag)) {
            strSanited = str.replace(tag, '')
        }else{
            // recursion here??
        }
    })
}

clean('<strong>hello <em>my name <strong>is</strong> </em></strong>')
</code>```

答:
Why not simply use the createElement and innerText

```<code>var div = document.createElement( "div" );
div.innerHTML = '<strong>hello <em>my name is </em></strong>';
console.log(div.innerText); //hello my name is
</code>```

Demo

var div = document.createElement("div");
div.innerHTML = 'hello my name is ';
console.log(div.innerText); //hello my name is```

Body:
I have the following function which should remove tags from an input string.

example in:

'hello my name is '

result:

'hello my name is'

Currently I have this code, but not sure how to make it work with recursion.

const clean= (str) => {
    const tags = ['', '', '', '', '', '']
    let strSanited = ''
    tags.forEach(tag => {
        if (str.includes(tag)) {
            strSanited = str.replace(tag, '')
        }else{
            // recursion here??
        }
    })
}

clean('hello my name is ')

Body:
Why not simply use the createElement and innerText

var div = document.createElement( "div" );
div.innerHTML = '<strong>hello <em>my name is </em></strong>';
console.log(div.innerText); //hello my name is

Demo

var div = document.createElement("div");
div.innerHTML = '<strong>hello <em>my name is </em></strong>';
console.log(div.innerText); //hello my name is


问:
How can I make Docker trigger higher CPU frequencies
OK, so my title may not actually be linked to a possible solution, however this is my problem.
I am running a Python 3 Jupyter notebook inside a docker container in from my windows 10 kaby-lake (2 physical cores, 4 virtual cores) laptop.
I noticed while doing heavy computing from there, my CPU usage seen in the task monitor is very low (~15%).
When going on the details for each process, the VBoxHeadless.exe actually uses 24% of the processor, which matches docker stats command which yields 97-100% CPU usage, and therefore makes sense from a single-core operation point of view.

My actual issue is that even though on thread is filled in terms of CPU time, windows (I guess) does not decide that it may actually be useful to speed up the CPU, and therefore it runs at 1.7GHz (with other apps in high performance mode, I usually hit the max 3.5GHz that the computer is capable of).

Therefore, how can I induce the higher clock speeds (nominal 2.7GHz or max 3.5GHZ) (considering that they would probably double my single threaded speed) from docker itself or inside windows 10?

答:
You need to configure the docker machine running docker. If you haven't created a custom one, the default docker machine named 'default' will only have access to one cpu.

You can check all the configuration for this docker-machine by running:

```<code>docker-machine inspect default
</code>```

You need to purge this default machine and recreate it:

```<code>docker-machine rm default
docker-machine create -d virtualbox --virtualbox-disk-size "400000" --virtualbox-cpu-count "2" --virtualbox-memory "2048" default
</code>```

You can check all the avaible configuration options for the machine by running:

```<code>docker-machine create --help
</code>```

Body:
You need to configure the docker machine running docker. If you haven't created a custom one, the default docker machine named 'default' will only have access to one cpu.

You can check all the configuration for this docker-machine by running:

docker-machine inspect default

You need to purge this default machine and recreate it:

docker-machine rm default
docker-machine create -d virtualbox --virtualbox-disk-size "400000" --virtualbox-cpu-count "2" --virtualbox-memory "2048" default

You can check all the avaible configuration options for the machine by running:

docker-machine create --help