问:
How do I get a fill_between shape in Funcanimation?
I would like to make a moving plot where the area under the curve gets colored while the curve is getting plotted.

I have googled a bit and found that I should somehow create a patch. However, I do not understand any of the examples they give, so let me ask it here with my specific example:

```<code>import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
import pylab as p

data = np.loadtext('datafile.dat', delimiter=',')
A = data[:,1]
B = data[:,2]

fig = plt.figure(figsize=(25,5), dpi=80)
ax = plt.axes(xlim=(0, 3.428), ylim=(-1,1))
line, = ax.plot([], [], lw=5)

def init():
    line.set_data([], [])
    return line,

def animate(i):
    x = A[0:(i-1)*400]
    y = B[0:(i-1)*400]
    line.set_data(x,y)
    # Here is the problem. I would now like to add the following line
    # p.fill_between(x, 0, y, facecolor = 'C0', alpha = 0.2)
    return line,

anim = animation.FuncAnimation(fig,animate, init_func=init, frames = 857, interval=20, blit=True)
</code>```

I hope someone can give me a solution for my problem or at least point me in the correct direction.

So my question would be: how can I add the commented part without any errors?

答:
Assuming you want blit = True, you will need to return the patch produced by fill_between as well.

```<code>p = plt.fill_between(x, y, 0)
return line, p,
</code>```

Complete working example:

```<code>import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

X = np.linspace(0,3.428, num=250)
Y = np.sin(X*3)

fig = plt.figure(figsize=(13,5), dpi=80)
ax = plt.axes(xlim=(0, 3.428), ylim=(-1,1))
line, = ax.plot([], [], lw=5)

def init():
    line.set_data([], [])
    return line,

def animate(i):
    x = X[0:(i-1)]
    y = Y[0:(i-1)]
    line.set_data(x,y)
    p = plt.fill_between(x, y, 0, facecolor = 'C0', alpha = 0.2)
    return line, p,

anim = animation.FuncAnimation(fig,animate, init_func=init,
                               frames = 250, interval=20, blit=True)

plt.show()
</code>```

Body:
I would like to make a moving plot where the area under the curve gets colored while the curve is getting plotted.

I have googled a bit and found that I should somehow create a patch. However, I do not understand any of the examples they give, so let me ask it here with my specific example:

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
import pylab as p

data = np.loadtext('datafile.dat', delimiter=',')
A = data[:,1]
B = data[:,2]

fig = plt.figure(figsize=(25,5), dpi=80)
ax = plt.axes(xlim=(0, 3.428), ylim=(-1,1))
line, = ax.plot([], [], lw=5)

def init():
    line.set_data([], [])
    return line,

def animate(i):
    x = A[0:(i-1)*400]
    y = B[0:(i-1)*400]
    line.set_data(x,y)
    # Here is the problem. I would now like to add the following line
    # p.fill_between(x, 0, y, facecolor = 'C0', alpha = 0.2)
    return line,

anim = animation.FuncAnimation(fig,animate, init_func=init, frames = 857, interval=20, blit=True)

I hope someone can give me a solution for my problem or at least point me in the correct direction.

So my question would be: how can I add the commented part without any errors?

Body:
Assuming you want blit = True, you will need to return the patch produced by fill_between as well.

p = plt.fill_between(x, y, 0)
return line, p,

Complete working example:

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

X = np.linspace(0,3.428, num=250)
Y = np.sin(X*3)

fig = plt.figure(figsize=(13,5), dpi=80)
ax = plt.axes(xlim=(0, 3.428), ylim=(-1,1))
line, = ax.plot([], [], lw=5)

def init():
    line.set_data([], [])
    return line,

def animate(i):
    x = X[0:(i-1)]
    y = Y[0:(i-1)]
    line.set_data(x,y)
    p = plt.fill_between(x, y, 0, facecolor = 'C0', alpha = 0.2)
    return line, p,

anim = animation.FuncAnimation(fig,animate, init_func=init,
                               frames = 250, interval=20, blit=True)

plt.show()


来源: stackexchange

问:
Use SBT to manage XML resources (required at runtime) from an external git repository
I have a Scala project in SBT, and at runtime it needs to access a collection of XML files which I would like fetch from git and put on the classpath at build time. These XMLs come from an external git repository that I have no control over, so I can't merge the two repos.

I see that SBT allows you to add unmanagedResourceDirectories and managedResoureDirectories (not sure what the difference is), which allows you to instruct SBT to add directories to the classpath, but I'm not sure how to get the directory from a git repo, rather than an actual directory on disk.

答:
You can use the JGit library to clone the repo locally and copy the files out of the repo using the archive command. As an example, see how the sbt-hackling plugin implements this.

If you don't need platform-independence, you can get by with invoking the command line git commands and combine clone/fetch to update the dependency and archive to extract files.

The part of the code that copies some paths out of a local repository:

```<code>// needed for installSource
// maybe implement some archiver to go directly to files?
org.eclipse.jgit.archive.ArchiveFormats.registerAll()

def installSource(cachedRepo: Git, paths: Seq[String], revision: ObjectId, target: File): Set[File] =
    IO.withTemporaryFile(target.getName, ".zip") { tmp =>
    val out = new BufferedOutputStream(new FileOutputStream(tmp))

    cachedRepo
        .archive()
        .setFormat("zip")
        .setTree(revision)
        .setPaths(paths :_*)
        .setOutputStream(out)
        .call()

    IO.unzip(tmp, target)
    }
</code>```

Part of code that clones a repo locally:

```<code>def downloadGitRepo(local: File)(repo: URI): File = {

    val clone = Git
        .cloneRepository()
        .setURI(repo.toString)
        .setDirectory(local)
        .setBare(true)
        .call()

    assert(local.exists())

    local
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can use the JGit library to clone the repo locally and copy the files out of the repo using the archive command. As an example, see how the sbt-hackling plugin implements this.

If you don't need platform-independence, you can get by with invoking the command line git commands and combine clone/fetch to update the dependency and archive to extract files.

The part of the code that copies some paths out of a local repository:

// needed for installSource
// maybe implement some archiver to go directly to files?
org.eclipse.jgit.archive.ArchiveFormats.registerAll()

def installSource(cachedRepo: Git, paths: Seq[String], revision: ObjectId, target: File): Set[File] =
    IO.withTemporaryFile(target.getName, ".zip") { tmp =>
    val out = new BufferedOutputStream(new FileOutputStream(tmp))

    cachedRepo
        .archive()
        .setFormat("zip")
        .setTree(revision)
        .setPaths(paths :_*)
        .setOutputStream(out)
        .call()

    IO.unzip(tmp, target)
    }

Part of code that clones a repo locally:

def downloadGitRepo(local: File)(repo: URI): File = {

    val clone = Git
        .cloneRepository()
        .setURI(repo.toString)
        .setDirectory(local)
        .setBare(true)
        .call()

    assert(local.exists())

    local
}


问:
Remove a page from Navigation Stack
I have this application schema :

```<code>[List Page] -> [Detail Page] -> [ShareOnFacebook Page]
                     ^__________________|
</code>```

The user select an Item in the [List Page]

The user may or may not click a Share button if he or she does, the application navigates to a [ShareOneFacebook page] which displays a Facebook Login Form, posts a message and navigates back

The user navigates back.

If the user shared on facebook, it will "repost" the message, because the application store the session so it will navigate back to ShareOnFacebook, and then back to my Detail page.

If the user didn't share, he goes back to the List Page.

How can I "ommit" the ShareOnFacebook page in my navigation stack ?

答:
I have a similar situation in my app, i solve it with a very simple solution.

If you want to "skip" a page in your backstack, place some logic in the NavigatedTo() function of that page.

For example: you can have a bool that you set to true when you post to facebook, and then place the following code in the NavigatedTo() function of the ShareOnFacebook page.

Here is pseudo code:

if (alreadyPosted)
     Navigation.GoBack();

The GoBack() function will skip this page and return to the previous one, the user will never see the page.

ContentLicense: CC BY-SA 2.5

Title: Remove a page from Navigation Stack

Body:
I have this application schema :

[List Page] -> [Detail Page] -> [ShareOnFacebook Page]
                     ^__________________|

The user select an Item in the [List Page]

The user may or may not click a Share button if he or she does, the application navigates to a [ShareOneFacebook page] which displays a Facebook Login Form, posts a message and navigates back

The user navigates back.

If the user shared on facebook, it will "repost" the message, because the application store the session so it will navigate back to ShareOnFacebook, and then back to my Detail page.

If the user didn't share, he goes back to the List Page.

How can I "ommit" the ShareOnFacebook page in my navigation stack ?


问:
Why does the serial value get printed twice along with a value that is not sent?
Using the code below, I am trying to print the value that is received through the Arduino serial. But the value gets printed twice. And one among the printed values is always 0.

byte b;
int i;

void setup() {
  Serial.begin(115200);
  Serial.setTimeout(10);
}

void loop() {
  while(Serial.available() == 0) {}
  i = Serial.parseInt();
  Serial.println(i);
}

EXAMPLE: value sent is 15
Serial monitor output: 15
                       0

EXAMPLE: value sent is 99
Serial monitor output: 99
                       0
```

答:
I am assuming you are sending from the serial monitor with newline characters.

This is what is happening in your code.

You are sending 15\n.

Serial.parseInt() reads 1 and 5 from the serial buffer and stops at \n. Then it returns 15.

Because \n is still in the buffer, Serial.parseInt() gets called again.

Serial.parseInt() discards any non numerical character from the serial buffer, until it finds a numerical character.

It removed \n and waits for a numerical character.

Serial.parseInt() times out and returns 0.

If you want to prevent your second Serial.parseInt() call, you should send the string without newline characters or empty the serial buffer like this:

void loop() {
  while(Serial.available() == 0) {}
  i = Serial.parseInt();
  Serial.println(i);
  while(Serial.available() > 0) Serial.read(); // empty the serial buffer by reading everything from it
}
```


问:
Generating a unique ID in Objective C
How do we get unique IDs in Objective C. I want to create a unique ID for my session & then generate a ID each time a server call happens. Each time this ID should be unique.

I tried using CFUUID class which gives us a huge unique ID (4FE9D00C-531E-45E8-B10E-11968ACC36E9). I want a unique ID of smaller size.

Any clue?

答:
you may try one of the following

1-

```<code>CFUUIDRef udidCFUUIDRef = CFUUIDCreate(NULL);
    NSString *UUIDString_token_name = (NSString *) CFBridgingRelease(CFUUIDCreateString(NULL, udidCFUUIDRef));
