问:
Merging strings together based on command line arguments.
I'm trying to write a program in C to merge 2 string together in two diffrent ways based on the given command line argument.

'-i' to merge the string alternating, like this

combine_strings –i
Please enter a string of maximum 30 characters: abcde
Please enter a string of maximum 30 characters: 1234567
The combined string is: a1b2c3d4e567

'-w' to concate the 2 strings together, and insert a '*' between each character of the string, like this

combine_strings -w
Please enter a string of maximum 30 characters: abcde
Please enter a string of maximum 30 characters: 1234567
The combined string is: abcde*1*2*3*4*5*6*7

This is what I got so far.

```<code>#include<stdio.h>
#include<string.h>
#include<memory.h>

void alt_merge(char *string1,char *string2,char *stringfinal){

while (*string1 != '\0' && *string2 != '\0')
{
    *stringfinal++= *string1++;
*stringfinal++ = *string2++;
}
while (*string1 != '\0')
    *stringfinal++=*string1++;
while (*string2 != '\0')
    *stringfinal++ = *string2++;
*stringfinal='\0';
}

void concate_star(char *string1,char *string2,char *stringfinal){

strcpy(stringfinal,strcat(string1,string2));
}

int main(int argc,char *argv[]){
char *string1[30+1];
char *string2[30+1];
char *stringfinal=malloc(strlen(string1)+strlen(string2)+1);

if(argv[1]=='-i'){
        printf("Please enter a string of maximum 30 characters: ");
        scanf("%s",&string1);
        printf("Please enter a string of maximum 30 characters: ");
        scanf("%s",&string2);

        alt_merge(string1,string2,stringfinal);

        printf("The combined string is: %s",stringfinal);
}
else if(argv[1]=='-w'){
        printf("Please enter a string of maximum 30 characters: ");
        scanf("%s",&string1);
        printf("Please enter a string of maximum 30 characters: ");
        scanf("%s",&string2);

        concate_star(*string1,*string2,*stringfinal);

        printf("The combined string is: %s",stringfinal);
}

return 0;
}
</code>```

I getting these error messages.

```<code>jdoodle.c: In function 'main':
jdoodle.c:27:23: warning: implicit declaration of function 'malloc' [-Wimplicit-function-declaration]
     char *stringfinal=malloc(strlen(string1)+strlen(string2)+1);
                       ^~~~~~
jdoodle.c:27:23: warning: incompatible implicit declaration of built-in function 'malloc'
jdoodle.c:27:23: note: include '<stdlib.h>' or provide a declaration of 'malloc'
jdoodle.c:27:37: warning: passing argument 1 of 'strlen' from incompatible pointer type [-Wincompatible-pointer-types]
     char *stringfinal=malloc(strlen(string1)+strlen(string2)+1);
                                     ^~~~~~~
In file included from jdoodle.c:2:0:
/usr/include/string.h:384:15: note: expected 'const char *' but argument is of type 'char **'
 extern size_t strlen (const char *__s)
               ^~~~~~
jdoodle.c:27:53: warning: passing argument 1 of 'strlen' from incompatible pointer type [-Wincompatible-pointer-types]
     char *stringfinal=malloc(strlen(string1)+strlen(string2)+1);
                                                     ^~~~~~~
In file included from jdoodle.c:2:0:
/usr/include/string.h:384:15: note: expected 'const char *' but argument is of type 'char **'
 extern size_t strlen (const char *__s)
               ^~~~~~
jdoodle.c:29:17: warning: multi-character character constant [-Wmultichar]
     if(argv[1]=='-i'){
                 ^~~~
jdoodle.c:29:15: warning: comparison between pointer and integer
     if(argv[1]=='-i'){
               ^~
jdoodle.c:35:23: warning: passing argument 1 of 'alt_merge' from incompatible pointer type [-Wincompatible-pointer-types]
             alt_merge(string1,string2,stringfinal);
                       ^~~~~~~
jdoodle.c:5:6: note: expected 'char *' but argument is of type 'char **'
 void alt_merge(char *string1,char *string2,char *stringfinal){
      ^~~~~~~~~
jdoodle.c:35:31: warning: passing argument 2 of 'alt_merge' from incompatible pointer type [-Wincompatible-pointer-types]
             alt_merge(string1,string2,stringfinal);
                               ^~~~~~~
jdoodle.c:5:6: note: expected 'char *' but argument is of type 'char **'
 void alt_merge(char *string1,char *string2,char *stringfinal){
      ^~~~~~~~~
jdoodle.c:39:22: warning: multi-character character constant [-Wmultichar]
     else if(argv[1]=='-w'){
                      ^~~~
jdoodle.c:39:20: warning: comparison between pointer and integer
     else if(argv[1]=='-w'){
                    ^~
jdoodle.c:45:44: warning: passing argument 3 of 'concate_star' makes pointer from integer without a cast [-Wint-conversion]
             concate_star(*string1,*string2,*stringfinal);
                                            ^
jdoodle.c:19:6: note: expected 'char *' but argument is of type 'char'
 void concate_star(char *string1,char *string2,char *stringfinal){
      ^~~~~~~~~~~~
</code>```

I'm new to programming, so any help and advice is appreciated.

答:
Two problems, you didn't include stdlib.h where there is the declaration of the function malloc().

Also you are passing a wrong parameter to the strlen() but you passed char**. Same in other functions too. You had parameter mismatch.

```<code>char *string1[30+1];
char *string2[30+1];
</code>```

You wanted

```<code>char string1[30+1];
char string2[30+1];
</code>```

Also you should use strcmp when you are comparing "-i" with argv[1].

Now argv is basically array of char*. And you are basically comparing a null terminated char array with (string) with "-i". (Not '-i').

Also notice one interesting thing,

compiler says

```<code>jdoodle.c:29:15: warning: comparison between pointer and integer
     if(argv[1]=='-i'){
               ^~
</code>```

An ordinary character literal that contains more than one c-char is a
  multicharacter literal . A multicharacter literal has type int and
  implementation-deﬁned value.

'-i' is a multicharacter literal. This has type int that's why the warning comparison between pointer and int.

Also there is another thing you should clearly know, when you pass an array to a function it decays into pointer to the first element of the array.

char *s[100] decays to char** because the content of the array is char* a pointer to it would be char**.

Body:
I'm trying to write a program in C to merge 2 string together in two diffrent ways based on the given command line argument.

'-i' to merge the string alternating, like this

combine_strings –i
Please enter a string of maximum 30 characters: abcde
Please enter a string of maximum 30 characters: 1234567
The combined string is: a1b2c3d4e567

'-w' to concate the 2 strings together, and insert a '*' between each character of the string, like this

combine_strings -w
Please enter a string of maximum 30 characters: abcde
Please enter a string of maximum 30 characters: 1234567
The combined string is: abcde*1*2*3*4*5*6*7

This is what I got so far.

#include<stdio.h>
#include<string.h>
#include<memory.h>

void alt_merge(char *string1,char *string2,char *stringfinal){

while (*string1 != '\0' && *string2 != '\0')
{
    *stringfinal++= *string1++;
*stringfinal++ = *string2++;
}
while (*string1 != '\0')
    *stringfinal++=*string1++;
while (*string2 != '\0')
    *stringfinal++ = *string2++;
*stringfinal='\0';
}

void concate_star(char *string1,char *string2,char *stringfinal){

strcpy(stringfinal,strcat(string1,string2));
}

int main(int argc,char *argv[]){
char *string1[30+1];
char *string2[30+1];
char *stringfinal=malloc(strlen(string1)+strlen(string2)+1);

if(argv[1]=='-i'){
        printf("Please enter a string of maximum 30 characters: ");
        scanf("%s",&string1);
        printf("Please enter a string of maximum 30 characters: ");
        scanf("%s",&string2);

        alt_merge(string1,string2,stringfinal);

        printf("The combined string is: %s",stringfinal);
}
else if(argv[1]=='-w'){
        printf("Please enter a string of maximum 30 characters: ");
        scanf("%s",&string1);
        printf("Please enter a string of maximum 30 characters: ");
        scanf("%s",&string2);

        concate_star(*string1,*string2,*stringfinal);

        printf("The combined string is: %s",stringfinal);
}

return 0;
}

I getting these error messages.

jdoodle.c: In function 'main':
jdoodle.c:27:23: warning: implicit declaration of function 'malloc' [-Wimplicit-function-declaration]
     char *stringfinal=malloc(strlen(string1)+strlen(string2)+1);
                       ^~~~~~
jdoodle.c:27:23: warning: incompatible implicit declaration of built-in function 'malloc'
jdoodle.c:27:23: note: include '<stdlib.h>' or provide a declaration of 'malloc'
jdoodle.c:27:37: warning: passing argument 1 of 'strlen' from incompatible pointer type [-Wincompatible-pointer-types]
     char *stringfinal=malloc(strlen(string1)+strlen(string2)+1);
                                     ^~~~~~~
In file included from jdoodle.c:2:0:
/usr/include/string.h:384:15: note: expected 'const char *' but argument is of type 'char **'
 extern size_t strlen (const char *__s)
               ^~~~~~
jdoodle.c:27:53: warning: passing argument 1 of 'strlen' from incompatible pointer type [-Wincompatible-pointer-types]
     char *stringfinal=malloc(strlen(string1)+strlen(string2)+1);
                                                     ^~~~~~~
In file included from jdoodle.c:2:0:
/usr/include/string.h:384:15: note: expected 'const char *' but argument is of type 'char **'
 extern size_t strlen (const char *__s)
               ^~~~~~
jdoodle.c:29:17: warning: multi-character character constant [-Wmultichar]
     if(argv[1]=='-i'){
                 ^~~~
jdoodle.c:29:15: warning: comparison between pointer and integer
     if(argv[1]=='-i'){
               ^~
jdoodle.c:35:23: warning: passing argument 1 of 'alt_merge' from incompatible pointer type [-Wincompatible-pointer-types]
             alt_merge(string1,string2,stringfinal);
                       ^~~~~~~
jdoodle.c:5:6: note: expected 'char *' but argument is of type 'char **'
 void alt_merge(char *string1,char *string2,char *stringfinal){
      ^~~~~~~~~
jdoodle.c:35:31: warning: passing argument 2 of 'alt_merge' from incompatible pointer type [-Wincompatible-pointer-types]
             alt_merge(string1,string2,stringfinal);
                               ^~~~~~~
jdoodle.c:5:6: note: expected 'char *' but argument is of type 'char **'
 void alt_merge(char *string1,char *string2,char *stringfinal){
      ^~~~~~~~~
jdoodle.c:39:22: warning: multi-character character constant [-Wmultichar]
     else if(argv[1]=='-w'){
                      ^~~~
jdoodle.c:39:20: warning: comparison between pointer and integer
     else if(argv[1]=='-w'){
                    ^~
jdoodle.c:45:44: warning: passing argument 3 of 'concate_star' makes pointer from integer without a cast [-Wint-conversion]
             concate_star(*string1,*string2,*stringfinal);
                                            ^
jdoodle.c:19:6: note: expected 'char *' but argument is of type 'char'
 void concate_star(char *string1,char *string2,char *stringfinal){
      ^~~~~~~~~~~~

I'm new to programming, so any help and advice is appreciated.

Body:
Two problems, you didn't include stdlib.h where there is the declaration of the function malloc().

Also you are passing a wrong parameter to the strlen() but you passed char**. Same in other functions too. You had parameter mismatch.

char *string1[30+1];
char *string2[30+1];

You wanted

char string1[30+1];
char string2[30+1];

Also you should use strcmp when you are comparing "-i" with argv[1].

Now argv is basically array of char*. And you are basically comparing a null terminated char array with (string) with "-i". (Not '-i').

Also notice one interesting thing,

compiler says

jdoodle.c:29:15: warning: comparison between pointer and integer
     if(argv[1]=='-i'){
               ^~

An ordinary character literal that contains more than one c-char is a
  multicharacter literal . A multicharacter literal has type int and
  implementation-deﬁned value.

'-i' is a multicharacter literal. This has type int that's why the warning comparison between pointer and int.

Also there is another thing you should clearly know, when you pass an array to a function it decays into pointer to the first element of the array.

char *s[100] decays to char** because the content of the array is char* a pointer to it would be char**.


来源: stackexchange

问:
Execute process in background, without printing "Done", and get PID
This seems like a pretty trivial thing to do, but I'm very stuck.

To execute something in the background, use &:

```<code>>>> sleep 5 &
[1] 21763
>>> #hit enter
[1]+  Done                    sleep 5
</code>```

But having a bashrc-sourced background script output job information is pretty frustrating, so you can do this to fix it:

```<code>>>> (sleep 5 &)
</code>```

OK, so now I want to get the PID of sleep for wait or kill. Unfortunately its running in a subshell so the typical $! method doesn't work:

```<code>>>> echo $!
21763
>>> (sleep 5 &)
>>> echo $!
21763 #hasn't changed
</code>```

So I thought, maybe I could get the subshell to print its PID in this way:

```<code>>>> sleep 5 & echo $!
[1] 21803 #annoying job-start message (stderr)
21803 #from the echo
</code>```

But now when I throw that in the subshell no matter how I try to capture stdout of the subshell, it appears to block until sleep has finished.

```<code>>>> pid=$(sleep 5 & echo $!)
</code>```

How can I run something in the background, get its PID and stop it from printing job information and "Done"?

答:
I found a great way, no need sub-shell, will keep the parent-child relationship.
Since: [1] 21763 and [1]+  Done sleep 5 are all stderr, which is &2.
We can redirect &2 to /dev/null, here is code:

```<code>exec 7>&2 2>/dev/null # Here backup 2 to 7, and redirect 2 to /dev/null
sleep 5
wait
exec 2>&7 7>&- # here restore 7 to 2, and delete 7.
</code>```

See: Using exec

ContentLicense: CC BY-SA 3.0

Body:
This seems like a pretty trivial thing to do, but I'm very stuck.

To execute something in the background, use &:

>>> sleep 5 &
[1] 21763
>>> #hit enter
[1]+  Done                    sleep 5

But having a bashrc-sourced background script output job information is pretty frustrating, so you can do this to fix it:

>>> (sleep 5 &)

OK, so now I want to get the PID of sleep for wait or kill. Unfortunately its running in a subshell so the typical $! method doesn't work:

>>> echo $!
21763
>>> (sleep 5 &)
>>> echo $!
21763 #hasn't changed

So I thought, maybe I could get the subshell to print its PID in this way:

>>> sleep 5 & echo $!
[1] 21803 #annoying job-start message (stderr)
21803 #from the echo

But now when I throw that in the subshell no matter how I try to capture stdout of the subshell, it appears to block until sleep has finished.

>>> pid=$(sleep 5 & echo $!)

How can I run something in the background, get its PID and stop it from printing job information and "Done"?

Body:
I found a great way, no need sub-shell, will keep the parent-child relationship.
Since: [1] 21763 and [1]+  Done sleep 5 are all stderr, which is &2.
We can redirect &2 to /dev/null, here is code:

exec 7>&2 2>/dev/null # Here backup 2 to 7, and redirect 2 to /dev/null
sleep 5
wait
exec 2>&7 7>&- # here restore 7 to 2, and delete 7.

See: Using exec


问:
testing a component with complex angular components nested inside using PageObjects
Our Application has components which consume components with consume components of varying complexity.  So i just want the input on the page, to validate when an object is set that the text is correct.  The issue is that it is one of these subcomponents.

My colleague told me that there is 2 ways to do this, The first is to use Page Objects, and Chaining annotation to find it on my page, and then find the next id etc until my input is found.  It requires me to look through another teams' Component Markup to narrow it down to the input i want to leverage.  I dont believe I should have to go into another component definition, or a definition of a definition to get the appropriate chain to get this arbitrary input.  It starts to create issues where if a lateral team creates changes unbeknownst to me, my PO will be broken.

The other option my friend asked was to use fixture.query to find the component.  This would be as simple as:

```<code>fixture.query((el)=> el.attribute["id"] == "description",
              (comp){
                expect(comp.value, value);
              });`
</code>```

Using Query looks at the markup but then will automatically componentize it as the appropriate SubComponent.  In this case, comp.value is the value stored in the HTML.  So, if i did something like:

```<code>fixture.update((MainComponent comp) {
  comp.myinput.value = new Foo();
});
</code>```

Then I am setting and getting this programmatically, so i am a bit unsure if it properly would reflect what is on the screen.

Whats the best course of action?  It seems PO would be better, but im not sure if there is a way around having to deep query for input boxes outside of the component i am testing.

Thanks

答:
I don't think I have a definitive answer for you but I can tell you how we do it at Google. For pretty much any component we provide the page object alongside the component. This is twofold it is for testing that widget, and also so we can have this as a shareable resource for other tests.

For leaf widgets the page objects are a little less fleshed out and are really just there for the local test. For components that are shared heavily the page object is a bit more flushed out for reusability. Without this much of the API for the widget (html, css, etc) we would need to consider public and changes to them would be very hard (person responsible for making the public breaking change needs to fix all associated code.) With it we can have a contract to only support the page object API and html structure changes are not considered breaking changes. At times we have even gone so far as to have two page objects for a widget. One for the local test, and one to share. Sometimes the API you want to expose for a local test is much more than you want people to use themselves.

We can then compose these page objects into higher level page objects that represent the widget. Good page objects support a higher level of abstraction for that widget. For example a calendar widget would let you go to the next/previous month, get the current selected date, etc. rather than directly exposing the buttons/inputs that accomplish those actions.

We plan to expose these page objects for angular_components eventually, but we are currently working on how to expose these. Our internal package structure is different than what we have externally. We have many packages per individual widget (page_objects, examples, widget itself) and we need to reconcile this externally before we expose them.

Here is an example:

```<code>import 'package:pageloader/objects.dart';
import 'material_button_po.dart';

/// Webdriver page object for `material-yes-no-buttons` component.
@EnsureTag('material-yes-no-buttons')
class MaterialYesNoButtonsPO {
  @ByClass('btn-yes')
  @optional
  MaterialButtonPO yesButton;

  @ByClass('btn-no')
  @optional
  MaterialButtonPO noButton;
}
</code>```

Body:
Our Application has components which consume components with consume components of varying complexity.  So i just want the input on the page, to validate when an object is set that the text is correct.  The issue is that it is one of these subcomponents.

My colleague told me that there is 2 ways to do this, The first is to use Page Objects, and Chaining annotation to find it on my page, and then find the next id etc until my input is found.  It requires me to look through another teams' Component Markup to narrow it down to the input i want to leverage.  I dont believe I should have to go into another component definition, or a definition of a definition to get the appropriate chain to get this arbitrary input.  It starts to create issues where if a lateral team creates changes unbeknownst to me, my PO will be broken.

The other option my friend asked was to use fixture.query to find the component.  This would be as simple as:

fixture.query((el)=> el.attribute["id"] == "description",
              (comp){
                expect(comp.value, value);
              });`

Using Query looks at the markup but then will automatically componentize it as the appropriate SubComponent.  In this case, comp.value is the value stored in the HTML.  So, if i did something like:

fixture.update((MainComponent comp) {
  comp.myinput.value = new Foo();
});

Then I am setting and getting this programmatically, so i am a bit unsure if it properly would reflect what is on the screen.

Whats the best course of action?  It seems PO would be better, but im not sure if there is a way around having to deep query for input boxes outside of the component i am testing.

Thanks

Body:
I don't think I have a definitive answer for you but I can tell you how we do it at Google. For pretty much any component we provide the page object alongside the component. This is twofold it is for testing that widget, and also so we can have this as a shareable resource for other tests.

For leaf widgets the page objects are a little less fleshed out and are really just there for the local test. For components that are shared heavily the page object is a bit more flushed out for reusability. Without this much of the API for the widget (html, css, etc) we would need to consider public and changes to them would be very hard (person responsible for making the public breaking change needs to fix all associated code.) With it we can have a contract to only support the page object API and html structure changes are not considered breaking changes. At times we have even gone so far as to have two page objects for a widget. One for the local test, and one to share. Sometimes the API you want to expose for a local test is much more than you want people to use themselves.

We can then compose these page objects into higher level page objects that represent the widget. Good page objects support a higher level of abstraction for that widget. For example a calendar widget would let you go to the next/previous month, get the current selected date, etc. rather than directly exposing the buttons/inputs that accomplish those actions.

We plan to expose these page objects for angular_components eventually, but we are currently working on how to expose these. Our internal package structure is different than what we have externally. We have many packages per individual widget (page_objects, examples, widget itself) and we need to reconcile this externally before we expose them.

Here is an example:

import 'package:pageloader/objects.dart';
import 'material_button_po.dart';

/// Webdriver page object for `material-yes-no-buttons` component.
@EnsureTag('material-yes-no-buttons')
class MaterialYesNoButtonsPO {
  @ByClass('btn-yes')
  @optional
  MaterialButtonPO yesButton;

  @ByClass('btn-no')
  @optional
  MaterialButtonPO noButton;
}


问:
Java- Sending user input to a server

I am simulating a simple chat room by creating a client and server relationship. I'm just using the Netbeans IDE to run this. When the user presses enter, whatever they typed into the IDE console is sent to the server and then echoed back.

```<code>console = new BufferedReader(new InputStreamReader(System.in));

while (thread != null) {
    try {
        streamOut.writeUTF(console.readLine());
        streamOut.flush();
    } catch(IOException ioe){
        System.out.println("Sending error: " + ioe.getMessage());
        stop();
    }
}
</code>```

I am trying to create a login/register system where the user is asked to enter username and password. I want the program to pause execution until the enter key is pressed. What I currently have is cutting off the first character from what is entered for username

```<code>System.out.println("Type 1 if you are an existing user \nType 2 if you want to register");
System.in.read();
System.out.println("Username:");
System.in.read();
System.out.println("Password:");
</code>```

Sample output

```<code>Connected: Socket[addr=/127.0.0.1,port=10233,localport=52932]
Type 1 if you are an existing user
Type 2 if you want to register
2
Username:
foo
Password:
52932: oo
bar
52932: bar
</code>```

答:
I would do this with a BufferedReader.

Something like this:

```<code>BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Username: ");
String username = reader.readLine();
System.out.print("Password: ");
String password = reader.readLine();
</code>```

Please note, it is bad practice to send passwords in plain text and to store them in String objects. An attacker would be able to sniff the plain text username and password without much hassle and there is a chance that the String's data could be read before it is destroyed.

Title: Java- Sending user input to a server

Body:
I am simulating a simple chat room by creating a client and server relationship. I'm just using the Netbeans IDE to run this. When the user presses enter, whatever they typed into the IDE console is sent to the server and then echoed back.

console = new BufferedReader(new InputStreamReader(System.in));

while (thread != null) {
    try {
        streamOut.writeUTF(console.readLine());
        streamOut.flush();
    } catch(IOException ioe){
        System.out.println("Sending error: " + ioe.getMessage());
        stop();
    }
}

I am trying to create a login/register system where the user is asked to enter username and password. I want the program to pause execution until the enter key is pressed. What I currently have is cutting off the first character from what is entered for username

System.out.println("Type 1 if you are an existing user \nType 2 if you want to register");
System.in.read();
System.out.println("Username:");
System.in.read();
System.out.println("Password:");

Sample output

Connected: Socket[addr=/127.0.0.1,port=10233,localport=52932]
Type 1 if you are an existing user
Type 2 if you want to register
2
Username:
foo
Password:
52932: oo
bar
52932: bar

Body:
I would do this with a BufferedReader.

Something like this:

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Username: ");
String username = reader.readLine();
System.out.print("Password: ");
String password = reader.readLine();

Please note, it is bad practice to send passwords in plain text and to store them in String objects. An attacker would be able to sniff the plain text username and password without much hassle and there is a chance that the String's data could be read before it is destroyed.


问:
That A-Ha Moment for Understanding OO Design in C#
I've been studying C# for a couple of years, reading voraciously, even taking a few C# data access courses from Microsoft.  I've also been reading books on OOP.  I'm coding a web-based database application at work.  While my job title is not "programmer", I'm fortunate enough to be able to work on this as a side project.  I coded in Basic in the early 80's and was even good at utilizing pokes and peeks to manipulate the Apple ][ + and the TRS-80 to astound and amaze my friends.  But that was a very linear approach to coding.

All this being said, something is just not clicking with me.  I haven't had that a-ha moment with either C# or OOP that gives me the ability to sit down, open up VS2008, and start coding.  I have to study other people's code so much that it simply seems like I'm not doing anything on my own.  I'm getting discouraged.

It's not like I'm not capable of it.  I picked up t-sql really quickly.  Someone can tell me what information they want out of the database and I can code out the tsql in a matter of a few minutes to give them what they want.  SQL is something that I get.  This isn't happening for me with OOP or C#.  Granted, C# is inherently more complex, but at some point it has to click.  Right?

I read over stackoverflow and I'm overwhelmed at how infinitely smart you all are.

What was it for you that made it click?

Edited to add:
A lot of the answers here were outstanding.  However, one in particular seemed to have risen to the top and that's the one I marked as the "answer".  I also hate not marking my questions with the answer.

答:
First question: how many hours are you coding per week?

Second Question: who do you know in real life who DOES get it?  Go talk to them!!!

...

Object oriented programming is a way of programming that organizes and minimizes repeating yourself.  This makes for less code, and easier to alter code (because everything is only on one spot).

You are having problems with it, so I can assume you aren't grokking the need for inheritance.  Inheritance is a way to reduce repeat code.  And the other main part of OOP is classes.  The point of classes is to group things in ways that keeps them nicely organized, and also keeps them encapsulated to reduce coupling (thus making changing code easier!)

That's pretty much all there is too it.

Now go out and program stuff 24/7 and find anyone in real life who really understands this stuff and talk their ear off.

Good luck.

OwnerDisplayName: GregD

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: GregD

OwnerDisplayName: GordonG


问:
How do I pull from within a nested tag with javascript?
Obviously, I'm new to Javascript, and I'm sure that my time with it will be shortlived; this is just for a small project at work. I would really appreciate it if someone would help me figure this out.

I'm trying to set up a page that displays data from an external .xml file, of which I have absolutely no control. It is set up just like this:

```<code><lab id="1" name="A" inUse="14" offline="1" available="16">
</lab>
<lab id="2" name="B" inUse="11" offline="9" available="7">
   <client id="x" status="available" mac="#" ip="#" name="COMPUTER1" />
   <client id="y" status="available" mac="#" ip="#" name="COMPUTER2" />
</lab>
</code>```

I am displaying the data with a table using the following code:

```<code><%
    try
    {
        URL url = new URL("http://clstats.cc.nd.edu/public/xml-client.jsp");
        InputStream input = url.openStream();
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document XMLInfo = builder.parse(input);

        NodeList labs = XMLInfo.getElementsByTagName("lab");

        int length = labs.getLength();
        int i;
        for (i = 0; i < length; i++)
        {

           Node current = labs.item(i);
           String labName = current.getAttributes().getNamedItem("name").getTextContent();
           String available = current.getAttributes().getNamedItem("available").getTextContent();
           String offline = current.getAttributes().getNamedItem("offline").getTextContent();
           String inUse = current.getAttributes().getNamedItem("inUse").getTextContent();
            //Alternate the row colors
            if( (i % 2) == 0)
            {
                  %>
                      <tr style="background:url(#);">
                  <%
             }
             else
             {
                 %>
                 <tr style="background:url(#);">
                 <%
              }
              %>
              <td><%= labName %></td>
              <td><%= available %></td>
                          <td><%= offline %></td>
              <td><%= inUse %></td>
              </tr>
              </td>
               <%
        }
    }
    catch(Exception e){
    }

%>
</code>```

I am having no trouble displaying information from the "lab" tag, but I'd like to only display data from within a particular lab, let's say lab id=2. Is there a way to display attributes from the "client" tags from under a single, particular "lab" tag?

Thanks, I hope I explained the problem well enough. As you can see, I'm pretty much a noob, and any help would be much appreciated.

Intended Result:

```<code><table>
<tr>
<td>Name</td>
<td>Status</td>
</tr>
<tr>
<td>COMPUTER1</td>
<td>Available</td>
</tr>
<tr>
<td>COMPUTER2</td>
<td>AVAILABLE</td>
</tr>
</table>
</code>```

答:
That looks like java to me in which case I think you could use Xpath like this:

```<code>InputStream input = url.openStream();
   DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
   Document XMLInfo = builder.parse(input);

  XPath xPath = XPathFactory.newInstance().newXPath();
  Node myNode = xPath.evaluate("/lab[@id='2']", XMLInfo, XPathConstants.NODESET);
</code>```

That should get you the individual node.

Body:
Obviously, I'm new to Javascript, and I'm sure that my time with it will be shortlived; this is just for a small project at work. I would really appreciate it if someone would help me figure this out.

I'm trying to set up a page that displays data from an external .xml file, of which I have absolutely no control. It is set up just like this:

<lab id="1" name="A" inUse="14" offline="1" available="16">
</lab>
<lab id="2" name="B" inUse="11" offline="9" available="7">
   <client id="x" status="available" mac="#" ip="#" name="COMPUTER1" />
   <client id="y" status="available" mac="#" ip="#" name="COMPUTER2" />
</lab>

I am displaying the data with a table using the following code:

<%
    try
    {
        URL url = new URL("http://clstats.cc.nd.edu/public/xml-client.jsp");
        InputStream input = url.openStream();
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document XMLInfo = builder.parse(input);

        NodeList labs = XMLInfo.getElementsByTagName("lab");

        int length = labs.getLength();
        int i;
        for (i = 0; i < length; i++)
        {

           Node current = labs.item(i);
           String labName = current.getAttributes().getNamedItem("name").getTextContent();
           String available = current.getAttributes().getNamedItem("available").getTextContent();
           String offline = current.getAttributes().getNamedItem("offline").getTextContent();
           String inUse = current.getAttributes().getNamedItem("inUse").getTextContent();
            //Alternate the row colors
            if( (i % 2) == 0)
            {
                  %>

                  <%
             }
             else
             {
                 %>

                 <%
              }
              %>
              <%= labName %>
              <%= available %>
                          <%= offline %>
              <%= inUse %>

               <%
        }
    }
    catch(Exception e){
    }

%>

I am having no trouble displaying information from the "lab" tag, but I'd like to only display data from within a particular lab, let's say lab id=2. Is there a way to display attributes from the "client" tags from under a single, particular "lab" tag?

Thanks, I hope I explained the problem well enough. As you can see, I'm pretty much a noob, and any help would be much appreciated.

Intended Result:

Name
Status

COMPUTER1
Available

COMPUTER2
AVAILABLE

Body:
That looks like java to me in which case I think you could use Xpath like this:

InputStream input = url.openStream();
   DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
   Document XMLInfo = builder.parse(input);

  XPath xPath = XPathFactory.newInstance().newXPath();
  Node myNode = xPath.evaluate("/lab[@id='2']", XMLInfo, XPathConstants.NODESET);

That should get you the individual node.


问:
What is the time complexity of this generation algorithm?
I have an number generation algo and i want to know what is its time complexity?

it generates all combinations up to length n.

below is the code snipet

```<code>void generate_N_Numbers(int n){
    int len = 0;
    int alphaLen = 2;
    int  *letters  = malloc(n * sizeof(int));

    uint64_t outerLoopCounter = 0,innerLoopCounter1 = 0,innerLoopCounter2 = 0,
    innerLoopCounter3 = 0,innerLoopCounter4 = 0,totalLoopCounter = 0;

    for (len=1; len<=n; len++)
    {
        outerLoopCounter++;
        int i;
        int stride = len+1;
        int bufLen = stride * alphaLen * alphaLen;

            if (len == 1)
            continue;

        for (i=len-2; i<bufLen; i+=stride)
            innerLoopCounter1++;

        if (len == 2)
            continue;

        for (i = 0; i < len;i++){
        letters[i] = 0;
        innerLoopCounter2++;
        }

    i = len-3;
    do {
        int  j;
        innerLoopCounter3++;

        letters[i]++;

        if (letters[i] >= alphaLen)
        letters[i] = 0;

        for (j=i;j<bufLen;j+=stride){
        innerLoopCounter4++;
        }

        if (letters[i] != 0) {
        i = len - 3;
        continue;
        }

        i--;

        if (i < 0)
        break;

    } while(1);

    }

}
</code>```

Here is the link to this code .
https://ideone.com/HxzDGv

and here is the link to result of algorithm for inputs 1 to 30.
https://pastebin.com/LwavAff1

I am guessing its complexity is O(n2) but still i am not sure about this .
and this loop generates number faster than loop which has time complexity of O(n) somehow.

答:
Yes, you are correct in assuming that the running time will be O(n^2). The most costly portions of your code to consider are those within two loops; all other sections are insignificant, and take O(1) time.

Your outer for loop will run n times, and each of the inner for loops will run O(n) times.

Your do-while loop will execute less than n times, and the for loop inside of it will execute at most n times.

Note that all operations within the innermost for loops are O(1).

To summarize this information, n*(n*1+n*1) + n*n*1 operations are required, which is O(n^2)

Note: your code is very confusing, and I made no attempt to follow the logic behind what you are doing; I just wanted to demonstrate basic complexity analysis. I would recommend taking a look at std::next_permutation.

Body:
I have an number generation algo and i want to know what is its time complexity?

it generates all combinations up to length n.

below is the code snipet

void generate_N_Numbers(int n){
    int len = 0;
    int alphaLen = 2;
    int  *letters  = malloc(n * sizeof(int));

    uint64_t outerLoopCounter = 0,innerLoopCounter1 = 0,innerLoopCounter2 = 0,
    innerLoopCounter3 = 0,innerLoopCounter4 = 0,totalLoopCounter = 0;

    for (len=1; len<=n; len++)
    {
        outerLoopCounter++;
        int i;
        int stride = len+1;
        int bufLen = stride * alphaLen * alphaLen;

            if (len == 1)
            continue;

        for (i=len-2; i<bufLen; i+=stride)
            innerLoopCounter1++;

        if (len == 2)
            continue;

        for (i = 0; i < len;i++){
        letters[i] = 0;
        innerLoopCounter2++;
        }

    i = len-3;
    do {
        int  j;
        innerLoopCounter3++;

        letters[i]++;

        if (letters[i] >= alphaLen)
        letters[i] = 0;

        for (j=i;j<bufLen;j+=stride){
        innerLoopCounter4++;
        }

        if (letters[i] != 0) {
        i = len - 3;
        continue;
        }

        i--;

        if (i < 0)
        break;

    } while(1);

    }

}

Here is the link to this code .
https://ideone.com/HxzDGv

and here is the link to result of algorithm for inputs 1 to 30.
https://pastebin.com/LwavAff1

I am guessing its complexity is O(n2) but still i am not sure about this .
and this loop generates number faster than loop which has time complexity of O(n) somehow.


问:
Database image to background (windows form)
Hi i am new to windows form programming and having some trouble coding.

What i am trying to do is replace the current background of the windows form with another background that has been stored in my database.

<img src="https://i.stack.imgur.com/OuirY.png" alt="enter image description here">

```<code> cmd = new SqlCommand("select Background from Employee where EmployeeName='" + label2.Text + "'", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        if (ds.Tables[0].Rows.Count > 0)
        {
            MemoryStream ms = new MemoryStream((byte[])ds.Tables[0].Rows[0]["Background"]);
            pictureBox1.Image = new Bitmap(ms);
</code>```

These are the codes that I tried using a picturebox as the background, But unable to do so with the background. Any form of help is much appreciated

答:
this.BackgroundImage = new Bitmap(ms);

Note: This will present the image using the BackgroundImageLayout property setting (eg. - None, Center, Stretch, etc.).

Body:
Hi i am new to windows form programming and having some trouble coding.

What i am trying to do is replace the current background of the windows form with another background that has been stored in my database.

<img src="https://i.stack.imgur.com/OuirY.png" alt="enter image description here">

 cmd = new SqlCommand("select Background from Employee where EmployeeName='" + label2.Text + "'", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        if (ds.Tables[0].Rows.Count > 0)
        {
            MemoryStream ms = new MemoryStream((byte[])ds.Tables[0].Rows[0]["Background"]);
            pictureBox1.Image = new Bitmap(ms);

These are the codes that I tried using a picturebox as the background, But unable to do so with the background. Any form of help is much appreciated


问:
Deploy a Visual Studio Community 2017 Asp.Net Core 2 project to remote IIS machine
I've built an ASP.NET Core 2.0 MVC Web app on an OS X machine.  I'd like to deploy it to a Windows 2012 server with IIS, not to Azure.

Visual Studio for Mac 2017 Community edition only has the option to publish to an Azure service:

What things on the remote server need to be configured prior to deployment?  What are the step involved in the deployment?

答:
I'd like to deploy it to a Windows 2012 server with IIS, not to Azure.

As you mentioned that Visual Studio for Mac 2017 Community only has publish to Azure option.

According to your description, my workaround is that you could use dotnet publish command to publish  to a local folder.

I test it with Windows platform, you could try it on Mac. You are deploying to a remote server, you could zip up the files and move to the server. You also could refer to this blog to get more detail info.

```<code>dotnet publish webprojectName.csproj --output localpath
</code>```

Body:
I'd like to deploy it to a Windows 2012 server with IIS, not to Azure.

As you mentioned that Visual Studio for Mac 2017 Community only has publish to Azure option.

According to your description, my workaround is that you could use dotnet publish command to publish  to a local folder.

I test it with Windows platform, you could try it on Mac. You are deploying to a remote server, you could zip up the files and move to the server. You also could refer to this blog to get more detail info.

dotnet publish webprojectName.csproj --output localpath


问:
how to automate version of azure ARM template
I am building a CI/CD pipeline in VSTS for Azure ARM Template

When I kick off a build in VSTS:

```<code>- ARM template is generated with a build script I wrote
- ARM template is deployed to Azure
</code>```

I am looking to add a step to increment the version of the ARM template every time I kick off a build.

Does VSTS have any out of the box functionality to increment this version number for me? or do I have to write a script that will read the current version from the arm template, increment it by one, then push the change to GIT? Is there any ways to optimize this process?

答:
There isn’t the official extension can do it, you can do it through PowerShell script, you also can custom build task extension to do it and share to others. Add a build task

Simple script to update version:

```<code>param(
[string]$filepath
)
[object]$armObj=Get-Content $filepath|ConvertFrom-Json
$vArray=$armObj.contentVersion.split(".")
$vArray[-1]=[int]$vArray[-1]+1
$armObj.contentVersion=$vArray -join '.'
$armObj | ConvertTo-Json -Depth 10 |  % { [System.Text.RegularExpressions.Regex]::Unescape($_) } | set-content $filepath
</code>```

Body:
I am building a CI/CD pipeline in VSTS for Azure ARM Template

When I kick off a build in VSTS:

- ARM template is generated with a build script I wrote
- ARM template is deployed to Azure

I am looking to add a step to increment the version of the ARM template every time I kick off a build.

Does VSTS have any out of the box functionality to increment this version number for me? or do I have to write a script that will read the current version from the arm template, increment it by one, then push the change to GIT? Is there any ways to optimize this process?

Body:
There isn’t the official extension can do it, you can do it through PowerShell script, you also can custom build task extension to do it and share to others. Add a build task

Simple script to update version:

param(
[string]$filepath
)
[object]$armObj=Get-Content $filepath|ConvertFrom-Json
$vArray=$armObj.contentVersion.split(".")
$vArray[-1]=[int]$vArray[-1]+1
$armObj.contentVersion=$vArray -join '.'
$armObj | ConvertTo-Json -Depth 10 |  % { [System.Text.RegularExpressions.Regex]::Unescape($_) } | set-content $filepath


问:
Travis CI and GitLab CI disappointing - Other options for GitHub?
I have started a Django (private) project on GitHub. I'd like that my repo tell me if my unit tests passed or failed to each commit. I know there exists Travis CI, but it is expensive and a service en GitLab, but I use GitHub, so...

What other free services, options could I use with GitHub?

答:
Travis CI is free for non-private projects.

Else a quick look at google would give you this:
https://github.com/marketplace/category/continuous-integration

Travis CI

CircleCI

AppVeyor

Percy

Buddy

Semaphore


问:
How do I code an event that calls a method
OK,

I have 5 methods

Move(), TurnRight(), TurnLeft(), Accelerate(), Decelerate()

I have 5 buttons on my windows form called:

Move, Turn Right, Turn Left, Accelerate, Decelerate

How do take values entered from texboxes and store them, so that when a user clicks one of those buttons it calls the method to perform calculations, and then display the information.

I just don't know how or what to code inside the event that I activated from the form.
Can anyone show me a sample of how they would do it?

Here is my move method

public void move()
        {
            double radians = direction * Math.PI / 180;

```<code>        //change the x location by the x vector of the speed
        X_Coordinate += (int)(speed * Math.Cos(radians));

        //change the y location by the y vectior of the speed
        Y_Coordinate -= (int)(speed * Math.Sin(radians));

    }
</code>```

I created a button on my form and named it btnMove

What should I code inside the event for my move button to call the move method and the display that for an outcome?

答:
Say you want to calculate the info in two text boxes, and show the result in the third, you cold do this.

```<code>private void Button1Click(object sender, EventArgs e)
{
    var x = int.Parse(textBox1.Text);
    var y = int.Parse(textBox2.Text);

    textBox3.Text = (x + y).ToString();
}
</code>```

say you shold pass the value over to the move method, you cold do this
change the textBox3.Text = (x + y).ToString(); with move(x + y); if the move takes in an int like this

```<code>public void move(int vaule)
{
   //do stuff with value
}
</code>```

Body:
OK,

I have 5 methods

Move(), TurnRight(), TurnLeft(), Accelerate(), Decelerate()

I have 5 buttons on my windows form called:

Move, Turn Right, Turn Left, Accelerate, Decelerate

How do take values entered from texboxes and store them, so that when a user clicks one of those buttons it calls the method to perform calculations, and then display the information.

I just don't know how or what to code inside the event that I activated from the form.
Can anyone show me a sample of how they would do it?

Here is my move method

public void move()
        {
            double radians = direction * Math.PI / 180;

        //change the x location by the x vector of the speed
        X_Coordinate += (int)(speed * Math.Cos(radians));

        //change the y location by the y vectior of the speed
        Y_Coordinate -= (int)(speed * Math.Sin(radians));

    }

I created a button on my form and named it btnMove

What should I code inside the event for my move button to call the move method and the display that for an outcome?

Body:
Say you want to calculate the info in two text boxes, and show the result in the third, you cold do this.

private void Button1Click(object sender, EventArgs e)
{
    var x = int.Parse(textBox1.Text);
    var y = int.Parse(textBox2.Text);

    textBox3.Text = (x + y).ToString();
}

say you shold pass the value over to the move method, you cold do this
change the textBox3.Text = (x + y).ToString(); with move(x + y); if the move takes in an int like this

public void move(int vaule)
{
   //do stuff with value
}


问:
Fill-in column based on multiple and nested conditions in R
I am simulating a dataset for an assignment, and I need help, I looked for hours but couldn't find a way to fix my problem. I will explain quickly:

I have 2 variables:

Seasons: 4 seasons (Spring, Summer, Autumn, Winter).

Depth: 5 ranges of depths (<100 / 100-400 / 400-700 / 700-1000 / >1000)

I want to generate a 3rd variable, that depends on those 2 independently, which is an abundance of dolphins (poisson distribution). So basically, the thing that needs to change is my lambda.
The only way I found so far to do that is by doing 4 times a different vector, one for each season. And in the end, putting them 4 together.

My code works fine, but it's awfully and ridiculously long and I know that I could shorten it! But I don't know how... Please help :D

Thanks in advance!!!

My code so far:

```<code>abundance_summer <- rep(NA, length(bottom_depth))
set.seed(5)
for (i in 1:length(abundance_summer)){
    if (bottom_depth[i] < 100){
    abundance_summer[i] <- rpois(n=1, lambda=0)
  } else if (bottom_depth[i] > 100 & bottom_depth[i] < 400){
    abundance_summer[i] <- rpois(n=1, lambda=2)
  } else if (bottom_depth[i] > 400 & bottom_depth[i] < 700){
    abundance_summer[i] <- rpois(n=1, lambda=4)
  } else if (bottom_depth[i] > 700 & bottom_depth[i] < 1000){
    abundance_summer[i] <- rpois(n=1, lambda=6)
  } else if (bottom_depth[i] > 1000){
    abundance_summer[i] <- rpois(n=1, lambda=8)
  }
}

abundance_spring <- rep(NA, length(bottom_depth))
set.seed(5)
for (i in 1:length(abundance_spring)){
  if (bottom_depth[i] < 100){
    abundance_spring[i] <- rpois(n=1, lambda=2)
  } else if (bottom_depth[i] > 100 & bottom_depth[i] < 400){
    abundance_spring[i] <- rpois(n=1, lambda=6)
  } else if (bottom_depth[i] > 400 & bottom_depth[i] < 700){
    abundance_spring[i] <- rpois(n=1, lambda=13)
  } else if (bottom_depth[i] > 700 & bottom_depth[i] < 1000){
    abundance_spring[i] <- rpois(n=1, lambda=20)
  } else if (bottom_depth[i] > 1000){
    abundance_spring[i] <- rpois(n=1, lambda=19)
  }
}

abundance_autumn <- rep(NA, length(bottom_depth))
set.seed(5)
for (i in 1:length(abundance_autumn)){
  if (bottom_depth[i] < 100){
    abundance_autumn[i] <- rpois(n=1, lambda=1)
  } else if (bottom_depth[i] > 100 & bottom_depth[i] < 400){
    abundance_autumn[i] <- rpois(n=1, lambda=3)
  } else if (bottom_depth[i] > 400 & bottom_depth[i] < 700){
    abundance_autumn[i] <- rpois(n=1, lambda=6)
  } else if (bottom_depth[i] > 700 & bottom_depth[i] < 1000){
    abundance_autumn[i] <- rpois(n=1, lambda=4)
  } else if (bottom_depth[i] > 1000){
    abundance_autumn[i] <- rpois(n=1, lambda=8)
  }
}

abundance_winter <- rep(NA, length(bottom_depth))
set.seed(5)
for (i in 1:length(abundance_winter)){
  if (bottom_depth[i] < 100){
    abundance_winter[i] <- rpois(n=1, lambda=2)
  } else if (bottom_depth[i] > 100 & bottom_depth[i] < 400){
    abundance_winter[i] <- rpois(n=1, lambda=6)
  } else if (bottom_depth[i] > 400 & bottom_depth[i] < 700){
    abundance_winter[i] <- rpois(n=1, lambda=23)
  } else if (bottom_depth[i] > 700 & bottom_depth[i] < 1000){
    abundance_winter[i] <- rpois(n=1, lambda=16)
  } else if (bottom_depth[i] > 1000){
    abundance_winter[i] <- rpois(n=1, lambda=10)
  }
}

common_dolphins_abundance <- c(abundance_autumn, abundance_spring,abundance_summer, abundance_winter)
</code>```

Body:
I am simulating a dataset for an assignment, and I need help, I looked for hours but couldn't find a way to fix my problem. I will explain quickly:

I have 2 variables:

Seasons: 4 seasons (Spring, Summer, Autumn, Winter).

Depth: 5 ranges of depths (<100 / 100-400 / 400-700 / 700-1000 / >1000)

I want to generate a 3rd variable, that depends on those 2 independently, which is an abundance of dolphins (poisson distribution). So basically, the thing that needs to change is my lambda.
The only way I found so far to do that is by doing 4 times a different vector, one for each season. And in the end, putting them 4 together.

My code works fine, but it's awfully and ridiculously long and I know that I could shorten it! But I don't know how... Please help :D

Thanks in advance!!!

My code so far:

abundance_summer <- rep(NA, length(bottom_depth))
set.seed(5)
for (i in 1:length(abundance_summer)){
    if (bottom_depth[i] < 100){
    abundance_summer[i] <- rpois(n=1, lambda=0)
  } else if (bottom_depth[i] > 100 & bottom_depth[i] < 400){
    abundance_summer[i] <- rpois(n=1, lambda=2)
  } else if (bottom_depth[i] > 400 & bottom_depth[i] < 700){
    abundance_summer[i] <- rpois(n=1, lambda=4)
  } else if (bottom_depth[i] > 700 & bottom_depth[i] < 1000){
    abundance_summer[i] <- rpois(n=1, lambda=6)
  } else if (bottom_depth[i] > 1000){
    abundance_summer[i] <- rpois(n=1, lambda=8)
  }
}

abundance_spring <- rep(NA, length(bottom_depth))
set.seed(5)
for (i in 1:length(abundance_spring)){
  if (bottom_depth[i] < 100){
    abundance_spring[i] <- rpois(n=1, lambda=2)
  } else if (bottom_depth[i] > 100 & bottom_depth[i] < 400){
    abundance_spring[i] <- rpois(n=1, lambda=6)
  } else if (bottom_depth[i] > 400 & bottom_depth[i] < 700){
    abundance_spring[i] <- rpois(n=1, lambda=13)
  } else if (bottom_depth[i] > 700 & bottom_depth[i] < 1000){
    abundance_spring[i] <- rpois(n=1, lambda=20)
  } else if (bottom_depth[i] > 1000){
    abundance_spring[i] <- rpois(n=1, lambda=19)
  }
}

abundance_autumn <- rep(NA, length(bottom_depth))
set.seed(5)
for (i in 1:length(abundance_autumn)){
  if (bottom_depth[i] < 100){
    abundance_autumn[i] <- rpois(n=1, lambda=1)
  } else if (bottom_depth[i] > 100 & bottom_depth[i] < 400){
    abundance_autumn[i] <- rpois(n=1, lambda=3)
  } else if (bottom_depth[i] > 400 & bottom_depth[i] < 700){
    abundance_autumn[i] <- rpois(n=1, lambda=6)
  } else if (bottom_depth[i] > 700 & bottom_depth[i] < 1000){
    abundance_autumn[i] <- rpois(n=1, lambda=4)
  } else if (bottom_depth[i] > 1000){
    abundance_autumn[i] <- rpois(n=1, lambda=8)
  }
}

abundance_winter <- rep(NA, length(bottom_depth))
set.seed(5)
for (i in 1:length(abundance_winter)){
  if (bottom_depth[i] < 100){
    abundance_winter[i] <- rpois(n=1, lambda=2)
  } else if (bottom_depth[i] > 100 & bottom_depth[i] < 400){
    abundance_winter[i] <- rpois(n=1, lambda=6)
  } else if (bottom_depth[i] > 400 & bottom_depth[i] < 700){
    abundance_winter[i] <- rpois(n=1, lambda=23)
  } else if (bottom_depth[i] > 700 & bottom_depth[i] < 1000){
    abundance_winter[i] <- rpois(n=1, lambda=16)
  } else if (bottom_depth[i] > 1000){
    abundance_winter[i] <- rpois(n=1, lambda=10)
  }
}

common_dolphins_abundance <- c(abundance_autumn, abundance_spring,abundance_summer, abundance_winter)

Body:
How about this?

You don't give bottom_depth so I will generate some random numbers.

set.seed(5);
bottom_depth <- runif(100, 0, 2000);

Bin bottom_depth values based on your 5 ranges.

# Bin depth into 5 ranges
breaks.depth <- cut(bottom_depth, breaks = c(0, 100, 400, 700, 1000, max(bottom_depth)));

Store lambda parameters in a dataframe, where columns correspond to seasons, and rows to depth bins.

# Dataframe of lambda parameters for every month for every depth bin
df.lambda <- data.frame(
    summer = c(0, 2, 4, 6, 8),
    spring = c(2, 6, 13, 20, 19),
    autumn = c(1, 3, 6, 4, 8),
    winter = c(2, 6, 23, 16, 10));

For every season, generate Poisson-distributed samples, one for every lambda value:

abundance <- lapply(df.lambda, function(x) {
    rpois(length(bottom_depth), lambda = x[as.numeric(breaks.depth)])
})
#$summer
#  [1]  7 10  8  7  3  7  6  8  8  1  2  6  5  6  4  3  6  5  8  5  5 14  6  6  1
# [26]  2  7 10  1  7  5  1  0  0  0  8  7  2  3  5  7  4  7  6  7 12  9  3  8  9
# [51]  7  9  7  9 11  3  4  5  2  1  6  3  9  7  3 12 11  2  8  5 10 14  1 12  0
# [76] 15  0  3  5  6  8 14  3  0  8  3  5  8  5  4 11  2  3  4  5 10  3 12  5  5
#
#$spring
#  [1] 12 18 10 14  6 19 18 22 18  2 11 20 18 30 13  8 13 21 19 18 24 22 19  8  4
# [26] 23 22 20  3 14 21  4 10  6  1 24 17 17 20 18 12 17 14 16 10 24 17  9 18 22
# [51] 11 18 18 16 15 32 11 13  6  8 27  9 23 13 15 17 22  3 23 16 16 25  9 24  3
# [76] 22  5 16 15 11 23 15 12  7 22  8 20 22 14 17 16 11  8 16 12 25 14 21 20 19
#
#$autumn
#  [1] 11  4  7  1  1  4  7 13  3  2  5  4  4  7  0  3  3  3 11 10  6 14  4  6  2
# [26]  8  8 15  6 10  2  4  5  1  2  5  9  2  4  6  8  6 12  8  4  8  6  3  9 11
# [51]  3  7  5 13  9  3  5  4  2  3  8  0  7  9  3 12  4  1  6  6  6  6  4  4  1
# [76]  4  0  8  4  8 11  7  4  2  4  4 15 12  8  9  6  7  1  5  4  7  5  4  2  6
#
#$winter
#  [1] 19 14 12 21  3 10 10  9 10  4 22 23 22 12 26 28 17  7  9 12 11 10 23 19  7
# [26] 19 16 10  9  8 21  6 23  0  2 12 15 10 22 20  6 26  6 13 12  7  5  3  8 14
# [51] 17 12  7  9 15 10 19 23  4  6  8  6 11  7  7 11 10  0  9 11  8 13  6  7  1
# [76]  5  2 13  7 19  8  9 25 11 22  7  3 16 25 13  8 28  4 23 27 13 22 10 16 15


问:
Intellij Scala library dependency not found
I am new to Scala & IntelliJ. I am trying to write a JSON program but it has compile errors below. I am using json4s-core_2.9.1-3.0.0.

Error:(37, 14) Class com.fasterxml.jackson.core.JsonParseException not
  found - continuing with a stub. Error:(37, 14) Class
  com.fasterxml.jackson.core.JsonProcessingException not found -
  continuing with a stub. Error:(37, 14) Class
  com.fasterxml.jackson.core.JsonGenerationException not found -
  continuing with a stub.

In my set file, I have:

```<code>scalaVersion := "2.12.4"
</code>```

libraryDependencies += "org.json4s" %% "json4s-jackson" % "{latestVersion}"

```<code>libraryDependencies += "com.fasterxml.jackson.core" % "jackson.core" % "{latestVersion}"
libraryDependencies += "com.fasterxml.jackson.core" % "JsonParseException" % "{latestVersion}"
libraryDependencies += "com.fasterxml.jackson.core" % "JsonProcessingException" % "{latestVersion}"
libraryDependencies += "com.fasterxml.jackson.core" % "JsonGenerationException" % "{latestVersion}"
</code>```

What could go wrong? Any idea is appreciated. Thank you!

答:
json4s-core_2.9.1-3.0.0 looks like a very dated version that works with Scala 2.9.1 but you are using Scala version 2.12.4. You need the most recent version of json4s that works with Scala 2.12.4 (which, based on Maven is json4s 3.5.3).  From the json4s install instructions I think you just need the following in your build.sbt file.

```<code>libraryDependencies ++= Seq(
  "org.json4s" %% "json4s-jackson" % "{latestVersion}"
)
</code>```

This should grab the latest version of json4s-core automatically along with the json4s-jackson libraries.

Body:
I am new to Scala & IntelliJ. I am trying to write a JSON program but it has compile errors below. I am using json4s-core_2.9.1-3.0.0.

Error:(37, 14) Class com.fasterxml.jackson.core.JsonParseException not
  found - continuing with a stub. Error:(37, 14) Class
  com.fasterxml.jackson.core.JsonProcessingException not found -
  continuing with a stub. Error:(37, 14) Class
  com.fasterxml.jackson.core.JsonGenerationException not found -
  continuing with a stub.

In my set file, I have:

scalaVersion := "2.12.4"

libraryDependencies += "org.json4s" %% "json4s-jackson" % "{latestVersion}"

libraryDependencies += "com.fasterxml.jackson.core" % "jackson.core" % "{latestVersion}"
libraryDependencies += "com.fasterxml.jackson.core" % "JsonParseException" % "{latestVersion}"
libraryDependencies += "com.fasterxml.jackson.core" % "JsonProcessingException" % "{latestVersion}"
libraryDependencies += "com.fasterxml.jackson.core" % "JsonGenerationException" % "{latestVersion}"

What could go wrong? Any idea is appreciated. Thank you!

Body:
json4s-core_2.9.1-3.0.0 looks like a very dated version that works with Scala 2.9.1 but you are using Scala version 2.12.4. You need the most recent version of json4s that works with Scala 2.12.4 (which, based on Maven is json4s 3.5.3).  From the json4s install instructions I think you just need the following in your build.sbt file.

libraryDependencies ++= Seq(
  "org.json4s" %% "json4s-jackson" % "{latestVersion}"
)

This should grab the latest version of json4s-core automatically along with the json4s-jackson libraries.


答:
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "sourcedir=U:\sourcedir"
SET "destdir=U:\destdir"
SET "filename1=%sourcedir%\q47642335.txt"
SET "outfile=%destdir%\outfile.txt"
(
FOR /f "delims=" %%a IN ('more %filename1%') DO (
 SET "line=%%a"
 ECHO !line:~0,-57!!line:~-53,-31!!line:~-27,-5!!line:~-1!
)
)>"%outfile%"

GOTO :EOF
```

You would need to change the settings of sourcedir and destdir to suit your circumstances.

I used a file named q47642335.txt containing your data for my testing.

Produces the file defined as %outfile%

Sadly, cmd doesn't play nicely with unicode files, so there will be some modification to the data. Essentially, read each line and pick the line-portions to be concatenated, using - substringing values to select from the end of the line, which is of a consistent structure.

Title: Edit text after dot with batch script

Body:
I want to remove three digits after dot in last 3 columns with batch file (windows). Note that dots can be present in other columns.

This is a sample of my data:

4216118,'0806010709','ljubičasti ','Hita kirška ambnta',1,'Eriiti (vk, kk)','X','Uđaj za heološke prege','Celyn1800 ','Hni Sak','Hemlogja','2016-06-08 11:42:05.040','2016-06-08 11:41:42.122','2016-06-08 11:49:49.370'
4216081,'0806010387','ljubičasti ','Oća doven.amb. - VANJA',1,'Erii (vk, kk)',,'Urj za heoške prage','Adia 120 R','Reni','Hlogija','2016-06-08 08:52:13.962','2016-06-08 08:51:57.067','2016-06-08 11:08:26.504'
4216667,'1506010909','ljčasti ','tna ambuta kke za invne bolesti',1,'Erciti (vk, kk)',,'Uj za hemloške prge','Cell-Dyn 1800 R','Hi','Hemagija','2016-06-15 21:24:14.646','2016-06-15 21:24:03.523','2016-06-15 21:26:58.871'
4213710,'0905010991','ljubičasti ','Hna kira amnta',1,'Eociti (vk, kk)','X','Uđaj za hemloške prage','Cel1800 ','Hi Sak','Hemlogja','2016-05-09 17:52:32.231','2016-05-09 17:52:26.319','2016-05-09 18:31:33.643'

Example:
Before:

'2016-06-08 11:49:49.370'

After:

'2016-06-08 11:49:49'

Body:
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "sourcedir=U:\sourcedir"
SET "destdir=U:\destdir"
SET "filename1=%sourcedir%\q47642335.txt"
SET "outfile=%destdir%\outfile.txt"
(
FOR /f "delims=" %%a IN ('more %filename1%') DO (
 SET "line=%%a"
 ECHO !line:~0,-57!!line:~-53,-31!!line:~-27,-5!!line:~-1!
)
)>"%outfile%"

GOTO :EOF

You would need to change the settings of sourcedir and destdir to suit your circumstances.

I used a file named q47642335.txt containing your data for my testing.

Produces the file defined as %outfile%

Sadly, cmd doesn't play nicely with unicode files, so there will be some modification to the data. Essentially, read each line and pick the line-portions to be concatenated, using - substringing values to select from the end of the line, which is of a consistent structure.


问:
Pygame + Sprite rotation not staying centered
I've been banging my head on this for a couple days now. I'm trying to rotate a sprite on its' center axis and have been referencing this previous post about the same issue:

How do I rotate an image around its center using Pygame?

I'm using the exact same code as described in the previous post and also utilizing a image_clean attribute as to not distort the image on successive rotations. When I try and rotate my sprite the center of the image oscillates back and forth between two points.

```<code>def rotate_center(image, angle):
    """rotate a Surface, maintaining position."""
    loc = image.get_rect().center  #rot_image is not defined
    rot_img = pg.transform.rotate(image, angle)
    print('')
    print('>>> before: ' + str(rot_img.get_rect().center))
    rot_img.get_rect().center = loc
    print('>>> after: ' + str(rot_img.get_rect().center))
    return rot_img
</code>```

print statements verify that the line:

```<code>rot_sprite.get_rect().center = loc
</code>```

Doesn't seem to assign the loc value to the image center. The output is always like this:

```<code>>>> before: (32, 32)
>>> after: (32, 32)

>>> before: (37, 37)
>>> after: (37, 37)

>>> before: (41, 41)
>>> after: (41, 41)

>>> before: (43, 43)
>>> after: (43, 43)

>>> before: (45, 45)
>>> after: (45, 45)

>>> before: (45, 45)
>>> after: (45, 45)

>>> before: (43, 43)
>>> after: (43, 43)

>>> before: (41, 41)
>>> after: (41, 41)

>>> before: (37, 37)
>>> after: (37, 37)
</code>```

I always want the center to be at (32, 32) (I believe). Any help would be greatly appreciated.

Code:

```<code>def main():
    pg.init()

# Screen Setup
size = (SCREEN_WIDTH, SCREEN_HEIGHT)
screen = pg.display.set_mode(size)
screen_flags = screen.get_flags()
pg.display.set_caption(GAME_NAME)
done = False
clock = pg.time.Clock()

# SPRITE GROUPS
all_sprites = pg.sprite.Group()
turrets = pg.sprite.Group()

turret = Tower2((SCREEN_WIDTH/2, SCREEN_HEIGHT/2))
turrets.add(turret)
all_sprites.add(turret)

# -------- Main Program Loop -----------
while not done:
    # Process Incoming Events
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True
        if event.type == pg.KEYDOWN:
            if event.key == pg.K_q:
                done = True
            if event.key == pg.K_f:
                if screen_flags & pg.FULLSCREEN == False:
                    screen_flags |= pg.FULLSCREEN
                    pg.display.set_mode(size, screen_flags)
                else:
                    screen_flags ^= pg.FULLSCREEN
                    pg.display.set_mode(size, screen_flags)

    turret.angle += 10
    turret.image = rotate_center(turret.image_clean, turret.angle)

    screen.fill(WHITE)
    all_sprites.draw(screen)
    pg.display.flip()
    clock.tick(15)

pg.quit()

class Tower2(pg.sprite.Sprite):
    def __init__(self, pos, image, tRange, attackSpeed=1):
        super().__init__()
        self.image = image
        self.image_clean = image
        self.rect = self.image.get_rect()
        self.rect.center = pos
        self.range = tRange
        self.attackSpeed = attackSpeed
        self.lastAttack = time.time()
        self.angle = 0

    def __iter__(self):
        return self

    def canAttack(self):
        if time.time() - self.lastAttack > self.attackSpeed:
            return True
        else:
            return False

    def rotate(self):
        pass

    def update(self):
        self.angle += 10
        self.image = pg.transform.rotate(self.image_clean, self.angle)
        self.image.get_rect().center = self.image_clean.get_rect().center

class Turret1(Tower2):
    def __init__(self, pos):
        TOWER_WIDTH = 64
        TOWER_HEIGHT = 64
        INIT_RANGE = 200
        INIT_RATE = 1
        SPEED = 1
        tower_img = pg.image.load('imgs/test_rotate.png')
        tower_img = pg.transform.scale(tower_img, (TOWER_WIDTH, TOWER_HEIGHT))
        super().__init__(pos, tower_img, INIT_RANGE, SPEED)
</code>```

答:
Don't use get_rect() all the time - it always creates new rectangle and you change position in this new rectangle, not in original one. And later you get again new rectangle to display position.

Besides image doesn't keep position you have to get rectangle once and use it to keep position.

```<code>loc = image.get_rect().center

rot_img = pg.transform.rotate(image, angle)

# get rectangle and keep it
rot_img_rect = rot_img.get_rect()

# change position in rectangle
rot_img_rect.center = loc

# display position
print('>>> after: ', rot_img_rect.center)

# return image and position in `rot_img_rect`
return rot_img, rot_img_rect
</code>```

Body:
I've been banging my head on this for a couple days now. I'm trying to rotate a sprite on its' center axis and have been referencing this previous post about the same issue:

How do I rotate an image around its center using Pygame?

I'm using the exact same code as described in the previous post and also utilizing a image_clean attribute as to not distort the image on successive rotations. When I try and rotate my sprite the center of the image oscillates back and forth between two points.

def rotate_center(image, angle):
    """rotate a Surface, maintaining position."""
    loc = image.get_rect().center  #rot_image is not defined
    rot_img = pg.transform.rotate(image, angle)
    print('')
    print('>>> before: ' + str(rot_img.get_rect().center))
    rot_img.get_rect().center = loc
    print('>>> after: ' + str(rot_img.get_rect().center))
    return rot_img

print statements verify that the line:

rot_sprite.get_rect().center = loc

Doesn't seem to assign the loc value to the image center. The output is always like this:

>>> before: (32, 32)
>>> after: (32, 32)

>>> before: (37, 37)
>>> after: (37, 37)

>>> before: (41, 41)
>>> after: (41, 41)

>>> before: (43, 43)
>>> after: (43, 43)

>>> before: (45, 45)
>>> after: (45, 45)

>>> before: (45, 45)
>>> after: (45, 45)

>>> before: (43, 43)
>>> after: (43, 43)

>>> before: (41, 41)
>>> after: (41, 41)

>>> before: (37, 37)
>>> after: (37, 37)

I always want the center to be at (32, 32) (I believe). Any help would be greatly appreciated.

Code:

def main():
    pg.init()

# Screen Setup
size = (SCREEN_WIDTH, SCREEN_HEIGHT)
screen = pg.display.set_mode(size)
screen_flags = screen.get_flags()
pg.display.set_caption(GAME_NAME)
done = False
clock = pg.time.Clock()

# SPRITE GROUPS
all_sprites = pg.sprite.Group()
turrets = pg.sprite.Group()

turret = Tower2((SCREEN_WIDTH/2, SCREEN_HEIGHT/2))
turrets.add(turret)
all_sprites.add(turret)

# -------- Main Program Loop -----------
while not done:
    # Process Incoming Events
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True
        if event.type == pg.KEYDOWN:
            if event.key == pg.K_q:
                done = True
            if event.key == pg.K_f:
                if screen_flags & pg.FULLSCREEN == False:
                    screen_flags |= pg.FULLSCREEN
                    pg.display.set_mode(size, screen_flags)
                else:
                    screen_flags ^= pg.FULLSCREEN
                    pg.display.set_mode(size, screen_flags)

    turret.angle += 10
    turret.image = rotate_center(turret.image_clean, turret.angle)

    screen.fill(WHITE)
    all_sprites.draw(screen)
    pg.display.flip()
    clock.tick(15)

pg.quit()

class Tower2(pg.sprite.Sprite):
    def __init__(self, pos, image, tRange, attackSpeed=1):
        super().__init__()
        self.image = image
        self.image_clean = image
        self.rect = self.image.get_rect()
        self.rect.center = pos
        self.range = tRange
        self.attackSpeed = attackSpeed
        self.lastAttack = time.time()
        self.angle = 0

    def __iter__(self):
        return self

    def canAttack(self):
        if time.time() - self.lastAttack > self.attackSpeed:
            return True
        else:
            return False

    def rotate(self):
        pass

    def update(self):
        self.angle += 10
        self.image = pg.transform.rotate(self.image_clean, self.angle)
        self.image.get_rect().center = self.image_clean.get_rect().center

class Turret1(Tower2):
    def __init__(self, pos):
        TOWER_WIDTH = 64
        TOWER_HEIGHT = 64
        INIT_RANGE = 200
        INIT_RATE = 1
        SPEED = 1
        tower_img = pg.image.load('imgs/test_rotate.png')
        tower_img = pg.transform.scale(tower_img, (TOWER_WIDTH, TOWER_HEIGHT))
        super().__init__(pos, tower_img, INIT_RANGE, SPEED)

Body:
Don't use get_rect() all the time - it always creates new rectangle and you change position in this new rectangle, not in original one. And later you get again new rectangle to display position.

Besides image doesn't keep position you have to get rectangle once and use it to keep position.

loc = image.get_rect().center

rot_img = pg.transform.rotate(image, angle)

# get rectangle and keep it
rot_img_rect = rot_img.get_rect()

# change position in rectangle
rot_img_rect.center = loc

# display position
print('>>> after: ', rot_img_rect.center)

# return image and position in `rot_img_rect`
return rot_img, rot_img_rect


问:
how to find multiple files with wildcard expression in objective-c
How do I get hold of all the *.bmp files (or *.xyz in general) in my Document folder, writing an iPhone 3.0 SDK?</p>

答:
You need to use NSFileManager's contentsOfDirectoryAtPath:error: function. Note that this does not traverse subdirectories and extension cannot contain a ..

```<code>-(NSArray *)findFiles:(NSString *)extension
{
    NSMutableArray *matches = [[NSMutableArray alloc]init];
    NSFileManager *manager = [NSFileManager defaultManager];

    NSString *item;
    NSArray *contents = [manager contentsOfDirectoryAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] error:nil];
    for (item in contents)
    {
        if ([[item pathExtension]isEqualToString:extension])
        {
            [matches addObject:item];
        }
    }

    return matches;
}
</code>```

Body:
You need to use NSFileManager's contentsOfDirectoryAtPath:error: function. Note that this does not traverse subdirectories and extension cannot contain a ..

-(NSArray *)findFiles:(NSString *)extension
{
    NSMutableArray *matches = [[NSMutableArray alloc]init];
    NSFileManager *manager = [NSFileManager defaultManager];

    NSString *item;
    NSArray *contents = [manager contentsOfDirectoryAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] error:nil];
    for (item in contents)
    {
        if ([[item pathExtension]isEqualToString:extension])
        {
            [matches addObject:item];
        }
    }

    return matches;
}


问:
Xamarin bar code scanner ZXing.Net Mobile
I am working on an Xamarin.Forms application. Specifically, I am focusing on the Android platform before I focus on iOS. So far in my application I have implemented login and registration. When I was working on the login and registration features of the application all the work that I did was in the PCL, which would compile into android and iOS.

However, I now want to implement barcode scanning. For this requirement I have decided to use the ZXing.Net.Mobile for Forms library. After reading the documentation it says the following var scanPage = new ZXingScannerPage();. I have download ZXing.Net.Mobile for Forms in my Xamarin.Android solution however it is unable to find the class. Any help or guidance would be great thanks.

答:
I have download ZXing.Net.Mobile for Forms in my Xamarin.Android solution however it is unable to find the class

If you just install the ZXing.Net.Mobile nuget package, it's unable to find the class.

You could see the ZXing.Net.Mobile source code, the ZXingScannerPage.cs class is included in ZXing.Net.Mobile.Forms. So you need download the ZXing.Net.Mobile.Forms nuget package :

Then you could get started with ZXingScannerPage :

```<code>var scanPage = new ZXing.Net.Mobile.Forms.ZXingScannerPage();
</code>```

Body:
I have download ZXing.Net.Mobile for Forms in my Xamarin.Android solution however it is unable to find the class

If you just install the ZXing.Net.Mobile nuget package, it's unable to find the class.

You could see the ZXing.Net.Mobile source code, the ZXingScannerPage.cs class is included in ZXing.Net.Mobile.Forms. So you need download the ZXing.Net.Mobile.Forms nuget package :

Then you could get started with ZXingScannerPage :

var scanPage = new ZXing.Net.Mobile.Forms.ZXingScannerPage();


问:
How to use final_embeddings?
From udacity notebook exercise;  After embeddings were trained,  I'm trying to get all related words from an input word and I'm getting wierd results.
Is the code below correct?

udacity exercise

```<code>final_embeddings = normalized_embeddings.eval()
word='history'
nearest = (-final_embeddings[dictionary[word], :]).argsort()[1:9]
for idx in range(len(nearest)):
    print reverse_dictionary[nearest[idx]]
</code>```

答:
sorry for the dumb question.  Just realized that final_embeddings is the W trained matrix.
Answer is: given an input word. Similarity is computed doing the prob_vec[word] matmul W

```<code>word='the'
word_vec = final_embeddings[dictionary[word]]
sim = np.dot(word_vec, -final_embeddings.T).argsort()[0:8]
for idx in range(8):
    print reverse_dictionary[sim[idx]]
</code>```

Thanks!

Title: How to use final_embeddings?

Body:
From udacity notebook exercise;  After embeddings were trained,  I'm trying to get all related words from an input word and I'm getting wierd results.
Is the code below correct?

udacity exercise

final_embeddings = normalized_embeddings.eval()
word='history'
nearest = (-final_embeddings[dictionary[word], :]).argsort()[1:9]
for idx in range(len(nearest)):
    print reverse_dictionary[nearest[idx]]

Body:
sorry for the dumb question.  Just realized that final_embeddings is the W trained matrix.
Answer is: given an input word. Similarity is computed doing the prob_vec[word] matmul W

word='the'
word_vec = final_embeddings[dictionary[word]]
sim = np.dot(word_vec, -final_embeddings.T).argsort()[0:8]
for idx in range(8):
    print reverse_dictionary[sim[idx]]

Thanks!


问:
Instantiating javascript class in Node.js
Why is the following code gives me an error?

```<code>// In Foo.js
class Foo {
    constructor(a) {
        this.a = a;
    }
}

module.exports = Foo

// In Index.js
var foo = new require('path/Foo.js')('param');
</code>```

This gives me Class constructor Foo cannot be invoked without 'new'.

Thanks.

答:
I believe that in your code the new operator is applied to the require() function, not to what require() returns. That is, this:

```<code>var foo = new require('path/Foo.js')('param');
</code>```

...is like doing this:

```<code>var foo = ( new require('path/Foo.js') )('param');
</code>```

...or:

```<code>var temp = new require('path/Foo.js');
var foo = temp('param');
</code>```

Try the following instead, so that new is applied to your class:

```<code>var Foo = require('path/Foo.js');
var foo = new Foo('param');
</code>```

Body:
Why is the following code gives me an error?

// In Foo.js
class Foo {
    constructor(a) {
        this.a = a;
    }
}

module.exports = Foo

// In Index.js
var foo = new require('path/Foo.js')('param');

This gives me Class constructor Foo cannot be invoked without 'new'.

Thanks.

Body:
I believe that in your code the new operator is applied to the require() function, not to what require() returns. That is, this:

var foo = new require('path/Foo.js')('param');

...is like doing this:

var foo = ( new require('path/Foo.js') )('param');

...or:

var temp = new require('path/Foo.js');
var foo = temp('param');

Try the following instead, so that new is applied to your class:

var Foo = require('path/Foo.js');
var foo = new Foo('param');


问:
Optimize nested array from path strings
Given this simple array of objects:

```<code>var allPaths = [
  {path: "/", component: 'cmp-1'},
  {path: "/my-cool-list/", component: 'cmp-2'},
  {path: "/my-cool-list/this-is-card-1", component: 'cmp-3'},
  {path: "/my-cool-list/this-is-card-2", component: 'cmp-4'},
  {path: "/blog/", component: 'cmp-5'},
  {path: "/blog/2017/01/this-is-card-3", component: 'cmp-6'},
  {path: "/blog/2017/02/this-is-card-4", component: 'cmp-7'},
  {path: "/recettes/", component: 'cmp-8'},
  {path: "/recettes/this-is-card-5", component: 'cmp-9'},
  {path: "/recettes/this-is-card-6", component: 'cmp-10'}
]
</code>```

In need to produce this output:

```<code>[
  {
    path: "/", component: 'cmp-1'
  },
  {
    path: "/my-cool-list",
    component: 'cmp-2',
    children: [
      {path: "/this-is-card-1", component: 'cmp-3'},
      {path: "/this-is-card-2", component: 'cmp-4'}
    ]
  },

  {
    path: "/blog",
    component: 'cmp-5',
    children: [
      {
        path: "/2017",
        children: [
          {
            path: "/01",
            children: [
              {path: "/this-is-card-3", component: 'cmp-6'}
            ]
          },
          {
            path: "/02",
            children: [
              {path: "/this-is-card-4", component: 'cmp-7'}
            ]
          }
        ]
      }
    ]
  },

  {
    path: "/recettes",
    component: 'cmp-8',
    children: [
      {path: "/this-is-card-5", component: 'cmp-9'},
      {path: "/this-is-card-6", component: 'cmp-10'}
    ]
  },
]
</code>```

One way I found to do this is by:

traverse each object in allPaths

create a valid output for each paths (like if only this path was provided)

push resulting object into an array named tree

...rinse and repeat...

then deeply merge resulting tree into a unique one.

The code look something like this fiddle here:

```<code>let tree = []

// Recursive Tree Builder
const buildTree = (pathArray, ...others) => {
    var currentToken = pathArray.shift()
    var arr = []
    if (pathArray.length>0) {
       arr.push( {path: '/'+currentToken, children: []} )
       arr[0].children = buildTree(pathArray, ...others)
    } else {
       arr.push( Object.assign( {path: '/'+currentToken}, others[0] ))
    }
    return arr;
}

// For each object in `allPaths`, build a tree
allPaths.map( page => {
   let {path, ...rest} = page
   let res = buildTree(path.split('/').slice(1), rest)
   tree.push(res[0])
})

// external code to deeply merge each objects in `tree` (external library: no need to put the code here but you got the point)
</code>```

I guess there should be a way to construct the final output lazily, without requiring yet another merge operation at the end: like constructing the final tree on the go without intermediate storing + another operation.

To narrow down the question further, I attempted to build the tree on-the-fly but I got stuck while attempting to push an entry to precise location in the tree. For example, keeping reference to tree[0].children[0].children[0].children[0] ... bugs me as I don't know how deeper I'll find the related path or if children will even exist at this level.

A pseudo code (I imagine), would be :

traverse allPaths objects one by one

(pretend the first object traversed has path like /blog/level-2)

search the tree for the 1st level found in path (ex: /blog in /blog/level-2)

not found ? then, push object in the tree

this path has further levels (like in /blog/level-2) ?

.......yes ? go one level deeper (/level-2) into children and repeat from step 3

.......no  ? reset level to 0. break

Now I have difficulties to achieve those levels tracking as:
- I don't know how to easily query the tree given a path: /blog/level-2 may be at tree[2].children[14] or tree[32].children[57] and I have hard time to query it but moreover to STORE this info for later use.

Any thoughts ?

答:
Ok I figured this out myself.

```<code>const appendToTree = (tree, obj) => {
  // extract path from object
  let {path, ...rest} = obj

  // turn path into array of params
  let URLparams = path.split('/').slice(1)

  // recursive calls could send empty array
  if (URLparams.length === 0) return tree

  // take out first element in array: removes it from the array as well
  let currentURLparam = URLparams.shift()
  // reset path to what's left in URLparams after shift
    path = '/' + URLparams.join('/')

  let currentPosition = 0,
      currentNode = {},
      found = false

loopTree:  // find corresponding param in tree
  for(currentPosition; currentPosition < tree.length; currentPosition++) {
    if (tree[currentPosition].path === '/'+currentURLparam) {
       currentNode = tree[currentPosition]
       found = true
       break loopTree
    }
  }

  if(  found ) {  // found a matching path
    // get a reference to children or create an empty one
    currentNode['children'] = currentNode.children || []
    // repeat all, but with current reference and val which has been shifted before
    return appendToTree(currentNode.children, {path, ...rest})
  } else {  // not matching path found: insert it
    if (URLparams.length > 0) {  // still have URL params left ?
       // push current page object into array
       // Here we could force any default props to index levels
       let pos = tree.push({path: '/'+currentURLparam, children: []}) - 1
       // we still have params to process, so we proceed another iteration
       return appendToTree(tree[pos].children, {path, ...rest})
    } else { // no URL params left, this is the last one in stack
       tree.push({path: '/'+currentURLparam, ...rest})
       return tree
    }
  }
}

const buildTree = (tree, pages) => {
  // Traverse all pages objects and append each to provided tree
  pages.map(page => {
    appendToTree(tree, page)
  })
  return tree
}
</code>```

Then, we just need to call:

```<code>buildTree([], allPaths)
</code>```

...it will correctly create a tree on the fly, as we traverse each object in allPaths.
To solve my problem, I used recursion.

Title: Optimize nested array from path strings

Body:
Given this simple array of objects:

var allPaths = [
  {path: "/", component: 'cmp-1'},
  {path: "/my-cool-list/", component: 'cmp-2'},
  {path: "/my-cool-list/this-is-card-1", component: 'cmp-3'},
  {path: "/my-cool-list/this-is-card-2", component: 'cmp-4'},
  {path: "/blog/", component: 'cmp-5'},
  {path: "/blog/2017/01/this-is-card-3", component: 'cmp-6'},
  {path: "/blog/2017/02/this-is-card-4", component: 'cmp-7'},
  {path: "/recettes/", component: 'cmp-8'},
  {path: "/recettes/this-is-card-5", component: 'cmp-9'},
  {path: "/recettes/this-is-card-6", component: 'cmp-10'}
]

In need to produce this output:

[
  {
    path: "/", component: 'cmp-1'
  },
  {
    path: "/my-cool-list",
    component: 'cmp-2',
    children: [
      {path: "/this-is-card-1", component: 'cmp-3'},
      {path: "/this-is-card-2", component: 'cmp-4'}
    ]
  },

  {
    path: "/blog",
    component: 'cmp-5',
    children: [
      {
        path: "/2017",
        children: [
          {
            path: "/01",
            children: [
              {path: "/this-is-card-3", component: 'cmp-6'}
            ]
          },
          {
            path: "/02",
            children: [
              {path: "/this-is-card-4", component: 'cmp-7'}
            ]
          }
        ]
      }
    ]
  },

  {
    path: "/recettes",
    component: 'cmp-8',
    children: [
      {path: "/this-is-card-5", component: 'cmp-9'},
      {path: "/this-is-card-6", component: 'cmp-10'}
    ]
  },
]

One way I found to do this is by:

traverse each object in allPaths

create a valid output for each paths (like if only this path was provided)

push resulting object into an array named tree

...rinse and repeat...

then deeply merge resulting tree into a unique one.

The code look something like this fiddle here:

let tree = []

// Recursive Tree Builder
const buildTree = (pathArray, ...others) => {
    var currentToken = pathArray.shift()
    var arr = []
    if (pathArray.length>0) {
       arr.push( {path: '/'+currentToken, children: []} )
       arr[0].children = buildTree(pathArray, ...others)
    } else {
       arr.push( Object.assign( {path: '/'+currentToken}, others[0] ))
    }
    return arr;
}

// For each object in `allPaths`, build a tree
allPaths.map( page => {
   let {path, ...rest} = page
   let res = buildTree(path.split('/').slice(1), rest)
   tree.push(res[0])
})

// external code to deeply merge each objects in `tree` (external library: no need to put the code here but you got the point)

I guess there should be a way to construct the final output lazily, without requiring yet another merge operation at the end: like constructing the final tree on the go without intermediate storing + another operation.

To narrow down the question further, I attempted to build the tree on-the-fly but I got stuck while attempting to push an entry to precise location in the tree. For example, keeping reference to tree[0].children[0].children[0].children[0] ... bugs me as I don't know how deeper I'll find the related path or if children will even exist at this level.

A pseudo code (I imagine), would be :

traverse allPaths objects one by one

(pretend the first object traversed has path like /blog/level-2)

search the tree for the 1st level found in path (ex: /blog in /blog/level-2)

not found ? then, push object in the tree

this path has further levels (like in /blog/level-2) ?

.......yes ? go one level deeper (/level-2) into children and repeat from step 3

.......no  ? reset level to 0. break

Now I have difficulties to achieve those levels tracking as:
- I don't know how to easily query the tree given a path: /blog/level-2 may be at tree[2].children[14] or tree[32].children[57] and I have hard time to query it but moreover to STORE this info for later use.

Any thoughts ?

Body:
Ok I figured this out myself.

const appendToTree = (tree, obj) => {
  // extract path from object
  let {path, ...rest} = obj

  // turn path into array of params
  let URLparams = path.split('/').slice(1)

  // recursive calls could send empty array
  if (URLparams.length === 0) return tree

  // take out first element in array: removes it from the array as well
  let currentURLparam = URLparams.shift()
  // reset path to what's left in URLparams after shift
    path = '/' + URLparams.join('/')

  let currentPosition = 0,
      currentNode = {},
      found = false

loopTree:  // find corresponding param in tree
  for(currentPosition; currentPosition < tree.length; currentPosition++) {
    if (tree[currentPosition].path === '/'+currentURLparam) {
       currentNode = tree[currentPosition]
       found = true
       break loopTree
    }
  }

  if(  found ) {  // found a matching path
    // get a reference to children or create an empty one
    currentNode['children'] = currentNode.children || []
    // repeat all, but with current reference and val which has been shifted before
    return appendToTree(currentNode.children, {path, ...rest})
  } else {  // not matching path found: insert it
    if (URLparams.length > 0) {  // still have URL params left ?
       // push current page object into array
       // Here we could force any default props to index levels
       let pos = tree.push({path: '/'+currentURLparam, children: []}) - 1
       // we still have params to process, so we proceed another iteration
       return appendToTree(tree[pos].children, {path, ...rest})
    } else { // no URL params left, this is the last one in stack
       tree.push({path: '/'+currentURLparam, ...rest})
       return tree
    }
  }
}

const buildTree = (tree, pages) => {
  // Traverse all pages objects and append each to provided tree
  pages.map(page => {
    appendToTree(tree, page)
  })
  return tree
}

Then, we just need to call:

buildTree([], allPaths)

...it will correctly create a tree on the fly, as we traverse each object in allPaths.
To solve my problem, I used recursion.


问:
What is the double dash in this bash script excerpt doing
I'm looking at an excerpt of bash and I'm trying to understand what exactly is happening here, particularly in the COMPREPLY assignment:

```<code> case "$cur" in
    -*)
    COMPREPLY=( $( compgen -W '-a -d -f -l -t -h --aoption --debug \
                               --file --log --test --help --' -- $cur ) );;
#   Generate the completion matches and load them into $COMPREPLY array.
#   xx) May add more cases here.
#   yy)
#   zz)
  esac
</code>```

I understand we're assigning a value to COMPREPLY here based on the output of compgen, but what exactly is -- doing in this assignment? Also, why the double semi-colon?

答:
The double dashes end the argument portion in getopt_long. From the manual.

The special argument "--" forces an end of option-scanning regardless
  of the scanning mode.

https://linux.die.net/man/3/getopt_long

The double semi colons end a case branch.

Body:
I'm looking at an excerpt of bash and I'm trying to understand what exactly is happening here, particularly in the COMPREPLY assignment:

 case "$cur" in
    -*)
    COMPREPLY=( $( compgen -W '-a -d -f -l -t -h --aoption --debug \
                               --file --log --test --help --' -- $cur ) );;
#   Generate the completion matches and load them into $COMPREPLY array.
#   xx) May add more cases here.
#   yy)
#   zz)
  esac

I understand we're assigning a value to COMPREPLY here based on the output of compgen, but what exactly is -- doing in this assignment? Also, why the double semi-colon?


问:
How to use thermal printer in laravel 5.4?
I m trying to do web application for restaurant in Laravel 5.4.
But i don't know how can i print receipt using thermal printer.
Please suggest me best way to print data on thermal printer in laravel.

Thanks in advance.

答:
I recently use Mike42/escpos-php for my minithermal M-58 POS printer. This is a php plugin that will connect your php app with minithermal printer through network. This is my simple code to print some words on minithermal printer.

```<code>try {
        // Enter the share name for your USB printer here
        //$connector = "POS-58";
        //$connector = new WindowsPrintConnector("POS-58");
        $connector = new WindowsPrintConnector("smb://yourPrinterIP");
        /* Print a "Hello world" receipt" */
        $printer = new Printer($connector);
        /* Name of shop */
        $printer->selectPrintMode(Printer::MODE_DOUBLE_WIDTH);
        $printer->setJustification(Printer::JUSTIFY_CENTER);
        $printer->text("POS Mart\n");
        $printer->selectPrintMode();
        $printer->text("Today Closing.\n");

        $printer->feed();
        /* Title of receipt */
        $printer->setEmphasis(true);

        $printer->feed(2);

        /* Cut the receipt and open the cash drawer */
        $printer->cut();
        $printer->pulse();
        /* Close printer */
        $printer->close();
        // echo "Sudah di Print";
        return true;
    } catch (Exception $e) {
        $message = "Couldn't print to this printer: " . $e->getMessage() . "\n";
        return false;
    }
</code>```

All you need is to add your printer IP to your php printconnector code or if you use usb cable to connect to your printer, you can use your own ip as php printconnector code.

Body:
I recently use Mike42/escpos-php for my minithermal M-58 POS printer. This is a php plugin that will connect your php app with minithermal printer through network. This is my simple code to print some words on minithermal printer.

try {
        // Enter the share name for your USB printer here
        //$connector = "POS-58";
        //$connector = new WindowsPrintConnector("POS-58");
        $connector = new WindowsPrintConnector("smb://yourPrinterIP");
        /* Print a "Hello world" receipt" */
        $printer = new Printer($connector);
        /* Name of shop */
        $printer->selectPrintMode(Printer::MODE_DOUBLE_WIDTH);
        $printer->setJustification(Printer::JUSTIFY_CENTER);
        $printer->text("POS Mart\n");
        $printer->selectPrintMode();
        $printer->text("Today Closing.\n");

        $printer->feed();
        /* Title of receipt */
        $printer->setEmphasis(true);

        $printer->feed(2);

        /* Cut the receipt and open the cash drawer */
        $printer->cut();
        $printer->pulse();
        /* Close printer */
        $printer->close();
        // echo "Sudah di Print";
        return true;
    } catch (Exception $e) {
        $message = "Couldn't print to this printer: " . $e->getMessage() . "\n";
        return false;
    }

All you need is to add your printer IP to your php printconnector code or if you use usb cable to connect to your printer, you can use your own ip as php printconnector code.


问:
Why does this C# function exist in Visual Studio 2015 but not Visual Studio 2017
Just someone can explain me why this work on Visual Studio 2015 but not on Visual Studio 2017 ?

```<code>public static TConvert DynamicPop<TObject, TConvert>(this IEnumerable<TObject> obj, Converter<TObject, TConvert> converter, long @default = 1)
    {
        if (obj.Count() == 0)
        {
            dynamic _defaut = @default;
            return (TConvert)_defaut;
        }
        var collection = obj.ConvertAll<TConvert>(converter);
        collection.Sort();
        dynamic lastValue = collection.Last();
        return (TConvert)(lastValue + 1);
    }
</code>```

That said to me that ConvertAll doesn't exist.

答:
ConvertAll is not an available method on IEnumerable<T>. In VS 2015 you must have been calling it via an extension method you built yourself (or which was referenced).

One option might be to replace:

```<code>var collection = obj.ConvertAll<TConvert>(converter);
collection.Sort();
dynamic lastValue = collection.Last();
</code>```

with:

```<code>dynamic lastValue = obj.Select(z => converter(z)).OrderByDescending(z => z).First();
</code>```

Basically just replacing ConvertAll with Select which does roughly the same thing. The OrderByDescending replaces the Sort also.

Body:
Just someone can explain me why this work on Visual Studio 2015 but not on Visual Studio 2017 ?

public static TConvert DynamicPop<TObject, TConvert>(this IEnumerable<TObject> obj, Converter<TObject, TConvert> converter, long @default = 1)
    {
        if (obj.Count() == 0)
        {
            dynamic _defaut = @default;
            return (TConvert)_defaut;
        }
        var collection = obj.ConvertAll<TConvert>(converter);
        collection.Sort();
        dynamic lastValue = collection.Last();
        return (TConvert)(lastValue + 1);
    }

That said to me that ConvertAll doesn't exist.

Body:
ConvertAll is not an available method on IEnumerable<T>. In VS 2015 you must have been calling it via an extension method you built yourself (or which was referenced).

One option might be to replace:

var collection = obj.ConvertAll<TConvert>(converter);
collection.Sort();
dynamic lastValue = collection.Last();

with:

dynamic lastValue = obj.Select(z => converter(z)).OrderByDescending(z => z).First();

Basically just replacing ConvertAll with Select which does roughly the same thing. The OrderByDescending replaces the Sort also.