</code>```

2-

```<code>NSString *UUIDString = [[NSUUID UUID] UUIDString];
</code>```

Title: Generating a unique ID in Objective C

Body:
you may try one of the following

1-

CFUUIDRef udidCFUUIDRef = CFUUIDCreate(NULL);
    NSString *UUIDString_token_name = (NSString *) CFBridgingRelease(CFUUIDCreateString(NULL, udidCFUUIDRef));

2-

NSString *UUIDString = [[NSUUID UUID] UUIDString];


问:
file_get_contents - getting real complete HTTP answer (not just headers)
I'm trying to get full HTTP answer over a call to file_get_contents function. I'm doing an HTTP POST call, putting credentials to login to my website, process some work, then return a HTTP answer to the caller.

When credentials are not good, i send a HTTP 403 return code, with a message as follow (Raw HTTP response as shown in SoapUI) :

```<code>HTTP/1.1 403 Forbidden
Server: Apache-Coyote/1.1
X-UA-Compatible: IE=edge
Pragma: no-cache
Cache-Control: no-cache
Expires: Mon, 05 Jun 2017 09:02:13 GMT
Content-Type: text/plain;charset=utf-8
Content-Length: 515
Date: Mon, 05 Jun 2017 09:02:13 GMT

L'authentification user/password n'est pas autorisée pour le login 'sebastien' depuis l'adresse '127.0.0.1'.
</code>```

How can i get the message at bottom after calling file_get_contents in php ? Message is not in the headers, so $http_response_header won't work. Is there a way to do so ?

答:
You could create an HTTP stream context to use with file_get_contents() then call stream_get_meta_data() but personally I would just use Curl with CURLOPT_HEADER=true

Note that since the service is returning a 403 rather than a 401, then you're going to need cookies (if it is possible at all) to authenticate. For that you will need Curl.

Body:
I'm trying to get full HTTP answer over a call to file_get_contents function. I'm doing an HTTP POST call, putting credentials to login to my website, process some work, then return a HTTP answer to the caller.

When credentials are not good, i send a HTTP 403 return code, with a message as follow (Raw HTTP response as shown in SoapUI) :

HTTP/1.1 403 Forbidden
Server: Apache-Coyote/1.1
X-UA-Compatible: IE=edge
Pragma: no-cache
Cache-Control: no-cache
Expires: Mon, 05 Jun 2017 09:02:13 GMT
Content-Type: text/plain;charset=utf-8
Content-Length: 515
Date: Mon, 05 Jun 2017 09:02:13 GMT

L'authentification user/password n'est pas autorisée pour le login 'sebastien' depuis l'adresse '127.0.0.1'.

How can i get the message at bottom after calling file_get_contents in php ? Message is not in the headers, so $http_response_header won't work. Is there a way to do so ?


问:
The Program is not recording the first array, set as a null -- Java
I have a code here that creates an array and puts in people's names into it. However, the first array does not get recorded.

```<code>Scanner newscan = new Scanner(System.in);

    System.out.println("How many people in the group?");
    int groupnum = newscan.nextInt();

    String[] people = new String[groupnum];

    System.out.println("Put in the names of the people in the group");
    String name;

    int i = 0;
    do{
        System.out.println("Input Name");
        name = newscan.nextLine();
        people[i] = name;
        i++;
    }while(i<groupnum);
</code>```

The console shows results like this:

```<code>How many people in the group?
5
Put in the names of the people in the group
Input Name
Input Name
John
Input Name
Bob
Input Name
Denis
Input Name
Andrew
</code>```

I have tried using the debugger on IntelliJ, and it shows that whatever value I put in the first array, gets ignored and is set as a "" null value.

I have no idea to approach this problem.
It would be very helpful if you can tell me what part of my code is causing this problem and how to fix it.

答: After reading nextInt() method, new line is going as input. To avoid that use scanner class skip method.</p>

Body:
I have a code here that creates an array and puts in people's names into it. However, the first array does not get recorded.

Scanner newscan = new Scanner(System.in);

    System.out.println("How many people in the group?");
    int groupnum = newscan.nextInt();

    String[] people = new String[groupnum];

    System.out.println("Put in the names of the people in the group");
    String name;

    int i = 0;
    do{
        System.out.println("Input Name");
        name = newscan.nextLine();
        people[i] = name;
        i++;
    }while(i<groupnum);

The console shows results like this:

How many people in the group?
5
Put in the names of the people in the group
Input Name
Input Name
John
Input Name
Bob
Input Name
Denis
Input Name
Andrew

I have tried using the debugger on IntelliJ, and it shows that whatever value I put in the first array, gets ignored and is set as a "" null value.

I have no idea to approach this problem.
It would be very helpful if you can tell me what part of my code is causing this problem and how to fix it.


问:
Django: How to get all users with profiles as JSON (extended User model)
I have extended the default User model in Django. Now my models look like following:

```<code>class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
birth_date = models.DateField(auto_now=False, auto_now_add=False, default=datetime.now)
phone_number = models.CharField(max_length=13, blank=True, default="")
address = models.CharField(max_length=100, blank=True, default="")
organization = models.ForeignKey(Organization, blank=True, null=True)
</code>```

Everything works fine, I am able to add new users through admin panel and so on.
However, I have got a problem. I need to return a customize JSON response to certain request in form of:

```<code>[
{"firs_name": first_name, "phone_number": phone_number, ...},
{"firs_name": first_name, "phone_number": phone_number, ...},
...
]
</code>```

As you can see, the phone_number attribute belongs to the Profile model, and I cannot get ALL users with their Profiles included (I am able to get only id of user).
Here is the response I get for now:

```<code>[{"username": "user", "profile": 2, "first_name": "User", "last_name": "User"}, {"username": "user1", "profile": 3, "first_name": "User1", "last_name": "User1"}, {"username": "user2", "profile": 4, "first_name": "User2", "last_name": "User2"}]
</code>```

Question: Is there any way to get all user objects with profile information included in it through User.Objects.all()?

Thanks!

P.S.:
This is how I make custom JSON response:

```<code>def get_users_as_json(request):
all_users = User.objects.all().values("username", "first_name", "last_name", 'profile')
user_list = list(all_users)
return JsonResponse(user_list, safe=False)
</code>```

答:
You could just enter all the variables you want manually</p>

```<code>User.objects.all()
    .select_related('profile')
    .values_list('username', ..., 'profile__phone_number', 'profile__address'...)
</code>```

Body:
I have extended the default User model in Django. Now my models look like following:

class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
birth_date = models.DateField(auto_now=False, auto_now_add=False, default=datetime.now)
phone_number = models.CharField(max_length=13, blank=True, default="")
address = models.CharField(max_length=100, blank=True, default="")
organization = models.ForeignKey(Organization, blank=True, null=True)

Everything works fine, I am able to add new users through admin panel and so on.
However, I have got a problem. I need to return a customize JSON response to certain request in form of:

[
{"firs_name": first_name, "phone_number": phone_number, ...},
{"firs_name": first_name, "phone_number": phone_number, ...},
...
]

As you can see, the phone_number attribute belongs to the Profile model, and I cannot get ALL users with their Profiles included (I am able to get only id of user).
Here is the response I get for now:

[{"username": "user", "profile": 2, "first_name": "User", "last_name": "User"}, {"username": "user1", "profile": 3, "first_name": "User1", "last_name": "User1"}, {"username": "user2", "profile": 4, "first_name": "User2", "last_name": "User2"}]

Question: Is there any way to get all user objects with profile information included in it through User.Objects.all()?

Thanks!

P.S.:
This is how I make custom JSON response:

def get_users_as_json(request):
all_users = User.objects.all().values("username", "first_name", "last_name", 'profile')
user_list = list(all_users)
return JsonResponse(user_list, safe=False)

Body:
You could just enter all the variables you want manually

User.objects.all()
    .select_related('profile')
    .values_list('username', ..., 'profile__phone_number', 'profile__address'...)


问:
SQL using TRANSFORM to reformat my table in MS-Access
I need help reformatting my table using TRANSFORM. I've tried a few things but for some reason it just won't work. Here's an example of what I have to do. Say I have this table:

```<code>     table1:

| in/out | year   |
|   in   | 2011-12|
|   in   | 2011-12|
|   in   | 2012-13|
|   out  | 2011-12|
|   out  |2012-13 |
|   out  |2012-13 |
</code>```

I want to reformat this table to look like this:

```<code>|in/out| 2011-12 | 2012-13
|  in  |   2     |   1
|  out |   1     |   2
</code>```

The first column is the in/out and the rest are just the years where the numbers under them is just a count of for example how many ins or outs happened that year. Any help would be greatly appreciated. Thanks in advance.

答:
The query would be

```<code>TRANSFORM   Sum(amount) AS SumOfamount
SELECT      [in/out]
FROM        Table1
GROUP BY    [in/out]
PIVOT       [year]
</code>```

Graphically it looks like this:

You might want to change the field name from year though as that's a reserved word and may confuse the database.

Body:
I need help reformatting my table using TRANSFORM. I've tried a few things but for some reason it just won't work. Here's an example of what I have to do. Say I have this table:

     table1:

| in/out | year   |
|   in   | 2011-12|
|   in   | 2011-12|
|   in   | 2012-13|
|   out  | 2011-12|
|   out  |2012-13 |
|   out  |2012-13 |

I want to reformat this table to look like this:

|in/out| 2011-12 | 2012-13
|  in  |   2     |   1
|  out |   1     |   2

The first column is the in/out and the rest are just the years where the numbers under them is just a count of for example how many ins or outs happened that year. Any help would be greatly appreciated. Thanks in advance.

Body:
The query would be

TRANSFORM   Sum(amount) AS SumOfamount
SELECT      [in/out]
FROM        Table1
GROUP BY    [in/out]
PIVOT       [year]

Graphically it looks like this:

You might want to change the field name from year though as that's a reserved word and may confuse the database.


问:
PHP Search File
i m not sure on how to write a code to search for files in a folder. i have the code below to view all file from a folder call "FILES".

example of file have

```<code>abc-def.txt
ghi-jkl.txt
</code>```

so i would like to have like an input where if i enter like abc so it will search for all file which have abc in it and display out. is it possible ?

```<code>$thelist = "";
if ($handle = opendir('./files/')) {
  while (false !== ($file = readdir($handle))){
    if ($file != "." && $file != ".."){
      $thelist .= $file . '<br>';
    }
  }
  closedir($handle);
}
echo $thelist;
unset($thelist);
</code>```

i need help in it.

答:
Use glob to find pathnames matching a pattern or a GlobIterator.

If you need that to be recursive use a RegexIterator and a RecursiveDirectoryIterator. See here

Title: PHP Search File

Body:
i m not sure on how to write a code to search for files in a folder. i have the code below to view all file from a folder call "FILES".

example of file have

abc-def.txt
ghi-jkl.txt

so i would like to have like an input where if i enter like abc so it will search for all file which have abc in it and display out. is it possible ?

$thelist = "";
if ($handle = opendir('./files/')) {
  while (false !== ($file = readdir($handle))){
    if ($file != "." && $file != ".."){
      $thelist .= $file . '
';
    }
  }
  closedir($handle);
}
echo $thelist;
unset($thelist);

i need help in it.


问:
Django settings - customize attributes per Site from admin
I'm using django sites framework.

I've a model with a OneToOneField to Site model. This way the admin users can customize each site attributes from the admin panel.

```<code>class CustomSite(models.Model):
    site = models.OneToOneField(Site)
    email_host_user = models.EmailField()
    ...
</code>```

Some of these fields are actually values that should be used in the settings file, like EMAIL_HOST_USER.

How can I use these values in the settings file of the custom sites? is this the correct approach?

答:
Found a solution:

Settings are saved in the DB using this model. Then I create a custom e-mail backend that I can pass to EmailMultiAlternatives() through the 'connection' param.

This way I don't need to store the email settings in any settings file.

Body:
I'm using django sites framework.

I've a model with a OneToOneField to Site model. This way the admin users can customize each site attributes from the admin panel.

class CustomSite(models.Model):
    site = models.OneToOneField(Site)
    email_host_user = models.EmailField()
    ...

Some of these fields are actually values that should be used in the settings file, like EMAIL_HOST_USER.

How can I use these values in the settings file of the custom sites? is this the correct approach?


问:
Need to lookup 2 columns in VBA Function
I need to use to lookup columns in from another sheet and return in a single cell VBA. My Data in Sheet1 is,

```<code>P.No.  REV   Qty
2918   01    50
2918   02    44
2919   01    72
</code>```

In Sheet2, It should return the Qty, by looking both the P.No. and REV columns. Kindly help me on this.

My code to lookup one column is below. In this I need to lookup two columns.

```<code>Function SingleCellExtractInward(lookupvalue As String, lookuprange As Range, ColumnNumber As Integer)
    Dim i As Double
    Dim Result1 As String
    Dim Result2 As String

    If Result2 = Empty Then
        Result2 = "no recent inward"
        SingleCellExtractInward = Result2
    End If

    For i = 1 To lookuprange.Columns(1).Cells.Count
        If lookuprange.Cells(i, 1) = lookupvalue Then
            Result1 = Result1 & " " & lookuprange.Cells(i, ColumnNumber) & ","
            SingleCellExtractInward = Left(Result1, Len(Result1) - 1)
        End If
    Next i
End Function
</code>```

答:
Try to use this function:

```<code>    Function LookupTwoCriteria(strPNo As String, strRev As String)

      LookupTwoCriteria = Evaluate("=INDEX(Sheet1!C:C,MATCH(1,(Sheet1!A:A=" & _
        strPNo & ")*(Sheet1!B:B=" & strRev & "),0))")

    End Function
</code>```

It uses array formula that tries to match two criteria: strPNo & strRev.  Use this in your cell like:

```<code>    =LookupTwoCriteria(A1, B1)
</code>```

If it does not find a match, it will exhibit #VALUE! so guard it with:

```<code>    =IFERROR(LookupTwoCriteria(A4,B4),0)
</code>```

if you desire so.

Body:
I need to use to lookup columns in from another sheet and return in a single cell VBA. My Data in Sheet1 is,

P.No.  REV   Qty
2918   01    50
2918   02    44
2919   01    72

In Sheet2, It should return the Qty, by looking both the P.No. and REV columns. Kindly help me on this.

My code to lookup one column is below. In this I need to lookup two columns.

Function SingleCellExtractInward(lookupvalue As String, lookuprange As Range, ColumnNumber As Integer)
    Dim i As Double
    Dim Result1 As String
    Dim Result2 As String

    If Result2 = Empty Then
        Result2 = "no recent inward"
        SingleCellExtractInward = Result2
    End If

    For i = 1 To lookuprange.Columns(1).Cells.Count
        If lookuprange.Cells(i, 1) = lookupvalue Then
            Result1 = Result1 & " " & lookuprange.Cells(i, ColumnNumber) & ","
            SingleCellExtractInward = Left(Result1, Len(Result1) - 1)
        End If
    Next i
End Function

Body:
Try to use this function:

    Function LookupTwoCriteria(strPNo As String, strRev As String)

      LookupTwoCriteria = Evaluate("=INDEX(Sheet1!C:C,MATCH(1,(Sheet1!A:A=" & _
        strPNo & ")*(Sheet1!B:B=" & strRev & "),0))")

    End Function

It uses array formula that tries to match two criteria: strPNo & strRev.  Use this in your cell like:

    =LookupTwoCriteria(A1, B1)

If it does not find a match, it will exhibit #VALUE! so guard it with:

    =IFERROR(LookupTwoCriteria(A4,B4),0)

if you desire so.


问:
Best practice for using date parameters in Spring controllers?
After written several backend APIs, I found that the following code duplicates in almost every method which needs to filter data by dates:

@GetMapping(value="/api/test")
@ResponseBody
public Result test(@RequestParam(value = "since", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate since,
                   @RequestParam(value = "until", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate until) {
    // Date validation code I want to eliminate
    since = ObjectUtils.defaultIfNull(since, DEFAULT_SINCE_DATE);
    until = ObjectUtils.defaultIfNull(until, LocalDate.now().plusDays(1));
    if(since.isAfter(until)) {
        throw new SinceDateAfterUntilDateException();
    }

    // Do stuff
}
```

Obviously this is some kind of code smell. But, since I do need to validate since and until before using them to query the service/DAO, I am not sure where should I extract these code to?

Any advice?

答:
As ol' gud-procedural approach suggests:</p>

```<code>public Result test(@RequestParam(value = "since", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate since,
               @RequestParam(value = "until", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate until) {
     checkInputDates();
     // Do stuff
}

private checkInputDates(LocalDate since, LocalDate until) {
    since = ObjectUtils.defaultIfNull(since, DEFAULT_SINCE_DATE);
    until = ObjectUtils.defaultIfNull(until, LocalDate.now().plusDays(1));
    if(since.isAfter(until)) {
        throw new SinceDateAfterUntilDateException();
    }
}
//so on..
</code>```

Body:
After written several backend APIs, I found that the following code duplicates in almost every method which needs to filter data by dates:

@GetMapping(value="/api/test")
@ResponseBody
public Result test(@RequestParam(value = "since", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate since,
                   @RequestParam(value = "until", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate until) {
    // Date validation code I want to eliminate
    since = ObjectUtils.defaultIfNull(since, DEFAULT_SINCE_DATE);
    until = ObjectUtils.defaultIfNull(until, LocalDate.now().plusDays(1));
    if(since.isAfter(until)) {
        throw new SinceDateAfterUntilDateException();
    }

    // Do stuff
}

Obviously this is some kind of code smell. But, since I do need to validate since and until before using them to query the service/DAO, I am not sure where should I extract these code to?

Any advice?

Body:
As ol' gud-procedural approach suggests:

public Result test(@RequestParam(value = "since", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate since,
               @RequestParam(value = "until", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate until) {
     checkInputDates();
     // Do stuff
}

private checkInputDates(LocalDate since, LocalDate until) {
    since = ObjectUtils.defaultIfNull(since, DEFAULT_SINCE_DATE);
    until = ObjectUtils.defaultIfNull(until, LocalDate.now().plusDays(1));
    if(since.isAfter(until)) {
        throw new SinceDateAfterUntilDateException();
    }
}
//so on..


问:
How to implement data compression in Redis written from R with rredis to reduce memory usage?
I need to compress data stored in Redis. I write the data from R (with package rredis) to Redis like this:

```<code>redisSet("x","{\"email\":\"master@disaster.com\",\"Ranking\":[{\"Number\":37665,\"rank\":1},{\"Number\":41551,\"rank\":2},{\"Number\":21684,\"rank\":3},{\"Number\":35946,\"rank\":4}]}")
</code>```

Instead of 4 elements in the list of this value there will be 4000 in the real scenario and 70000 keys like that in total. At the moment each of these keys take ~0.15 MB.

I read that it is possible to compress the memory usage of those entries in Redis significantly, e.g. with algorithms like LZO or Snappy. But I could not find information about the concrete implementation.
Some suggestions to solve the problem? Thanks!

答:
Thanks for the hint! I was able to implement it, here are some details:

I used a compression function implemented in R (base package), as suggested.

```<code>memCompress()
</code>```

I tried different compressions gzip and bzip2.

```<code>memCompress(type="gzip",...)
memCompress(type="bzip2",...)
</code>```

Here is the code with a toy example:

```<code>#In R:
x<-"{\"email\":\"master@disaster.com\",\"Ranking\":[{\"Number\":37665,\"rank\":1},{\"Number\":41551,\"rank\":2},{\"Number\":21684,\"rank\":3},{\"Number\":35946,\"rank\":4}]}"
y<-memCompress(charToRaw(x),type="gzip")
# [1] 78 9c 4d c9 3d 0a 80 20 00 06 d0 bb 7c b3 04 e6 4f e5 d4 09 1a 5a a3 c1 4a 42 ca 02 ad 29 bc 7b 11 48 6d 0f de 05 e3 b4 5d a1 e0 74 38 8c
# [47] af 27 1b 5e 64 e3 ee 40 d0 ea 6d b1 db 0c d5 5d 68 4e 37 18 0f c5 0a 29 05 81 7f 0a 8a 46 f2 0d a7 42 d0 34 f9 7f 72 2a 4b 9e 86 fd 87 89
# [93] 8a cb 34 3c f6 f1 06 b3 67 2d c4
rawToChar(memDecompress(y,type="gzip"))
# [1] "{\"email\":\"master@disaster.com\",\"Ranking\":[{\"Number\":37665,\"rank\":1},{\"Number\":41551,\"rank\":2},{\"Number\":21684,\"rank\":3},{\"Number\":35946,\"rank\":4}]}"

# R to redis:
redisConnect(host="XXX.XX.XX.XXX", port=XXXX, timeout =10) # Insert your redis information (IP and port)
x<-"{\"email\":\"master@disaster.com\",\"Ranking\":[{\"Number\":37665,\"rank\":1},{\"Number\":41551,\"rank\":2},{\"Number\":21684,\"rank\":3},{\"Number\":35946,\"rank\":4}]}"
redisSet("x",x) #Wrong transfer of character string to redis
# redis-cli # On redis server
# get x # On redis server
# "X\n\x00\x00\x00\x02\x00\x03\x03\x02\x00\x02\x03\x00\x00\x00\x00\x10\x00\x00\x00\x01\x00\x04\x00\t\x00\x00\x00\x93{\"email\":\"master@disaster.com\",\"Ranking\":[{\"Number\":37665,\"rank\":1},{\"Number\":41551,\"rank\":2},{\"Number\":21684,\"rank\":3},{\"Number\":35946,\"rank\":4}]}"
redisSet("x",charToRaw(x)) #Right transfer of character string to redis
# redis-cli # On redis server
# get x # On redis server
# "{\"email\":\"master@disaster.com\",\"Ranking\":[{\"Number\":37665,\"rank\":1},{\"Number\":41551,\"rank\":2},{\"Number\":21684,\"rank\":3},{\"Number\":35946,\"rank\":4}]}"
redisSet("x",memCompress(charToRaw(x),type="gzip")) #Right transfer of compressed string to redis
# redis-cli # On redis server
# get x # On redis server
# "x\x9cM\xc9=\n\x80 \x00\x06\xd0\xbb|\xb3\x04\xe6O\xe5\xd4\t\x1aZ\xa3\xc1JB\xca\x02\xad)\xbc{\x11Hm\x0f\xde\x05\xe3\xb4]\xa1\xe0t8\x8c\xaf'\x1b^d\xe3\xee@\xd0\xeam\xb1\xdb\x0c\xd5]hN7\x18\x0f\xc5\n)\x05\x81\x7f\n\x8aF\xf2\r\xa7B\xd04\xf9\x7fr*K\x9e\x86\xfd\x87\x89\x8a\xcb4<\xf6\xf1\x06\xb3g-\xc4"

# I have not implemented the reimport to R yet. So feel free to add it :)
</code>```

There is no improvement for this short string. But for the long version (4000 instead of 4 elements in the json file) there was a huge improvement:

Compression gives an improvement by ~85% in memory usage and writing time in this case!

Compressed:
Time to write 500 users with 4.000 elements each to redis: 12.62 sec
Memory kept by 500 users with 4.000 elements each on redis: 11.782 MB

Uncompressed:
Time to write 500 users with 4.000 elements each to redis: 88.76 sec
Memory kept by 500 users with 4.000 elements each on redis: 78.192 MB

Body:
I need to compress data stored in Redis. I write the data from R (with package rredis) to Redis like this:

redisSet("x","{\"email\":\"master@disaster.com\",\"Ranking\":[{\"Number\":37665,\"rank\":1},{\"Number\":41551,\"rank\":2},{\"Number\":21684,\"rank\":3},{\"Number\":35946,\"rank\":4}]}")

Instead of 4 elements in the list of this value there will be 4000 in the real scenario and 70000 keys like that in total. At the moment each of these keys take ~0.15 MB.

I read that it is possible to compress the memory usage of those entries in Redis significantly, e.g. with algorithms like LZO or Snappy. But I could not find information about the concrete implementation.
Some suggestions to solve the problem? Thanks!

Body:
Thanks for the hint! I was able to implement it, here are some details:

I used a compression function implemented in R (base package), as suggested.

memCompress()

I tried different compressions gzip and bzip2.

memCompress(type="gzip",...)
memCompress(type="bzip2",...)

Here is the code with a toy example:

#In R:
x<-"{\"email\":\"master@disaster.com\",\"Ranking\":[{\"Number\":37665,\"rank\":1},{\"Number\":41551,\"rank\":2},{\"Number\":21684,\"rank\":3},{\"Number\":35946,\"rank\":4}]}"
y<-memCompress(charToRaw(x),type="gzip")
# [1] 78 9c 4d c9 3d 0a 80 20 00 06 d0 bb 7c b3 04 e6 4f e5 d4 09 1a 5a a3 c1 4a 42 ca 02 ad 29 bc 7b 11 48 6d 0f de 05 e3 b4 5d a1 e0 74 38 8c
# [47] af 27 1b 5e 64 e3 ee 40 d0 ea 6d b1 db 0c d5 5d 68 4e 37 18 0f c5 0a 29 05 81 7f 0a 8a 46 f2 0d a7 42 d0 34 f9 7f 72 2a 4b 9e 86 fd 87 89
# [93] 8a cb 34 3c f6 f1 06 b3 67 2d c4
rawToChar(memDecompress(y,type="gzip"))
# [1] "{\"email\":\"master@disaster.com\",\"Ranking\":[{\"Number\":37665,\"rank\":1},{\"Number\":41551,\"rank\":2},{\"Number\":21684,\"rank\":3},{\"Number\":35946,\"rank\":4}]}"

# R to redis:
redisConnect(host="XXX.XX.XX.XXX", port=XXXX, timeout =10) # Insert your redis information (IP and port)
x<-"{\"email\":\"master@disaster.com\",\"Ranking\":[{\"Number\":37665,\"rank\":1},{\"Number\":41551,\"rank\":2},{\"Number\":21684,\"rank\":3},{\"Number\":35946,\"rank\":4}]}"
redisSet("x",x) #Wrong transfer of character string to redis
# redis-cli # On redis server
# get x # On redis server
# "X\n\x00\x00\x00\x02\x00\x03\x03\x02\x00\x02\x03\x00\x00\x00\x00\x10\x00\x00\x00\x01\x00\x04\x00\t\x00\x00\x00\x93{\"email\":\"master@disaster.com\",\"Ranking\":[{\"Number\":37665,\"rank\":1},{\"Number\":41551,\"rank\":2},{\"Number\":21684,\"rank\":3},{\"Number\":35946,\"rank\":4}]}"
redisSet("x",charToRaw(x)) #Right transfer of character string to redis
# redis-cli # On redis server
# get x # On redis server
# "{\"email\":\"master@disaster.com\",\"Ranking\":[{\"Number\":37665,\"rank\":1},{\"Number\":41551,\"rank\":2},{\"Number\":21684,\"rank\":3},{\"Number\":35946,\"rank\":4}]}"
redisSet("x",memCompress(charToRaw(x),type="gzip")) #Right transfer of compressed string to redis
# redis-cli # On redis server
# get x # On redis server
# "x\x9cM\xc9=\n\x80 \x00\x06\xd0\xbb|\xb3\x04\xe6O\xe5\xd4\t\x1aZ\xa3\xc1JB\xca\x02\xad)\xbc{\x11Hm\x0f\xde\x05\xe3\xb4]\xa1\xe0t8\x8c\xaf'\x1b^d\xe3\xee@\xd0\xeam\xb1\xdb\x0c\xd5]hN7\x18\x0f\xc5\n)\x05\x81\x7f\n\x8aF\xf2\r\xa7B\xd04\xf9\x7fr*K\x9e\x86\xfd\x87\x89\x8a\xcb4<\xf6\xf1\x06\xb3g-\xc4"

# I have not implemented the reimport to R yet. So feel free to add it :)

There is no improvement for this short string. But for the long version (4000 instead of 4 elements in the json file) there was a huge improvement:

Compression gives an improvement by ~85% in memory usage and writing time in this case!

Compressed:
Time to write 500 users with 4.000 elements each to redis: 12.62 sec
Memory kept by 500 users with 4.000 elements each on redis: 11.782 MB

Uncompressed:
Time to write 500 users with 4.000 elements each to redis: 88.76 sec
Memory kept by 500 users with 4.000 elements each on redis: 78.192 MB


问:
Return string from Fortran to C++
I have the following function call in C++:

```<code>int strLength = 20;
char* name;

getName(name, strLength);

printf("name: %s\n", name);
</code>```

and in Fortran:

```<code>subroutine getName(name) bind (c, name='GETNAME')
use,intrinsic :: iso_c_binding
implicit none
character, intent(out) :: name

name = 'Martin'
end subroutine getName
</code>```

When I execute the C++ routine the output is: name: M. Now, I suppose this happens because character, intent(out) :: name declares the name variable with size of 1, but if I change the declaration to this: character(len=6), intent(out) :: name I get this error message: Error: Character argument 'name' at (1) must be length 1 because procedure 'getname' is BIND(C). I've also tried this: character(len=6,kind=c_char), intent(out) :: name, with the same error message. Lastly, I tried this declaration: character(c_char),dimension(6), intent(out) :: name, which compiles but, yields this result: name: MMMMMM.

My question boils down to: How can I return a string from Fortran to C++?

答:
The problem was in assigning a character array of rank n to a character scalar of length n, which was addressed in this question. Changing the Fortran routine as shown below solved the issue.

Solution

Since I'm working in a legacy system I had to go for the solution indicated below. Obviously it's not exactly the same, but it still shows the general structure. If anyone else should go for this solution as well you should probably follow the recommendations in Matt P's comment.

Although this is the solution I went for, I feel like the answer from Matt P is a better solution to the general problem as stated in the question title, which is why I accepted that as the answer.

C++

```<code>int strLength = 20;
char* name = new char[strLength];
getName(name, strLength);
printf("name: %s\n", name);
</code>```

Fortran

```<code>subroutine getName(name) bind (c, name='GETNAME')
use,intrinsic :: iso_c_binding
implicit none
character(c_char),dimension(20), intent(out) :: name
character(20) :: fName

fName = 'Martin'//c_null_char

do j=1,len(fName )
  name(j) = fName (j:j)
enddo

end subroutine getName
</code>```

Title: Return string from Fortran to C++

Body:
I have the following function call in C++:

int strLength = 20;
char* name;

getName(name, strLength);

printf("name: %s\n", name);

and in Fortran:

subroutine getName(name) bind (c, name='GETNAME')
use,intrinsic :: iso_c_binding
implicit none
character, intent(out) :: name

name = 'Martin'
end subroutine getName

When I execute the C++ routine the output is: name: M. Now, I suppose this happens because character, intent(out) :: name declares the name variable with size of 1, but if I change the declaration to this: character(len=6), intent(out) :: name I get this error message: Error: Character argument 'name' at (1) must be length 1 because procedure 'getname' is BIND(C). I've also tried this: character(len=6,kind=c_char), intent(out) :: name, with the same error message. Lastly, I tried this declaration: character(c_char),dimension(6), intent(out) :: name, which compiles but, yields this result: name: MMMMMM.

My question boils down to: How can I return a string from Fortran to C++?

Body:
The problem was in assigning a character array of rank n to a character scalar of length n, which was addressed in this question. Changing the Fortran routine as shown below solved the issue.

Solution

Since I'm working in a legacy system I had to go for the solution indicated below. Obviously it's not exactly the same, but it still shows the general structure. If anyone else should go for this solution as well you should probably follow the recommendations in Matt P's comment.

Although this is the solution I went for, I feel like the answer from Matt P is a better solution to the general problem as stated in the question title, which is why I accepted that as the answer.

C++

int strLength = 20;
char* name = new char[strLength];
getName(name, strLength);
printf("name: %s\n", name);

Fortran

subroutine getName(name) bind (c, name='GETNAME')
use,intrinsic :: iso_c_binding
implicit none
character(c_char),dimension(20), intent(out) :: name
character(20) :: fName

fName = 'Martin'//c_null_char

do j=1,len(fName )
  name(j) = fName (j:j)
enddo

end subroutine getName


问:
Where can you find the control panel for xampp in mac?
This seems like a very basic question, but I can't seem to find a straightforward answer online after searching for very long.

I am using xampp, but can't seem to find the control panel.

The only application I have is manager-osx

Is there something missing in my download? Or is there a procedure to run the control panel?

Thank you very much!

答: I looked up the question on the apache forum for mac and it appears there the interface you're looking for is only available on Windows.</p>


问:
Merge E-Signature with DOC to PDF
I have E-Signature saved on png file with transparent BG and I want to merge it with a word document on a specific location on the document and saved it to one PDF by using C#
How can I do it?</p>

答:
office interop.

It's quite involved so start by googling that to get started (opening the file, moving around, inserting picture, saving file.)

Title: Merge E-Signature with DOC to PDF


问:
NPM install hangs on loadRequestedDeps
When I download any package using NPM, it hangs on the last command "loadRequestedDeps." I've added my whole -verbose output to the end of this question for reference. It will just sit there until I cancel the command, and nothing will be installed and my package.json will not be updated.

What could the issue be? I've looked around but haven't found out how to fix my particular problem.

Here's some info:

OS is Windows 10

Node version is 6.9.1

NPM version is 3.10.8

My CPU maxes out at 100% whenever I run NPM install. Could that be the issue itself? I used to be able to use NPM install on this computer, however.

Thanks for anyone who can help. The verbose output is below.

```<code>npm info it worked if it ends with ok
npm info using npm@3.10.8
npm info using node@v6.9.1
npm info ok
npm info it worked if it ends with ok
npm verb cli [ 'C:\\Program Files\\nodejs\\node.exe',
npm verb cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
npm verb cli   'install',
npm verb cli   'moment',
npm verb cli   '--save',
npm verb cli   '-verbose' ]
npm info using npm@3.10.8
npm info using node@v6.9.1
npm verb request uri https://registry.npmjs.org/moment
npm verb request no auth needed
npm info attempt registry request try #1 at 11:19:11 AM
npm verb request id 6aa9ece5a04fcd33
npm verb etag W/"583b0871-194b0"
npm verb lastModified Sun, 27 Nov 2016 16:23:13 GMT
npm http request GET https://registry.npmjs.org/moment
npm http 304 https://registry.npmjs.org/moment
npm verb headers { date: 'Tue, 29 Nov 2016 19:19:02 GMT',
npm verb headers   via: '1.1 varnish',
npm verb headers   'cache-control': 'max-age=300',
npm verb headers   etag: 'W/"583b0871-194b0"',
npm verb headers   age: '11',
npm verb headers   connection: 'keep-alive',
npm verb headers   'x-served-by': 'cache-sjc3136-SJC',
npm verb headers   'x-cache': 'HIT',
npm verb headers   'x-cache-hits': '1',
npm verb headers   'x-timer': 'S1480447142.653125,VS0,VE0',
npm verb headers   vary: 'Accept-Encoding' }
npm verb etag https://registry.npmjs.org/moment from cache
npm verb get saving moment to C:\Users\Zach\AppData\Roaming\npm-cache\registry.npmjs.org\moment\.cache.json
npm verb correctMkdir C:\Users\Zach\AppData\Roaming\npm-cache correctMkdir not in flight; initializing
npm verb cache add spec moment
npm verb addNamed "latest" is being treated as a dist-tag for moment
npm info addNameTag [ 'moment', 'latest' ]
npm verb addNameTag registry:https://registry.npmjs.org/moment not in flight; fetching
npm verb get https://registry.npmjs.org/moment not expired, no request
npm verb addNamed "2.17.0" is a plain semver version for moment
npm verb addRemoteTarball https://registry.npmjs.org/moment/-/moment-2.17.0.tgz not in flight; adding
npm verb addRemoteTarball [ 'https://registry.npmjs.org/moment/-/moment-2.17.0.tgz',
npm verb addRemoteTarball   'a4c292e02aac5ddefb29a6eed24f51938dd3b74f' ]
[    ..............] \ loadRequestedDeps: verb addRemoteTarball [ 'https://registry.npmjs.org/moment/-/moment-2.17.0.tgz',
</code>```

答:
Finally Resolved The Problem(Wondering)

Change Both System And User TEMP Variable point to C:\temp and make a directory as C:\temp.

1.TEMP=C:\temp;

2.Make A Directory temp at C:\

Title: NPM install hangs on loadRequestedDeps

Body:
When I download any package using NPM, it hangs on the last command "loadRequestedDeps." I've added my whole -verbose output to the end of this question for reference. It will just sit there until I cancel the command, and nothing will be installed and my package.json will not be updated.

What could the issue be? I've looked around but haven't found out how to fix my particular problem.

Here's some info:

OS is Windows 10

Node version is 6.9.1

NPM version is 3.10.8

My CPU maxes out at 100% whenever I run NPM install. Could that be the issue itself? I used to be able to use NPM install on this computer, however.

Thanks for anyone who can help. The verbose output is below.

npm info it worked if it ends with ok
npm info using npm@3.10.8
npm info using node@v6.9.1
npm info ok
npm info it worked if it ends with ok
npm verb cli [ 'C:\\Program Files\\nodejs\\node.exe',
npm verb cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
npm verb cli   'install',
npm verb cli   'moment',
npm verb cli   '--save',
npm verb cli   '-verbose' ]
npm info using npm@3.10.8
npm info using node@v6.9.1
npm verb request uri https://registry.npmjs.org/moment
npm verb request no auth needed
npm info attempt registry request try #1 at 11:19:11 AM
npm verb request id 6aa9ece5a04fcd33
npm verb etag W/"583b0871-194b0"
npm verb lastModified Sun, 27 Nov 2016 16:23:13 GMT
npm http request GET https://registry.npmjs.org/moment
npm http 304 https://registry.npmjs.org/moment
npm verb headers { date: 'Tue, 29 Nov 2016 19:19:02 GMT',
npm verb headers   via: '1.1 varnish',
npm verb headers   'cache-control': 'max-age=300',
npm verb headers   etag: 'W/"583b0871-194b0"',
npm verb headers   age: '11',
npm verb headers   connection: 'keep-alive',
npm verb headers   'x-served-by': 'cache-sjc3136-SJC',
npm verb headers   'x-cache': 'HIT',
npm verb headers   'x-cache-hits': '1',
npm verb headers   'x-timer': 'S1480447142.653125,VS0,VE0',
npm verb headers   vary: 'Accept-Encoding' }
npm verb etag https://registry.npmjs.org/moment from cache
npm verb get saving moment to C:\Users\Zach\AppData\Roaming\npm-cache\registry.npmjs.org\moment\.cache.json
npm verb correctMkdir C:\Users\Zach\AppData\Roaming\npm-cache correctMkdir not in flight; initializing
npm verb cache add spec moment
npm verb addNamed "latest" is being treated as a dist-tag for moment
npm info addNameTag [ 'moment', 'latest' ]
npm verb addNameTag registry:https://registry.npmjs.org/moment not in flight; fetching
npm verb get https://registry.npmjs.org/moment not expired, no request
npm verb addNamed "2.17.0" is a plain semver version for moment
npm verb addRemoteTarball https://registry.npmjs.org/moment/-/moment-2.17.0.tgz not in flight; adding
npm verb addRemoteTarball [ 'https://registry.npmjs.org/moment/-/moment-2.17.0.tgz',
npm verb addRemoteTarball   'a4c292e02aac5ddefb29a6eed24f51938dd3b74f' ]
[    ..............] \ loadRequestedDeps: verb addRemoteTarball [ 'https://registry.npmjs.org/moment/-/moment-2.17.0.tgz',


问:
How to call object from one class to another in C#
I have a problem that I just can't solve on my own. I am new to programming and I would appreciate if you could help me with this issue:

I have a class I would like to inherit from:

```<code>namespace rsDeployer.Common.SQLServerCommunication
{
    public class RSDatabaseConnectionCreator: LoggerBase
    {
        public RSProfile profile;
        public RSDatabaseConnectionCreator(RSProfile profile)
        {
            this.profile = profile;
        }

        public SqlConnection CreateConnection(RSDatabaseNames DatabaseName, bool UseWindowsAuthentication, bool testConnection = false)
        {
            var connectionString = BuildRSDatabaseConnectionString(DatabaseName, UseWindowsAuthentication);
            if (testConnection)
            {
                return IsConnectionAvailable(connectionString) ? new SqlConnection(connectionString) : null;
            }
            return new SqlConnection(connectionString);
        }
    }
}
</code>```

and I would like to call CreateConnection() in another class to inject to methods to allow me to open connection and then execute scripts.

Edit 1 - class I would like to have it injected to.

```<code>        public void QueryExecution(string SQLQuery)
    {

        //here's where I would like to inject it
        SqlCommand command = new SqlCommand(SQLQuery, conn);
        var file = new StreamWriter(@"D:\Project\rsDeployer\ImportedQuery.txt");
        file.WriteLine(command);
        file.Close();
    }
</code>```

If this question is way to silly to deserve answer would you just point in the direction where I should read about it?

I hope this question is well asked and clear.
Thanks in advance.

答:
You can inject the connection creator into the consumer class through the constructor.

```<code>public class Consumer
{
    private RSDatabaseConnectionCreator _connectionCreator;

    // Constructor injection
    public Consumer (RSDatabaseConnectionCreator connectionCreator)
    {
        _connectionCreator = connectionCreator;
    }

    public void QueryExecution(string SQLQuery)
    {
        using (var conn = _connectionCreator.CreateConnection(dbName, true, true)) {
            if (conn != null) {
                ...
            }
        }
    }
}
</code>```

Note: The using statement automatically closes the connection.

Usage

```<code>var connectionCreator = new RSDatabaseConnectionCreator(profile);
var consumer = new Consumer(connectionCreator);
consumer.QueryExecution(sqlQuery);
</code>```

If you want to inject the connection creator at each call of QueryExecution, you can inject it directly into the method as an additional parameter, instead.

```<code>public void QueryExecution(string SQLQuery, RSDatabaseConnectionCreator connectionCreator)
{
    using (var conn = connectionCreator.CreateConnection(dbName, true, true)) {
        if (conn != null) {
            ...
        }
    }
}
</code>```

Usage

```<code>var connectionCreator = new RSDatabaseConnectionCreator(profile);
var consumer = new Consumer();
consumer.QueryExecution(sqlQuery, connectionCreator);
</code>```

Body:
I have a problem that I just can't solve on my own. I am new to programming and I would appreciate if you could help me with this issue:

I have a class I would like to inherit from:

namespace rsDeployer.Common.SQLServerCommunication
{
    public class RSDatabaseConnectionCreator: LoggerBase
    {
        public RSProfile profile;
        public RSDatabaseConnectionCreator(RSProfile profile)
        {
            this.profile = profile;
        }

        public SqlConnection CreateConnection(RSDatabaseNames DatabaseName, bool UseWindowsAuthentication, bool testConnection = false)
        {
            var connectionString = BuildRSDatabaseConnectionString(DatabaseName, UseWindowsAuthentication);
            if (testConnection)
            {
                return IsConnectionAvailable(connectionString) ? new SqlConnection(connectionString) : null;
            }
            return new SqlConnection(connectionString);
        }
    }
}

and I would like to call CreateConnection() in another class to inject to methods to allow me to open connection and then execute scripts.

Edit 1 - class I would like to have it injected to.

        public void QueryExecution(string SQLQuery)
    {

        //here's where I would like to inject it
        SqlCommand command = new SqlCommand(SQLQuery, conn);
        var file = new StreamWriter(@"D:\Project\rsDeployer\ImportedQuery.txt");
        file.WriteLine(command);
        file.Close();
    }

If this question is way to silly to deserve answer would you just point in the direction where I should read about it?

I hope this question is well asked and clear.
Thanks in advance.

Body:
You can inject the connection creator into the consumer class through the constructor.

public class Consumer
{
    private RSDatabaseConnectionCreator _connectionCreator;

    // Constructor injection
    public Consumer (RSDatabaseConnectionCreator connectionCreator)
    {
        _connectionCreator = connectionCreator;
    }

    public void QueryExecution(string SQLQuery)
    {
        using (var conn = _connectionCreator.CreateConnection(dbName, true, true)) {
            if (conn != null) {
                ...
            }
        }
    }
}

Note: The using statement automatically closes the connection.

Usage

var connectionCreator = new RSDatabaseConnectionCreator(profile);
var consumer = new Consumer(connectionCreator);
consumer.QueryExecution(sqlQuery);

If you want to inject the connection creator at each call of QueryExecution, you can inject it directly into the method as an additional parameter, instead.

public void QueryExecution(string SQLQuery, RSDatabaseConnectionCreator connectionCreator)
{
    using (var conn = connectionCreator.CreateConnection(dbName, true, true)) {
        if (conn != null) {
            ...
        }
    }
}

Usage

var connectionCreator = new RSDatabaseConnectionCreator(profile);
var consumer = new Consumer();
consumer.QueryExecution(sqlQuery, connectionCreator);


问:
What is the Spring Data JPA method to use findBy for multiple fields and also use Containing clause for all the fields
I have a class called Profile and its JPA repository ProfileRepo
I'm trying to use findBy method to find names using first name or middle name or last name and also using containing clause.

```<code>public class Profile{
    private String firstName;
    private String middleName;
    private String lastName;

    //getters and setters
}
</code>```

Am using the following query in the JPA repository but it is not accepting the method

```<code>List<Profile> findByLastNameContainingOrFirstNameContainingOrMiddleNameContainingAllIgnoreCase(String firstName,
        String lastName,String midName);
</code>```

Kindly help out.

答:
Try this:

```<code>List<Profile> findByFirstNameIgnoreCaseContainingOrLastNameIgnoreCaseContainingOrMidNameIgnoreCaseContaining(String firstName, String lastName, String midName);
</code>```

or this:

```<code>@Query("select p from Profile p where upper(p.firstName) like concat('%', upper(?1), '%') or upper(p.lastName) like concat('%', upper(?2), '%') or upper(p.midName) like concat('%', upper(?3), '%')")
List<Profile> getByNames(String firstName, String lastName, String midName);
</code>```

Body:
I have a class called Profile and its JPA repository ProfileRepo
I'm trying to use findBy method to find names using first name or middle name or last name and also using containing clause.

public class Profile{
    private String firstName;
    private String middleName;
    private String lastName;

    //getters and setters
}

Am using the following query in the JPA repository but it is not accepting the method

List<Profile> findByLastNameContainingOrFirstNameContainingOrMiddleNameContainingAllIgnoreCase(String firstName,
        String lastName,String midName);

Kindly help out.

Body:
Try this:

List<Profile> findByFirstNameIgnoreCaseContainingOrLastNameIgnoreCaseContainingOrMidNameIgnoreCaseContaining(String firstName, String lastName, String midName);

or this:

@Query("select p from Profile p where upper(p.firstName) like concat('%', upper(?1), '%') or upper(p.lastName) like concat('%', upper(?2), '%') or upper(p.midName) like concat('%', upper(?3), '%')")
List<Profile> getByNames(String firstName, String lastName, String midName);


问:
How to make array search filter in angular2?
I create a text box and an array. I want to filter array items according to the text box value.

 <input type="text" placeholder="Search Tickets"
 class="searchboxttext" [(ngModel)]="searchfav"/>

```

How do I filter an array in angular2?

答:
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'searchfilter',
  pure: false
})
export class SearchfilterPipe implements PipeTransform {

  transform(items: any, term: any): any {
    if (term === undefined) return items;

    return items.filter(function(item) {
      for(let property in item){
        if (item[property] === null){
          continue;
        }
        if(item[property].toString().toLowerCase().includes(term.toLowerCase())){
          return true;
        }
      }
      return false;
    });
  }
}```
</div>
</div>
</p>

<p>This works 100% fine like I expected. Save this as pipe and import this in both appmodule and your component.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>
     <div class="searchboxt"> <input type="text" placeholder="Search Tickets" class="searchboxttext" [(ngModel)]="searchfav"/> </div>

   <li class="selectlistticket" *ngFor="let fav of favlist.slice().reverse() | searchfilter :searchfav" (mouseover)="showfavstar(fav)" (mouseleave)="hidefavstar(fav)"></code>```

Body:
I create a text box and an array. I want to filter array items according to the text box value.

 <input type="text" placeholder="Search Tickets"
 class="searchboxttext" [(ngModel)]="searchfav"/>

How do I filter an array in angular2?

Body:
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'searchfilter',
  pure: false
})
export class SearchfilterPipe implements PipeTransform {

  transform(items: any, term: any): any {
    if (term === undefined) return items;

    return items.filter(function(item) {
      for(let property in item){
        if (item[property] === null){
          continue;
        }
        if(item[property].toString().toLowerCase().includes(term.toLowerCase())){
          return true;
        }
      }
      return false;
    });
  }
}

This works 100% fine like I expected. Save this as pipe and import this in both appmodule and your component.

     <div class="searchboxt"> <input type="text" placeholder="Search Tickets" class="searchboxttext" [(ngModel)]="searchfav"/> </div>

   <li class="selectlistticket" *ngFor="let fav of favlist.slice().reverse() | searchfilter :searchfav" (mouseover)="showfavstar(fav)" (mouseleave)="hidefavstar(fav)">


问:
Using echo y as an automated response to a pcp hostkey prompt
I am building a batch file so that I can push firmware to 600 plus devices.

If I am at a command prompt I can run the following command on a single line that will push the firmware and answer yes to the SSH key prompt.

```<code>echo y | pscp -v -scp -pw password C:\CNA1000\Firmware\CNA1504v1.1.7\CNA1504v1_1_7.run root@192.168.1.1:/tmp/.
</code>```

The echo y | answers yes to the SSH keys prompt. However when I try to add it to a batch file I get an error in the command prompt that it did not like the password.

Specifically, it looks like this;

```<code>Using username "root".
root@192.168.1.1's password:
Sent password
Access denied
Access denied
</code>```

and then it repeats itself until I hit CTRL+C to break the batch file.

Is there a better way to do this so that I can automate the process?

Thanks,

答:
Do not blindly answer "y", you lose a protection against man-in-the-middle attacks.

You should use the -hostkey switch with your host key fingerprint.

Actually it's the same with WinSCP, that you ended up using. WinSCP open command also has the -hostkey switch.

If it does work without the -hostkey switch, it's because the host key is cached in Windows registry from some previous interactive use of WinSCP.

Similarly, that's the same with pscp. Had you used PuTTY or pscp (or any other tools from PuTTY suite) before interactively and had you confirmed the host key, it would get cached. And later automatic uses would pass without confirmation.

Body:
I am building a batch file so that I can push firmware to 600 plus devices.

If I am at a command prompt I can run the following command on a single line that will push the firmware and answer yes to the SSH key prompt.

echo y | pscp -v -scp -pw password C:\CNA1000\Firmware\CNA1504v1.1.7\CNA1504v1_1_7.run root@192.168.1.1:/tmp/.

The echo y | answers yes to the SSH keys prompt. However when I try to add it to a batch file I get an error in the command prompt that it did not like the password.

Specifically, it looks like this;

Using username "root".
root@192.168.1.1's password:
Sent password
Access denied
Access denied

and then it repeats itself until I hit CTRL+C to break the batch file.

Is there a better way to do this so that I can automate the process?

Thanks,


问:
Updating text in Sprite using dirty rectangle method
I am trying to achieve the following using pygame:
printing a changing text part of a sprite and update the sprite every frame.
The sprite is a simple transparent rectangular area surounded by red edges.
At the center of that area a number is printed and that number change over time.
I also want to use the dirty rectangle method.

I haven't managed yet to make it work in my game but I have reproduce the scenario in the following sample (you can run it as is):

```<code>import pygame
from pygame.locals import *

class Sprite(pygame.sprite.Sprite):
        def __init__(self, group=None):

            pygame.sprite.Sprite.__init__(self, group)
            self.counter = 0

            self.image = pygame.Surface((100,100)).convert_alpha()
            self.image.fill((0,0,0,0))
            pygame.draw.rect(self.image, (255,0,0), [ (0,0), (100,100) ], 1)
            self.rect = self.image.get_rect()

            self.myfont = pygame.font.SysFont("monospace", 15)
            text = str(self.counter)
            label = self.myfont.render(text, 1, (255,0,0))
            self.image.blit(label, self.rect.center)

        def update(self):
            rect_save = self.rect
            self.image = pygame.Surface((100,100)).convert_alpha()
            self.image.fill((0,0,0,0))
            pygame.draw.rect(self.image, (255,0,0), [ (0,0), (100,100) ], 1)
            self.rect = self.image.get_rect()
            self.rect.x = rect_save[0]
            self.rect.y = rect_save[1]

            text = str(self.counter)
            label = self.myfont.render(text, 1, (255,0,0))

            self.image.blit(label, self.rect.center)

Quit = False

pygame.init()
window = pygame.display.set_mode((640, 480))
render = pygame.sprite.RenderUpdates()

sprite = Sprite(render)
BUG = False
if BUG:
    sprite.rect = (300,300)

while not Quit:
    for event in pygame.event.get():
        if event.type == QUIT:
            Quit = True
        if event.type == KEYDOWN:
            sprite.counter += 1

    background = pygame.Surface( window.get_size() )
    background.fill( (0,0,0) )
    render.clear( window, background )

    render.update()

    dirty = render.draw(window)
    pygame.display.update( dirty )
#end while

pygame.quit()
</code>```

In the code example I have defined a BUG variable to trigger the problem I encounter.
If I set the BUG to False my sprite is rendered as wanted in the top left corner of the screen with the text updating when hitting a key.
However when I set BUG to True the sprite is rendered at the right position on the screen but the text is not there anymore.

How can I make that second case work as expected ?

Thanks

Note:
the following post didn't help solving my problem
Python pygame writing text in sprite

答:
Solution of the BUG problem is:

You need to understand the meaning of

```<code>self.image.blit(label, self.rect.center)
</code>```

This won't work if you are trying to blit text on the surface which isn't positioned at (0,0). Why? Because you aren't blitting text directly on the display. You are blitting it on the surface. You need to provide coordinates respective to the surface and not to the display.

This worked before as your surface was positioned on the display at (0,0). Now as you have changed the position of your surface to (300,300), self.rect.center is now (350,350). It should be (50,50) as your surface (width,height) is (100,100).

So now keep the BUG True and change that statement to:

```<code>self.image.blit(label, (50,50))
</code>```

If you want better positioning, use:

```<code>text = str(self.counter)
label = self.myfont.render(text, 1, (255,0,0))
text_rect = label.get_rect()
text_rect.center = (50,50)

self.image.blit(label, text_rect)
</code>```

Body:
I am trying to achieve the following using pygame:
printing a changing text part of a sprite and update the sprite every frame.
The sprite is a simple transparent rectangular area surounded by red edges.
At the center of that area a number is printed and that number change over time.
I also want to use the dirty rectangle method.

I haven't managed yet to make it work in my game but I have reproduce the scenario in the following sample (you can run it as is):

import pygame
from pygame.locals import *

class Sprite(pygame.sprite.Sprite):
        def __init__(self, group=None):

            pygame.sprite.Sprite.__init__(self, group)
            self.counter = 0

            self.image = pygame.Surface((100,100)).convert_alpha()
            self.image.fill((0,0,0,0))
            pygame.draw.rect(self.image, (255,0,0), [ (0,0), (100,100) ], 1)
            self.rect = self.image.get_rect()

            self.myfont = pygame.font.SysFont("monospace", 15)
            text = str(self.counter)
            label = self.myfont.render(text, 1, (255,0,0))
            self.image.blit(label, self.rect.center)

        def update(self):
            rect_save = self.rect
            self.image = pygame.Surface((100,100)).convert_alpha()
            self.image.fill((0,0,0,0))
            pygame.draw.rect(self.image, (255,0,0), [ (0,0), (100,100) ], 1)
            self.rect = self.image.get_rect()
            self.rect.x = rect_save[0]
            self.rect.y = rect_save[1]

            text = str(self.counter)
            label = self.myfont.render(text, 1, (255,0,0))

            self.image.blit(label, self.rect.center)

Quit = False

pygame.init()
window = pygame.display.set_mode((640, 480))
render = pygame.sprite.RenderUpdates()

sprite = Sprite(render)
BUG = False
if BUG:
    sprite.rect = (300,300)

while not Quit:
    for event in pygame.event.get():
        if event.type == QUIT:
            Quit = True
        if event.type == KEYDOWN:
            sprite.counter += 1

    background = pygame.Surface( window.get_size() )
    background.fill( (0,0,0) )
    render.clear( window, background )

    render.update()

    dirty = render.draw(window)
    pygame.display.update( dirty )
#end while

pygame.quit()

In the code example I have defined a BUG variable to trigger the problem I encounter.
If I set the BUG to False my sprite is rendered as wanted in the top left corner of the screen with the text updating when hitting a key.
However when I set BUG to True the sprite is rendered at the right position on the screen but the text is not there anymore.

How can I make that second case work as expected ?

Thanks

Note:
the following post didn't help solving my problem
Python pygame writing text in sprite

Body:
Solution of the BUG problem is:

You need to understand the meaning of

self.image.blit(label, self.rect.center)

This won't work if you are trying to blit text on the surface which isn't positioned at (0,0). Why? Because you aren't blitting text directly on the display. You are blitting it on the surface. You need to provide coordinates respective to the surface and not to the display.

This worked before as your surface was positioned on the display at (0,0). Now as you have changed the position of your surface to (300,300), self.rect.center is now (350,350). It should be (50,50) as your surface (width,height) is (100,100).

So now keep the BUG True and change that statement to:

self.image.blit(label, (50,50))

If you want better positioning, use:

text = str(self.counter)
label = self.myfont.render(text, 1, (255,0,0))
text_rect = label.get_rect()
text_rect.center = (50,50)

self.image.blit(label, text_rect)


问:
C# How to use Directory White Spaces into process.arguements?
The program created utilizes a 3rd party tool to generate a log file.

However the arguments provided for the the tool requires various files from Directory locations as part of generating the logs. Therefore the main argument of @"-r C:\test\ftk\ntuser.dat -d C:\System Volume Information\" + restoreFolder.Name + " -p runmru"; would be used to generate the logs.

May someone advise on how to make the arguments of "C:\System Volume Information\" be processed by the system with the white spaces in placed? Thanks!

The codes:

```<code>            Process process = new Process();
            process.StartInfo.FileName = @"C:\test\ftk\ripxp\ripxp.exe";
            process.StartInfo.Arguments = @"-r C:\test\ftk\ntuser.dat -d C:\System Volume Information\" + restoreFolder.Name + " -p runmru";
            process.StartInfo.CreateNoWindow = false;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardError = true;
            process.Start();
</code>```

答:
You really need to use a string.Format along with the Path class:

```<code>process.StartInfo.Arguments = @"-r C:\test\ftk\ntuser.dat -d C:\System Volume Information\" + restoreFolder.Name + " -p runmru"
</code>```

can be rewritten to be a lot cleaner as follows:

```<code>string ntuser = @"C:\test\ftk\ntuser.dat";
var args = Path.Combine(@"C:\System Volume Information\", "restoreFolder.Name");

var outs = string.Format("-r {0} -d {1} -p runmru", ntuser, args);
outs.Dump();
</code>```

Body:
The program created utilizes a 3rd party tool to generate a log file.

However the arguments provided for the the tool requires various files from Directory locations as part of generating the logs. Therefore the main argument of @"-r C:\test\ftk\ntuser.dat -d C:\System Volume Information\" + restoreFolder.Name + " -p runmru"; would be used to generate the logs.

May someone advise on how to make the arguments of "C:\System Volume Information\" be processed by the system with the white spaces in placed? Thanks!

The codes:

            Process process = new Process();
            process.StartInfo.FileName = @"C:\test\ftk\ripxp\ripxp.exe";
            process.StartInfo.Arguments = @"-r C:\test\ftk\ntuser.dat -d C:\System Volume Information\" + restoreFolder.Name + " -p runmru";
            process.StartInfo.CreateNoWindow = false;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardError = true;
            process.Start();

Body:
You really need to use a string.Format along with the Path class:

process.StartInfo.Arguments = @"-r C:\test\ftk\ntuser.dat -d C:\System Volume Information\" + restoreFolder.Name + " -p runmru"

can be rewritten to be a lot cleaner as follows:

string ntuser = @"C:\test\ftk\ntuser.dat";
var args = Path.Combine(@"C:\System Volume Information\", "restoreFolder.Name");

var outs = string.Format("-r {0} -d {1} -p runmru", ntuser, args);
outs.Dump();


问:
CSS Change background color by User
i'm writing a page for a mobile version of a website and i'd like to insert a checkbox with label Dark Theme, when an user check this box change background color (of entire website) to black and text color to white, i found many part of codes in internet but it doesn't works, i don't know why.

For Example i tried this:

#select1:checked ~ div .wrapper{
 background-color:black;
  color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
<input id="select1" name="check1" type="checkbox" />
<label for="select1">Dark Theme</label>
</div></code>```

Can you help me?
Thank you

答:
The only way you can get it through pure CSS is the following snippet:

#select1:checked~div.wrapper {
  background-color: black;
  color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="select1" name="check1" type="checkbox" />
<label for="select1">Dark Theme</label>
<div class="wrapper">

  Some text here
</div></code>```

NOTE: Using JS is the correct way to achieve what you are expecting.

Title: CSS Change background color by User

Body:
i'm writing a page for a mobile version of a website and i'd like to insert a checkbox with label Dark Theme, when an user check this box change background color (of entire website) to black and text color to white, i found many part of codes in internet but it doesn't works, i don't know why.

For Example i tried this:

#select1:checked ~ div .wrapper{
 background-color:black;
  color: white;
}

<input id="select1" name="check1" type="checkbox" />
Dark Theme

Can you help me?
Thank you

Body:
The only way you can get it through pure CSS is the following snippet:

#select1:checked~div.wrapper {
  background-color: black;
  color: white;
}

<input id="select1" name="check1" type="checkbox" />
<label for="select1">Dark Theme</label>
<div class="wrapper">

  Some text here
</div>

NOTE: Using JS is the correct way to achieve what you are expecting.


问:
Why can't I get the data in POST request?
The js file is:

```<code>function pageInit() {
    jQuery("#list2").jqGrid({
        url: '/json.json',
        mtype: 'post',
        datatype: "json",
        colNames: ['ID', 'account', 'password'],
        colModel: [{
            name: 'ID',
            index: 'id',
            width: 60
        }, {
            name: 'account',
            index: 'username',
            width: 110
        }, {
            name: 'password',
            index: 'name asc, username',
            width: 110
        }],
        rowNum: 10,
        rowList: [10, 20, 30],
        pager: '#pager2',
        sortname: 'id',
        sortorder: "desc",
        viewrecords: true,
        caption: "exp",
        jsonReader: {
            root: "rows",
            page: "page",
            total: "total",
            records: "records",
            repeatitems: false,
            id: "0"
        },
        prmNames: {
            rows: 'pageSize',
            sort: null,
            order: null,
            search: null,
            npage: null,
            nd: null
        }
    });
    jQuery("#list2").jqGrid('navGrid', '#pager2', {
        edit: false,
        add: false,
        del: false
    });
}
</code>```

and my controller in springmvc:

```<code>@RequestMapping(value = "/json.json",method = RequestMethod.POST)
@ResponseBody
public void b(HttpServletRequest request, @RequestParam(value = "page",required = false) String page) throws Exception{
    System.out.println(request.getParameterMap().size());
    InputStream inputStream = request.getInputStream();
    String result = IOUtils.toString(inputStream, "UTF-8");
    System.out.println(result);
    System.out.println(page);
    System.out.println(request.getMethod());
    System.out.println(request.getContentType());
}
</code>```

and the println show :

```<code>0
pageSize=10&page=1
null
POST
</code>```

the request headers is:

```<code>Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip, deflate, br
Accept-Language:zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Content-Length:18
Content-Type:application/x-www-form-urlencoded
Cookie:Idea-9d783f23=f3d01b09-52e1-4f55-a692-17f4f2a1bbb0
X-Requested-With:XMLHttpRequest
</code>```

and form data is:

```<code>pageSize:10
page:1
</code>```

web.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         metadata-complete="true" version="3.0">

  <servlet>
    <servlet-name>spring-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
    <async-supported>true</async-supported>

  </servlet>
  <servlet-mapping>
    <servlet-name>spring-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

</web-app>
</code>```

spring-dispatcher-servlet.xml :

```<code><beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <context:component-scan base-package="controller"/>

    <mvc:annotation-driven/>

    <mvc:default-servlet-handler/>

    <bean id="templateResolver" class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".html"/>
        <property name="templateMode" value="HTML5"/>
        <property name="characterEncoding" value="UTF-8"/>
    </bean>

    <bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
        <property name="templateResolver" ref="templateResolver"/>
    </bean>

    <bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
        <property name="templateEngine" ref="templateEngine"/>
        <property name="characterEncoding" value="UTF-8"/>
    </bean>

    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="jsonHttpMessageConverter"/>
            </list>
        </property>
    </bean>

    <bean id="jsonHttpMessageConverter"
          class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>application/json;charset=UTF-8</value>
            </list>
        </property>
    </bean>

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    </bean>
</beans>
</code>```

but if I change the method to "get", It works. Why it happens?

答: well..I fix it. Since my previous project needs to upload a large volume of the picture, then I found this answer at stackoverflow.HttpRequest maximum allowable size in tomcat? Freeman said. and now I delete that new code.and done</p>

Body:
The js file is:

function pageInit() {
    jQuery("#list2").jqGrid({
        url: '/json.json',
        mtype: 'post',
        datatype: "json",
        colNames: ['ID', 'account', 'password'],
        colModel: [{
            name: 'ID',
            index: 'id',
            width: 60
        }, {
            name: 'account',
            index: 'username',
            width: 110
        }, {
            name: 'password',
            index: 'name asc, username',
            width: 110
        }],
        rowNum: 10,
        rowList: [10, 20, 30],
        pager: '#pager2',
        sortname: 'id',
        sortorder: "desc",
        viewrecords: true,
        caption: "exp",
        jsonReader: {
            root: "rows",
            page: "page",
            total: "total",
            records: "records",
            repeatitems: false,
            id: "0"
        },
        prmNames: {
            rows: 'pageSize',
            sort: null,
            order: null,
            search: null,
            npage: null,
            nd: null
        }
    });
    jQuery("#list2").jqGrid('navGrid', '#pager2', {
        edit: false,
        add: false,
        del: false
    });
}

and my controller in springmvc:

@RequestMapping(value = "/json.json",method = RequestMethod.POST)
@ResponseBody
public void b(HttpServletRequest request, @RequestParam(value = "page",required = false) String page) throws Exception{
    System.out.println(request.getParameterMap().size());
    InputStream inputStream = request.getInputStream();
    String result = IOUtils.toString(inputStream, "UTF-8");
    System.out.println(result);
    System.out.println(page);
    System.out.println(request.getMethod());
    System.out.println(request.getContentType());
}

and the println show :

0
pageSize=10&page=1
null
POST

the request headers is:

Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip, deflate, br
Accept-Language:zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Content-Length:18
Content-Type:application/x-www-form-urlencoded
Cookie:Idea-9d783f23=f3d01b09-52e1-4f55-a692-17f4f2a1bbb0
X-Requested-With:XMLHttpRequest

and form data is:

pageSize:10
page:1

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         metadata-complete="true" version="3.0">

  <servlet>
    <servlet-name>spring-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
    <async-supported>true</async-supported>

  </servlet>
  <servlet-mapping>
    <servlet-name>spring-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

</web-app>

spring-dispatcher-servlet.xml :

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <context:component-scan base-package="controller"/>

    <mvc:annotation-driven/>

    <mvc:default-servlet-handler/>

    <bean id="templateResolver" class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".html"/>
        <property name="templateMode" value="HTML5"/>
        <property name="characterEncoding" value="UTF-8"/>
    </bean>

    <bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
        <property name="templateResolver" ref="templateResolver"/>
    </bean>

    <bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
        <property name="templateEngine" ref="templateEngine"/>
        <property name="characterEncoding" value="UTF-8"/>
    </bean>

    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="jsonHttpMessageConverter"/>
            </list>
        </property>
    </bean>

    <bean id="jsonHttpMessageConverter"
          class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>application/json;charset=UTF-8</value>
            </list>
        </property>
    </bean>

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    </bean>
</beans>

but if I change the method to "get", It works. Why it happens?


问:
Easiest way to validate and read an xml file in .net?
What is the easiest/simplest/cleanest way to:

Read an xml file from the filesystem

Validate the xml against an xsd

Read parts of the xml file into variables

Using .net.

答:
Depending on the level of tolerance and error reporting you want to have, you might find the new XML Api introduced in .NET 3.5 to be useful - the classes XDocument, XElement, XAttribute and so on, all from the System.Xml.Linq namespace.

The design of new XML Api was heavily influenced by lessons learned from the older XMLDocument design, and is much more lightweight and easier to use.

OwnerDisplayName: webdtc

OwnerDisplayName: Bevan


Title: Row value as a column

Body:
I have following records

DocNo   PrnOrd  DESCR   ITEMCD  AMT
1          1    D1      16844   43330
1          2    D2      16844
1          7    D7      16844   2166.5
1         21    D21     16844   0.5
1          1    D1        937   58188
1          7    D7        937   2909.4
1         21    D21       937
1         23    D23       937   -0.02

want to present like this

DocNo,ITEMCD,   D1,    D2,     D7, D21,  D23,
1    , 16844,43330,      , 2166.5, 0.5,     ,
1    ,   937,58188,2909.4,       ,    ,-0.02,

DESCR field value as a column and its AMT as a value

Body:
Try as follows:

 DECLARE @cols AS NVARCHAR(MAX),
        @query  AS NVARCHAR(MAX);

    SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.DESCR)
                FROM temp c
                FOR XML PATH(''), TYPE
                ).value('.', 'NVARCHAR(MAX)')
            ,1,1,'')

    set @query = 'SELECT DocNo   ,ITEMCD, ' + @cols + ' from
                (
                    select DocNo ,ITEMCD
                        , AMT
                        , DESCR
                    from temp
               ) x
                pivot
                (
                     max(AMT)
                    for DESCR in (' + @cols + ')
                ) p '

exec (@query)

output:

*-*-------*-------*-------*----*----------*----------*
|1| 937   |58188    |NULL |    |-0.02     |2909.4    |
*-*-------*-------*-------*----*----------*----------*
|1| 16844   |43330  |     |0.5 |    NULL  |2166.5    |
*-*-------*-------*-------*----*----------*----------*


问:
The Program is not recording the first array, set as a null -- Java
I have a code here that creates an array and puts in people's names into it. However, the first array does not get recorded.

```<code>Scanner newscan = new Scanner(System.in);

    System.out.println("How many people in the group?");
    int groupnum = newscan.nextInt();

    String[] people = new String[groupnum];

    System.out.println("Put in the names of the people in the group");
    String name;

    int i = 0;
    do{
        System.out.println("Input Name");
        name = newscan.nextLine();
        people[i] = name;
        i++;
    }while(i<groupnum);
</code>```

The console shows results like this:

```<code>How many people in the group?
5
Put in the names of the people in the group
Input Name
Input Name
John
Input Name
Bob
Input Name
Denis
Input Name
Andrew
</code>```

I have tried using the debugger on IntelliJ, and it shows that whatever value I put in the first array, gets ignored and is set as a "" null value.

I have no idea to approach this problem.
It would be very helpful if you can tell me what part of my code is causing this problem and how to fix it.

答:
Check the Scanner.nextLine() javadoc. It's return line separator from the nextInt() input.
You can just use it before your cycle </p>

```<code>int i = 0;
newscan.nextLine();
do{
    System.out.println("Input Name");
    name = newscan.nextLine();
    people[i] = name;
    i++;
}while(i<groupnum);
</code>```

Body:
I have a code here that creates an array and puts in people's names into it. However, the first array does not get recorded.

Scanner newscan = new Scanner(System.in);

    System.out.println("How many people in the group?");
    int groupnum = newscan.nextInt();

    String[] people = new String[groupnum];

    System.out.println("Put in the names of the people in the group");
    String name;

    int i = 0;
    do{
        System.out.println("Input Name");
        name = newscan.nextLine();
        people[i] = name;
        i++;
    }while(i<groupnum);

The console shows results like this:

How many people in the group?
5
Put in the names of the people in the group
Input Name
Input Name
John
Input Name
Bob
Input Name
Denis
Input Name
Andrew

I have tried using the debugger on IntelliJ, and it shows that whatever value I put in the first array, gets ignored and is set as a "" null value.

I have no idea to approach this problem.
It would be very helpful if you can tell me what part of my code is causing this problem and how to fix it.

Body:
Check the Scanner.nextLine() javadoc. It's return line separator from the nextInt() input.
You can just use it before your cycle

int i = 0;
newscan.nextLine();
do{
    System.out.println("Input Name");
    name = newscan.nextLine();
    people[i] = name;
    i++;
}while(i<groupnum);