问:
Segmentation Fault when trying to increment letters
```<code>#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
#include <crypt.h>

int main(int argc, string argv[])
{
    if(argc > 2){ printf("too many arguments\n"); return 51; }
    if(argc < 2){ printf("too few arguments\n"); return 50; }
    if(strlen(argv[1]) > 4){ printf("Password is greater than 4 characters\n"); return 52; }

    if(argc == 2) //make sure there are enough args
    {
        string hash_guess = "A";

        while(crypt(hash_guess, "50") != argv[1]) //while answer not correct
        {
            while(hash_guess[0] <= 'Z' && hash_guess[0] >= 'A')
            {
                hash_guess[0] = hash_guess[0] + 1;
                printf("%s", hash_guess);
            }
        }

    }

}
</code>```

I am trying to increment letter by letter through a word, so it would go a then b then c until z then it will go aa, ab, ac, ad.... then ba bb bc bd... then za... zz... zzz. I'm starting with one letter, but I get error "segmentation fault"

答:
I am surprised you are getting a seg-fault.  The code you are showing should not even compile.

The line:

```<code>   string hash_guess = "A";
</code>```

uses string as a type.  Unless you have typedef'd string in a part of your code somewhere not shown, it cannot be used to create a variable.

Try:

```<code>   char hash_guess[] = "A";//creates array of char, 2 bytes long:  |A|0|
</code>```

Even then, if you need this variable to contain more than just 2 bytes, create it with more space:

```<code>   char hash_guess[10] = "A"; Creates space for 10 bytes: |A|0|0|0|0|0|0|0|0|0|
</code>```

Remember that a C string is defined as an array of char terminated with a NULL.

EDIT  Per @MichaelDorgan's finding, cs50 typedefs String as char *.  So the offending line now becomes equivalent to:

```<code>   char *hash_guess = "A";
</code>```

Which is why it compiles and runs.   The segfault could be happening when you explicitly attempt to write to a location in memory that you do not own, which is UB.  (however, it is not clear from looking at your code that this is what is happening, just a guess)

Another conventional way to create and initialize a pointer, then create space (for more than two bytes):

```<code>String hash_guess = {0};
hash_guess = calloc(10, 1);
if(hash_guess)
{
    //... (your code here)
    //hash_guess can now contain up to 9 characters and the NULL terminator.
}
free(hash_guess);
</code>```

Body:
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
#include <crypt.h>

int main(int argc, string argv[])
{
    if(argc > 2){ printf("too many arguments\n"); return 51; }
    if(argc < 2){ printf("too few arguments\n"); return 50; }
    if(strlen(argv[1]) > 4){ printf("Password is greater than 4 characters\n"); return 52; }

    if(argc == 2) //make sure there are enough args
    {
        string hash_guess = "A";

        while(crypt(hash_guess, "50") != argv[1]) //while answer not correct
        {
            while(hash_guess[0] <= 'Z' && hash_guess[0] >= 'A')
            {
                hash_guess[0] = hash_guess[0] + 1;
                printf("%s", hash_guess);
            }
        }

    }

}

I am trying to increment letter by letter through a word, so it would go a then b then c until z then it will go aa, ab, ac, ad.... then ba bb bc bd... then za... zz... zzz. I'm starting with one letter, but I get error "segmentation fault"

Body:
I am surprised you are getting a seg-fault.  The code you are showing should not even compile.

The line:

   string hash_guess = "A";

uses string as a type.  Unless you have typedef'd string in a part of your code somewhere not shown, it cannot be used to create a variable.

Try:

   char hash_guess[] = "A";//creates array of char, 2 bytes long:  |A|0|

Even then, if you need this variable to contain more than just 2 bytes, create it with more space:

   char hash_guess[10] = "A"; Creates space for 10 bytes: |A|0|0|0|0|0|0|0|0|0|

Remember that a C string is defined as an array of char terminated with a NULL.

EDIT  Per @MichaelDorgan's finding, cs50 typedefs String as char *.  So the offending line now becomes equivalent to:

   char *hash_guess = "A";

Which is why it compiles and runs.   The segfault could be happening when you explicitly attempt to write to a location in memory that you do not own, which is UB.  (however, it is not clear from looking at your code that this is what is happening, just a guess)

Another conventional way to create and initialize a pointer, then create space (for more than two bytes):

String hash_guess = {0};
hash_guess = calloc(10, 1);
if(hash_guess)
{
    //... (your code here)
    //hash_guess can now contain up to 9 characters and the NULL terminator.
}
free(hash_guess);


来源: stackexchange

问:
Use a switch case for a verification function (LWJGL keyboard input)?
What the title says. Is it possible?
As far as I know, there is no getKeyPressed or anything of the sort. I want to use a switch case for organization (and practice) as well as speed (or so I was informed).

Basically, the switch case clause(?) is just a boolean return. But how can I check if a key is pressed based on a value passed into it without a pasta bowl of if / else statements?

Obviously this code doesn't work, but I'm looking for something like it.

```<code>public void moveCamera() {
    switch (Keyboard.isKeyDown(!!!CASE CHECKING HERE!!!)) {
        case Keyboard.KEY_W:
            position.z -= MOVE_SPEED;
            break;

        case Keyboard.KEY_A:
            position.x += MOVE_SPEED;
            break;

        case Keyboard.KEY_S:
            position.z -= MOVE_SPEED;
            break;

        case Keyboard.KEY_D:
            position.x += MOVE_SPEED;
            break;
    }
}
</code>```

答:
Here is a solution that I liked (but did not try) from @KysonTyner.

You can switch on getEventKey(). This will hit your current cases and then you can wrap the whole switch statement with if (getEventKeyState()) {switch/case}. There is no need to use an event listener. – Kylon Tyner

As for what I used, I abandoned the idea of a switch entirely, as I realized that the movement speed would multiply if there were more than one direction of input.

I wanted to support multiple directions of motion for diagonal movement, so it wouldn't be "ghosting" as keys were pressed.

What I did is separate the functions, one to test keyboard input, and one to move the camera. There doesn't have to be any special logic for the key input, as it simply passes an LWJGL Vector3f to the camera move function.

Then, in camera move, I normalized that vector and altered the positions accordingly.

This is a simplified version of my Camera class for demonstration. I removed everything except translation.

```<code>package spikespaz.engine.main;

import org.lwjgl.input.Keyboard;
import org.lwjgl.util.vector.Vector3f;

// Created by spike on 7/3/2017.
public final class Camera {
    private Camera() {}

    private float moveSpeed = 0.2f;
    private Vector3f position = new Vector3f(0, 0, 0);

    public Camera(Vector3f position, Vector3f rotation) {
        this.position = position;
    }

            public void updateKeyInput() {
        Vector3f direction = new Vector3f(0, 0, 0);

        if (Keyboard.isKeyDown(Keyboard.KEY_W)) {
            direction.x = 1;
        } else if (Keyboard.isKeyDown(Keyboard.KEY_S)) {
            direction.x = -1;
        }

        if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) {
            direction.y = -1;
        } else if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) {
            direction.y = 1;
        }

        if (Keyboard.isKeyDown(Keyboard.KEY_A)) {
            direction.z = 1;
        } else if (Keyboard.isKeyDown(Keyboard.KEY_D)) {
            direction.z = -1;
        }

        translate(direction);
    }

    private void translate(Vector3f direction) {
        Vector3f normalized = direction.normalise(null);
        Vector3f.add(position, (Vector3f) normalized.scale(moveSpeed), position);
    }

    public float getMoveSpeed() {
        return moveSpeed;
    }

    public void setMoveSpeed(float moveSpeed) {
        this.moveSpeed = moveSpeed;
    }
}
</code>```

Translate is relative. In the full class I have another function to set absolute position, without the move speed.

In the above example, the input vector for translate is simply a direction. The function should coordinate that based on the movement speed for each frame.

ContentLicense: CC BY-SA 3.0

Body:
What the title says. Is it possible?
As far as I know, there is no getKeyPressed or anything of the sort. I want to use a switch case for organization (and practice) as well as speed (or so I was informed).

Basically, the switch case clause(?) is just a boolean return. But how can I check if a key is pressed based on a value passed into it without a pasta bowl of if / else statements?

Obviously this code doesn't work, but I'm looking for something like it.

public void moveCamera() {
    switch (Keyboard.isKeyDown(!!!CASE CHECKING HERE!!!)) {
        case Keyboard.KEY_W:
            position.z -= MOVE_SPEED;
            break;

        case Keyboard.KEY_A:
            position.x += MOVE_SPEED;
            break;

        case Keyboard.KEY_S:
            position.z -= MOVE_SPEED;
            break;

        case Keyboard.KEY_D:
            position.x += MOVE_SPEED;
            break;
    }
}

Body:
Here is a solution that I liked (but did not try) from @KysonTyner.

You can switch on getEventKey(). This will hit your current cases and then you can wrap the whole switch statement with if (getEventKeyState()) {switch/case}. There is no need to use an event listener. – Kylon Tyner

As for what I used, I abandoned the idea of a switch entirely, as I realized that the movement speed would multiply if there were more than one direction of input.

I wanted to support multiple directions of motion for diagonal movement, so it wouldn't be "ghosting" as keys were pressed.

What I did is separate the functions, one to test keyboard input, and one to move the camera. There doesn't have to be any special logic for the key input, as it simply passes an LWJGL Vector3f to the camera move function.

Then, in camera move, I normalized that vector and altered the positions accordingly.

This is a simplified version of my Camera class for demonstration. I removed everything except translation.

package spikespaz.engine.main;

import org.lwjgl.input.Keyboard;
import org.lwjgl.util.vector.Vector3f;

// Created by spike on 7/3/2017.
public final class Camera {
    private Camera() {}

    private float moveSpeed = 0.2f;
    private Vector3f position = new Vector3f(0, 0, 0);

    public Camera(Vector3f position, Vector3f rotation) {
        this.position = position;
    }

            public void updateKeyInput() {
        Vector3f direction = new Vector3f(0, 0, 0);

        if (Keyboard.isKeyDown(Keyboard.KEY_W)) {
            direction.x = 1;
        } else if (Keyboard.isKeyDown(Keyboard.KEY_S)) {
            direction.x = -1;
        }

        if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) {
            direction.y = -1;
        } else if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) {
            direction.y = 1;
        }

        if (Keyboard.isKeyDown(Keyboard.KEY_A)) {
            direction.z = 1;
        } else if (Keyboard.isKeyDown(Keyboard.KEY_D)) {
            direction.z = -1;
        }

        translate(direction);
    }

    private void translate(Vector3f direction) {
        Vector3f normalized = direction.normalise(null);
        Vector3f.add(position, (Vector3f) normalized.scale(moveSpeed), position);
    }

    public float getMoveSpeed() {
        return moveSpeed;
    }

    public void setMoveSpeed(float moveSpeed) {
        this.moveSpeed = moveSpeed;
    }
}

Translate is relative. In the full class I have another function to set absolute position, without the move speed.

In the above example, the input vector for translate is simply a direction. The function should coordinate that based on the movement speed for each frame.


问:
Convert unsigned char to char* and Concatenate them in C
I want to convert a value unsigned char to one of type char* passing values through a function.

This is my program:

```<code>int my_function(unsigned char param1, unsigned char param2)
{
    char* buffer_char;

    const char* mss_part_1 = "Value 1: ";
    const char* mss_part_2 = " Value 2: ";

    buffer_char = malloc(240);

    strcpy(buffer_char, mss_part_1);    //OK
    strcat(buffer_char, param1);        //ERROR
    strcat(buffer_char, mss_part_2);    //OK
    strcat(buffer_char, param2);        //ERROR

    //Desire Output: "Value 1: 1234 Value 2: 5678"
    printf("%s", buffer_char);

    free(buffer_char);
}

int main(int argc, char const *argv[])
{
    unsigned char value1[10];
    unsigned char value2[10];

    strncpy(value1, "1234", 4);
    strncpy(value2, "5678", 4);

    my_function(value1, value2);

    return 0;
}
</code>```

The problem is in the strcat() function when I try to concatenate the value as "unsigned char" but I have not found the way to convert it so I can concatenate it.

I am trying to use the strcat() function but if there was a more efficient form I would like to know.

Note: I have no problem displaying the output value.

答:
Your problem is in the function declaration and in understanding the difference between unsigned char and unsigned char[].  In your function definition:

```<code>int my_function(unsigned char param1, unsigned char param2)
</code>```

..you are stating that my_function accepts two parameters, each of type unsigned char.  To the compiler, this means that each parameter contains a single char.. which is not a pointer, but actually an 8 bit integer type.. each parameter is expected to hold a single 8 bit character.  But what you really want to pass is a pointer to an array of characters:

```<code>int my_function(unsigned char *param1, unsigned char *param2)
</code>```

or

```<code>int my_function(unsigned char param1[], unsigned char param2[])
</code>```

To the compiler, these both mean the same thing, because the name of an array (regardless of the type contained within the array) always evaluates to a pointer to the first element in the array.

So, when you define a variable:

```<code>unsigned char value1[10];
</code>```

.. you are allocating (on the stack, in this case.. since it's a local variable) an array of 10 unsigned chars, one after the other.  But when you pass or refer to value1, it evaluates as the address of the first character in the array, in other words, a pointer to the array, which would be of type unsigned char *.

The second thing you should be thinking about is, why are you using unsigned char when it seems that your text is all regular ASCII characters that are suitable for a char array type?  There is nothing wrong with unsigned char, and the compiler will often do these conversions for you anyway, but in general when you mix up types without being aware of the consequences, you can have problems.  Be aware of what types the functions you are using expect, and try to keep this consistent.

Body:
I want to convert a value unsigned char to one of type char* passing values through a function.

This is my program:

int my_function(unsigned char param1, unsigned char param2)
{
    char* buffer_char;

    const char* mss_part_1 = "Value 1: ";
    const char* mss_part_2 = " Value 2: ";

    buffer_char = malloc(240);

    strcpy(buffer_char, mss_part_1);    //OK
    strcat(buffer_char, param1);        //ERROR
    strcat(buffer_char, mss_part_2);    //OK
    strcat(buffer_char, param2);        //ERROR

    //Desire Output: "Value 1: 1234 Value 2: 5678"
    printf("%s", buffer_char);

    free(buffer_char);
}

int main(int argc, char const *argv[])
{
    unsigned char value1[10];
    unsigned char value2[10];

    strncpy(value1, "1234", 4);
    strncpy(value2, "5678", 4);

    my_function(value1, value2);

    return 0;
}

The problem is in the strcat() function when I try to concatenate the value as "unsigned char" but I have not found the way to convert it so I can concatenate it.

I am trying to use the strcat() function but if there was a more efficient form I would like to know.

Note: I have no problem displaying the output value.

Body:
Your problem is in the function declaration and in understanding the difference between unsigned char and unsigned char[].  In your function definition:

int my_function(unsigned char param1, unsigned char param2)

..you are stating that my_function accepts two parameters, each of type unsigned char.  To the compiler, this means that each parameter contains a single char.. which is not a pointer, but actually an 8 bit integer type.. each parameter is expected to hold a single 8 bit character.  But what you really want to pass is a pointer to an array of characters:

int my_function(unsigned char *param1, unsigned char *param2)

or

int my_function(unsigned char param1[], unsigned char param2[])

To the compiler, these both mean the same thing, because the name of an array (regardless of the type contained within the array) always evaluates to a pointer to the first element in the array.

So, when you define a variable:

unsigned char value1[10];

.. you are allocating (on the stack, in this case.. since it's a local variable) an array of 10 unsigned chars, one after the other.  But when you pass or refer to value1, it evaluates as the address of the first character in the array, in other words, a pointer to the array, which would be of type unsigned char *.

The second thing you should be thinking about is, why are you using unsigned char when it seems that your text is all regular ASCII characters that are suitable for a char array type?  There is nothing wrong with unsigned char, and the compiler will often do these conversions for you anyway, but in general when you mix up types without being aware of the consequences, you can have problems.  Be aware of what types the functions you are using expect, and try to keep this consistent.


问:
How to set text-decoration: underline only for specific content
I have a input tag and where I am getting input value like this.

```<code>input.value += " " + value + ";" ;
</code>```

In my css I have text-decoration: underline; but here underline is coming in "space" and ";" both the place. Is there any way I can decorate only text part.

My Code is like :

```<code>var div = document.getElementById(divID);

var myTable = '<input type="text" id="myInput"  list="myUL" onclick = "openingList()" onkeyup="openingList()" style="width:30%;" >' +
    '<div id="triggers">' + '<img class="trigger" onclick ="deleteValue()" src="css/clearT.png" id="cross" />' + '<img class="trigger" src="css/combo_arrow.png" onclick = "openingList()" id="arrow" />' + '</div>' +
    '<ul id="myUL" hidden=true>' + '<li>' + '<a href="#" ></a>' + '</li>' + '</ul>';

div.innerHTML = myTable;

function selectItem(input, value) {
    var newinput = input.value.split(';');
    newinput[newinput.length - 1] = "";
    input.value = newinput.join(";");
    input.value += " " + value + ";" + "";
}
</code>```

Current it is coming like this.

What exactly I want here

答:
Many complex and great answers.  If you want it done fast and simple:

```<code>input.value += " " + value + ";" ;
</code>```

Changes to:

CSS:

```<code>.ul {text-decoration: underline;}
</code>```

JS:

```<code>startUL = "<span class='ul'>";
endUL = "</span>";
startUL + input.value + endUL += " " + startUL + value + endUL + ";" ;
</code>```

And call it a day.  Then, once this is working nicely for you, revisit the requirements for the display to determine a better display requirement since underlining is sketchy UX when it's not:
a) a hyperlink or
b) indicative of something important to the user.

Happy coding.

ContentLicense: CC BY-SA 4.0

Body:
I have a input tag and where I am getting input value like this.

input.value += " " + value + ";" ;

In my css I have text-decoration: underline; but here underline is coming in "space" and ";" both the place. Is there any way I can decorate only text part.

My Code is like :

var div = document.getElementById(divID);

var myTable = '<input type="text" id="myInput"  list="myUL" onclick = "openingList()" onkeyup="openingList()" style="width:30%;" >' +
    '
' + '' + '' + '
' +
    '
' + '
' + '' + '
' + '
';

div.innerHTML = myTable;

function selectItem(input, value) {
    var newinput = input.value.split(';');
    newinput[newinput.length - 1] = "";
    input.value = newinput.join(";");
    input.value += " " + value + ";" + "";
}

Current it is coming like this.

What exactly I want here

Body:
Many complex and great answers.  If you want it done fast and simple:

input.value += " " + value + ";" ;

Changes to:

CSS:

.ul {text-decoration: underline;}

JS:

startUL = "<span class='ul'>";
endUL = "</span>";
startUL + input.value + endUL += " " + startUL + value + endUL + ";" ;

And call it a day.  Then, once this is working nicely for you, revisit the requirements for the display to determine a better display requirement since underlining is sketchy UX when it's not:
a) a hyperlink or
b) indicative of something important to the user.

Happy coding.


问:
Rails 4 + Devise: Validate password
Something odd is happening when someone accepts an invitation to my website, they set their initial password, but then that password is not accepted as correct in the future.  For instance, I invited myself, and then accepted the invitation and set my initial password to "foobar".

When I open the console and check the password I see:

```<code>User.find_by(email: "myemail@gmail.com").valid_password?("foobar")
=> false
</code>```

Is there a way to view my unencrypted password so that I can diagnose where it might be getting set or some other way of finding out where the password is being updated?

Devise Initializer:

```<code>Devise.setup do |config|

  config.secret_key = '*****'

  config.mailer_sender = 'admin@foobar.com'

  config.mailer = 'CustomDeviseMailer'
  require 'devise/orm/active_record'

  config.case_insensitive_keys = [:email]
  config.strip_whitespace_keys = [:email]
  config.skip_session_storage = [:http_auth]
  config.stretches = Rails.env.test? ? 1 : 10
  config.reconfirmable = true
  config.expire_all_remember_me_on_sign_out = true
  config.password_length = 8..72
  config.reset_password_within = 6.hours
  config.sign_out_via = :delete
end
</code>```

Devise Invitable Initializer:

```<code>Devise::InvitationsController.class_eval do
  def update_resource_params
    params.require(resource_name).permit(
            :email,:encrypted_password,:reset_password_token,:reset_password_sent_at,:remember_created_at,:sign_in_count,:current_sign_in_at,:last_sign_in_at,:current_sign_in_ip,:last_sign_in_ip,:created_at,:updated_at,:admin,:invitation_token,:invitation_created_at,:invitation_sent_at,:invitation_accepted_at,:invitation_limit,:invited_by_id,:invitations_count,:invited_by_type,:employee,:is_client,:location_id,:user_type, :location_id
    )
  end
end
</code>```

答:
<s>Your password won't be accepted because this line on your devise initializer:

```<code>config.password_length = 8..72
</code>```

"foobar" has only 6 characters long. Have you tried longer passwords? That's why valid_password returns false. If you want to accept passwords like "foobar" change the range for password validations.</s>

UPDATE

Permit password on your strong parameters, you're no allowing password attribute on your controller.

As a note, is very dangerous for you to add every field to your strong parameters. If you permit something like this, I could post anything to your controller easily and change sensitive data. For example, I could change the encrypted_password, reset_password_token among other fields that should never be changed. Only permit parameters that you want the user to pass, nothing else, or you can expose a huge security hole to your app. Reference.

Title: Rails 4 + Devise: Validate password

Body:
Something odd is happening when someone accepts an invitation to my website, they set their initial password, but then that password is not accepted as correct in the future.  For instance, I invited myself, and then accepted the invitation and set my initial password to "foobar".

When I open the console and check the password I see:

User.find_by(email: "myemail@gmail.com").valid_password?("foobar")
=> false

Is there a way to view my unencrypted password so that I can diagnose where it might be getting set or some other way of finding out where the password is being updated?

Devise Initializer:

Devise.setup do |config|

  config.secret_key = '*****'

  config.mailer_sender = 'admin@foobar.com'

  config.mailer = 'CustomDeviseMailer'
  require 'devise/orm/active_record'

  config.case_insensitive_keys = [:email]
  config.strip_whitespace_keys = [:email]
  config.skip_session_storage = [:http_auth]
  config.stretches = Rails.env.test? ? 1 : 10
  config.reconfirmable = true
  config.expire_all_remember_me_on_sign_out = true
  config.password_length = 8..72
  config.reset_password_within = 6.hours
  config.sign_out_via = :delete
end

Devise Invitable Initializer:

Devise::InvitationsController.class_eval do
  def update_resource_params
    params.require(resource_name).permit(
            :email,:encrypted_password,:reset_password_token,:reset_password_sent_at,:remember_created_at,:sign_in_count,:current_sign_in_at,:last_sign_in_at,:current_sign_in_ip,:last_sign_in_ip,:created_at,:updated_at,:admin,:invitation_token,:invitation_created_at,:invitation_sent_at,:invitation_accepted_at,:invitation_limit,:invited_by_id,:invitations_count,:invited_by_type,:employee,:is_client,:location_id,:user_type, :location_id
    )
  end
end

Body:
<s>Your password won't be accepted because this line on your devise initializer:

config.password_length = 8..72

"foobar" has only 6 characters long. Have you tried longer passwords? That's why valid_password returns false. If you want to accept passwords like "foobar" change the range for password validations.</s>

UPDATE

Permit password on your strong parameters, you're no allowing password attribute on your controller.

As a note, is very dangerous for you to add every field to your strong parameters. If you permit something like this, I could post anything to your controller easily and change sensitive data. For example, I could change the encrypted_password, reset_password_token among other fields that should never be changed. Only permit parameters that you want the user to pass, nothing else, or you can expose a huge security hole to your app. Reference.


问:
Why can't I reuse "unapply" without repeating the method signature
The following Scala code compiles fine:

```<code>val f = (input: String) => Some("result")
object Extract {
   def unapply(input: String): Option[String] = f(input)
}
val Extract(result) = "a string"
</code>```

But if I replace the extractor by:

```<code>object Extract {
   def unapply = f
}
</code>```

Then compilation fails with:

```<code>error: an unapply result must have a member `def isEmpty: Boolean
val Extract(result) = "a string"
    ^
</code>```

Why? Where does def isEmpty: Boolean come from?

答:
To answer your first question - isEmpty comes from internals of Option type.

def unapply = f means - create a parameterless method that returns a function. This is not a method by itself and thus you have an error.

You can further read about difference between function and method in Scala there: Difference between method and function in Scala

Body:
The following Scala code compiles fine:

val f = (input: String) => Some("result")
object Extract {
   def unapply(input: String): Option[String] = f(input)
}
val Extract(result) = "a string"

But if I replace the extractor by:

object Extract {
   def unapply = f
}

Then compilation fails with:

error: an unapply result must have a member `def isEmpty: Boolean
val Extract(result) = "a string"
    ^

Why? Where does def isEmpty: Boolean come from?


问:
How to get the URL of an ics file from a webpage containing a calendar?
For example, I have the following web page containing a calendar:

https://meded.hms.harvard.edu/calendar

Below is my code attempt to download the ics:

```<code>import urllib2

url = 'https://meded.hms.harvard.edu/calendar'

response = urllib2.urlopen(url)
webContent = response.read()

f = open('calendar.ics', 'w')
f.write(webContent)
f.close
</code>```

However, because I did not specify the specific URL of the .ics file, it obviously downloads a file with nothing in it so I can't open it with something like iCal. My question is, how can I get the specific URL of the .ics file so I can download it? I tried searching for how to download a specific file on stack overflow already but all the answers had URLs containing the file, so I did not know what to do. Thanks.

答:
This approach gave me a file that seems to work on my mailer which is Mozilla Thunderbird.</p>

```<code>>>> import requests
>>> page = requests.get('https://meded.hms.harvard.edu/calendar').content
>>> import bs4
>>> soup = bs4.BeautifulSoup(page, 'lxml')
>>> link = soup.find('a', attrs={'class': 'subscribe'})
>>> link
<a class="subscribe" href="https://meded.hms.harvard.edu/calendar/upcoming/all/export.ics">subscribe</a>
>>> link.attrs['href']
'https://meded.hms.harvard.edu/calendar/upcoming/all/export.ics'
>>> ics = requests.get(link.attrs['href']).content
>>> open('med_school.ics', 'wb').write(ics)
1699
</code>```

Body:
For example, I have the following web page containing a calendar:

https://meded.hms.harvard.edu/calendar

Below is my code attempt to download the ics:

import urllib2

url = 'https://meded.hms.harvard.edu/calendar'

response = urllib2.urlopen(url)
webContent = response.read()

f = open('calendar.ics', 'w')
f.write(webContent)
f.close

However, because I did not specify the specific URL of the .ics file, it obviously downloads a file with nothing in it so I can't open it with something like iCal. My question is, how can I get the specific URL of the .ics file so I can download it? I tried searching for how to download a specific file on stack overflow already but all the answers had URLs containing the file, so I did not know what to do. Thanks.

Body:
This approach gave me a file that seems to work on my mailer which is Mozilla Thunderbird.

>>> import requests
>>> page = requests.get('https://meded.hms.harvard.edu/calendar').content
>>> import bs4
>>> soup = bs4.BeautifulSoup(page, 'lxml')
>>> link = soup.find('a', attrs={'class': 'subscribe'})
>>> link
<a class="subscribe" href="https://meded.hms.harvard.edu/calendar/upcoming/all/export.ics">subscribe</a>
>>> link.attrs['href']
'https://meded.hms.harvard.edu/calendar/upcoming/all/export.ics'
>>> ics = requests.get(link.attrs['href']).content
>>> open('med_school.ics', 'wb').write(ics)
1699


问:
Fastest way to read a binary file with a defined format?
I have large binary data files that have a predefined format, originally written by a Fortran program as little endians. I would like to read these files in the fastest, most efficient manner, so using the array package seemed right up my alley as suggested in Improve speed of reading and converting from binary file?.

The problem is the pre-defined format is non-homogeneous. It looks something like this:
['<2i','<5d','<2i','<d','<i','<3d','<2i','<3d','<i','<d','<i','<3d']

with each integer i taking up 4 bytes, and each double d taking 8 bytes.

Is there a way I can still use the super efficient array package (or another suggestion) but with the right format?

答:
Take a look at the documentation for numpy's fromfile function: https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.fromfile.html and https://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html#arrays-dtypes-constructing

Simplest example:

```<code>import numpy as np
data = np.fromfile('binary_file', dtype=np.dtype('<i8, ...'))
</code>```

Read more about "Structured Arrays" in numpy and how to specify their data type(s) here: https://docs.scipy.org/doc/numpy/user/basics.rec.html#

Body:
Take a look at the documentation for numpy's fromfile function: https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.fromfile.html and https://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html#arrays-dtypes-constructing

Simplest example:

import numpy as np
data = np.fromfile('binary_file', dtype=np.dtype('<i8, ...'))

Read more about "Structured Arrays" in numpy and how to specify their data type(s) here: https://docs.scipy.org/doc/numpy/user/basics.rec.html#


问:
How to show html tags from javascript variable to a div id?
I want to show the testTag variable to the div after i click the button. When i clicked it only shows the label of the option tag and not the full select tags.
Please help! This is my code.

function showDropdown() {

 var textTag = "<select>";
 var textOptions = ["option1","option2","option3"];

 for (i = 0; i < textOptions.length; i++) {
  textTag += '<options value="' + textOptions[i] + '">' + textOptions[i] + "</options>";

 }

 textTag += "</select>";

 document.getElementById("dropdownTest").innerHTML= textTag;
 console.log(textTag);
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Show dropdown</title>
</head>

<body>
<input type="button" id="showDrop" value="Show dropdown" onClick="showDropdown()">
<div id="dropdownTest"></div>

</body>
</html></code>```

答:
It's called <option>, not <options>:

function showDropdown() {
    var textTag = "<select>";
    var textOptions = ["option1","option2","option3"];

    // declare "i"!
    for (var i = 0; i < textOptions.length; i++) {
        // change this line
        textTag += '<option value="' + textOptions[i] + '">' + textOptions[i] + "</option>";
    }

    textTag += "</select>";

    document.getElementById("dropdownTest").innerHTML = textTag;
    console.log(textTag);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Show dropdown</title>
  </head>
  <body>
    <input type="button" id="showDrop" value="Show dropdown" onClick="showDropdown()">
    <div id="dropdownTest"></div>
  </body>
</html></code>```

Body:
I want to show the testTag variable to the div after i click the button. When i clicked it only shows the label of the option tag and not the full select tags.
Please help! This is my code.

function showDropdown() {

 var textTag = "<select>";
 var textOptions = ["option1","option2","option3"];

 for (i = 0; i < textOptions.length; i++) {
  textTag += '<options value="' + textOptions[i] + '">' + textOptions[i] + "</options>";

 }

 textTag += "</select>";

 document.getElementById("dropdownTest").innerHTML= textTag;
 console.log(textTag);
 }

<!doctype html>

<meta charset="utf-8">
<title>Show dropdown</title>

<input type="button" id="showDrop" value="Show dropdown" onClick="showDropdown()">

Body:
It's called <option>, not <options>:

function showDropdown() {
    var textTag = "<select>";
    var textOptions = ["option1","option2","option3"];

    // declare "i"!
    for (var i = 0; i < textOptions.length; i++) {
        // change this line
        textTag += '<option value="' + textOptions[i] + '">' + textOptions[i] + "</option>";
    }

    textTag += "</select>";

    document.getElementById("dropdownTest").innerHTML = textTag;
    console.log(textTag);
}

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Show dropdown</title>
  </head>
  <body>
    <input type="button" id="showDrop" value="Show dropdown" onClick="showDropdown()">
    <div id="dropdownTest"></div>
  </body>
</html>


问:
Neo4j how to create a property set, with out duplicate values unlike a List
I have a :hobby relation between :User nodes.

The hobby relation contains a List property { hobbies:['football','hockey'] }

Now I am iterating through a data stream and i want to uniquely merge the hobbies into this List (Like a set). I tried using coalesce like this:

```<code>MERGE  (from)-[rel:hobbies]->(to)
set rel.hobbies= COALESCE(rel.hobbies, []) + 'football';
</code>```

The problem is that now my property contains duplicates

{ hobbies:['football','hockey','football'] }

How can i avoid duplicates?

答:
This Cypher query should work without need of APOC procedures.

```<code>MERGE (from)-[rel:hobbies]->(to)
WITH rel, COALESCE(rel.hobbies, []) + 'football' AS hobbies
UNWIND hobbies as r
WITH rel, collect(distinct r) AS unique
set rel.hobbies = unique
</code>```

This query use UNWIND to expand the hobbies array and after it collect the unique hobbies into an variable called unique. If you don't have APOC procedures in your Neo4j Server use this query.

Body:
I have a :hobby relation between :User nodes.

The hobby relation contains a List property { hobbies:['football','hockey'] }

Now I am iterating through a data stream and i want to uniquely merge the hobbies into this List (Like a set). I tried using coalesce like this:

MERGE  (from)-[rel:hobbies]->(to)
set rel.hobbies= COALESCE(rel.hobbies, []) + 'football';

The problem is that now my property contains duplicates

{ hobbies:['football','hockey','football'] }

How can i avoid duplicates?

Body:
This Cypher query should work without need of APOC procedures.

MERGE (from)-[rel:hobbies]->(to)
WITH rel, COALESCE(rel.hobbies, []) + 'football' AS hobbies
UNWIND hobbies as r
WITH rel, collect(distinct r) AS unique
set rel.hobbies = unique

This query use UNWIND to expand the hobbies array and after it collect the unique hobbies into an variable called unique. If you don't have APOC procedures in your Neo4j Server use this query.


问:
Is there a way to keep a weak reference on an object and control its lifetime as well?

shared_ptr/weak_ptr allow to keep a weak reference on an object but I can't prevent someone who receives a weak to convert it and store it as a shared. So I lose the control of the object lifetime .

unique_ptr is ok to control the lifetime of the object, but does not have a weak reference mechanism.

I couldn't find a standard way to have the benefits of lifetime control and weak reference at the same time. I can't believe that I'm the only one to encounter this problem.

Is there anything in the standard or in boost that would allow this behavior?
Or is there a pattern allowing this without rewriting a complete smart_ptr class?

答:
Ok, there is no standard way to do that.

The solution is to add unique_ids to all the objects, and everybody who needs a weak reference store an id.

Then we have a Manager that keeps a map of unique_ptr of those objects, with a public method findById(id).

This way, the memory allocation is fully controlled by the manager, and anybody can keep weak references on it.


问:
Jhipster: how to save multiple records in one entity
I need to save multiple records in loop. In dialog.js i m getting my correct object which i m sending to service js to save. calling service js in loop only. while i m running this service js save function is called after dialog js loop. how is this happening? How can i save data in loop?

Dialog-controller.js

```<code>function save () {
     vm.isSaving = true;

     for(var i in resourceData)
     {

         vm.timesheet.sunday=resourceData[i].sunday;
         vm.timesheet.monday=resourceData[i].monday;
         vm.timesheet.tuesday=resourceData[i].tuesday;
         vm.timesheet.wednesday=resourceData[i].wednesday;
         vm.timesheet.thursday=resourceData[i].thursday;
         vm.timesheet.friday=resourceData[i].friday;
         vm.timesheet.saturday=resourceData[i].saturday;
         vm.timesheet.resource=resourceData[i].saturday;
         vm.timesheet.resource=resourceData[i];

        Timesheet.save(vm.timesheet,onSaveSuccess, onSaveError);

 }
</code>```

this is my timesheet.service.js

```<code>(function() {
    'use strict';
    angular
        .module('timesheetApp')
        .factory('Timesheet', Timesheet);

    Timesheet.$inject = ['$resource', 'DateUtils'];

    function Timesheet ($resource, DateUtils) {
        var resourceUrl =  'api/timesheets/:id';

        return $resource(resourceUrl, {}, {
            'query': { method: 'GET', isArray: true},
            'save': {
                method: 'POST',
                isArray: false,
                transformRequest: function (data) {
                    alert("123");
                    var copy = angular.copy(data);
                    return angular.toJson(copy);
                }
            }
        });
    }
})();
</code>```

答:
You might have to write a recursive function, depending upon the promise returned.

```<code>Timesheet.save(vm.timesheet,onSaveSuccess, onSaveError);
</code>```

This returns a promise which calls you onSaveSuccess method.

in the function

```<code>function onSaveSuccess(){
// Need some recursive logic
}
</code>```

Or try to implement this answer.

Need to call angular http service from inside loop and wait for the value of the service to return before executing code below call

Body:
I need to save multiple records in loop. In dialog.js i m getting my correct object which i m sending to service js to save. calling service js in loop only. while i m running this service js save function is called after dialog js loop. how is this happening? How can i save data in loop?

Dialog-controller.js

function save () {
     vm.isSaving = true;

     for(var i in resourceData)
     {

         vm.timesheet.sunday=resourceData[i].sunday;
         vm.timesheet.monday=resourceData[i].monday;
         vm.timesheet.tuesday=resourceData[i].tuesday;
         vm.timesheet.wednesday=resourceData[i].wednesday;
         vm.timesheet.thursday=resourceData[i].thursday;
         vm.timesheet.friday=resourceData[i].friday;
         vm.timesheet.saturday=resourceData[i].saturday;
         vm.timesheet.resource=resourceData[i].saturday;
         vm.timesheet.resource=resourceData[i];

        Timesheet.save(vm.timesheet,onSaveSuccess, onSaveError);

 }

this is my timesheet.service.js

(function() {
    'use strict';
    angular
        .module('timesheetApp')
        .factory('Timesheet', Timesheet);

    Timesheet.$inject = ['$resource', 'DateUtils'];

    function Timesheet ($resource, DateUtils) {
        var resourceUrl =  'api/timesheets/:id';

        return $resource(resourceUrl, {}, {
            'query': { method: 'GET', isArray: true},
            'save': {
                method: 'POST',
                isArray: false,
                transformRequest: function (data) {
                    alert("123");
                    var copy = angular.copy(data);
                    return angular.toJson(copy);
                }
            }
        });
    }
})();

Body:
You might have to write a recursive function, depending upon the promise returned.

Timesheet.save(vm.timesheet,onSaveSuccess, onSaveError);

This returns a promise which calls you onSaveSuccess method.

in the function

function onSaveSuccess(){
// Need some recursive logic
}

Or try to implement this answer.

Need to call angular http service from inside loop and wait for the value of the service to return before executing code below call


问:
Jenkins-CLI/Rest API to change the credentials in the created Jenkins Job
I am creating a Jenkins Job using the Jenkins CLI/REST API, by copying Jenkins Job template, I am good with this.

Now I need to change the credentials in newly created Jenkins Job(like GIT Credentials, Artifactory, Docker), the created Jenkins Job have someones credentials, i need mine there)

Is there any API/provision to do this?

答:
Below jenkins Rest API is used to add the credentials to the user

curl --user username:password -XGET 'http://localhost:8080/credentials/store/system/domain/_/createCredentials' --data-urlencode 'json={
  "": "0",
  "credentials": {
    "scope": "GLOBAL",
    "id": "apicredentials",
    "username": "username",
    "password": "password",
    "description": "apicredentials",
    "stapler-class": "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl"
  }
}'

Once you add the credentials to the jenkins, change the cloned xml with the latest username and ID, and push the updated xml to create new jenkins job.


问:
How read the first and the last line of a file in scala
I am reading a file that contain the following:

```<code>16,44,34
16,47,18
22,44,28
22,47,24
</code>```

but I just want to read the first and the last line of the file,
In this moment I am reading the file as an Iterator:

```<code> while (in2.hasNext) {
        val s  = in2.next(',').toInt
        val p = in2.next(',').toInt
        val o  = in2.next('\n').toInt
 }
</code>```

but I am reading the whole file, exist a way in scala to do it?

答:
Well, you can write it a little nicer, and save on not having to parse every line in the file, but you will still have to read them all, unless you are willing to do some acrobatics with random access files and binary data (probably, not worth the effort, unless the file is truly huge).

```<code>   val lines = Source.fromFile("input_file.csv").getLines
   val firstLine = if(lines.hasNext) Some(lines.next) else None
   val lastLine = lines.foldLeft(Option.empty[String]) { case (_, line) => Some(line) }
   val spos: Seq[Seq[Int]] = (firstLine ++ lastLine).map(_.split(",").map(_.toInt))

   // next line will fail if there are fewer than two lines in the file
   // or if either first or last line doesn't have exactly three comma-separated fields
   // I am just putting it here to illustrate how you could extract the parsed data

   val Seq(Seq(s1, p1, o1), Seq(s2, p2, o2)) = spos
</code>```

Update

Ok, if you really don't want to have to read through the entire file, you can try something like this (this is a crude approach, based on the fact that your lines are all short, so I can be sure that if I land somewhere ~1000 bytes from the end of the file, I'll definitely be well before the start of the last line.

```<code>   val file = new RandomAccessFile("input_file.csv", "r")
   val firstLine = Option(file.readLine)
   if(file.length > 1024 + firstLine.fold(0)(_.length))
      file.skipBytes(file.length - 1024)
   val lastLine = Iterator.continually(file.readLine)
     .takeWhile(_ != null)
     .foldLeft(Option.empty[String]) { case (_, line) => line }
</code>```

(the rest of the earlier snippet can stay the same).

Body:
I am reading a file that contain the following:

16,44,34
16,47,18
22,44,28
22,47,24

but I just want to read the first and the last line of the file,
In this moment I am reading the file as an Iterator:

 while (in2.hasNext) {
        val s  = in2.next(',').toInt
        val p = in2.next(',').toInt
        val o  = in2.next('\n').toInt
 }

but I am reading the whole file, exist a way in scala to do it?

Body:
Well, you can write it a little nicer, and save on not having to parse every line in the file, but you will still have to read them all, unless you are willing to do some acrobatics with random access files and binary data (probably, not worth the effort, unless the file is truly huge).

   val lines = Source.fromFile("input_file.csv").getLines
   val firstLine = if(lines.hasNext) Some(lines.next) else None
   val lastLine = lines.foldLeft(Option.empty[String]) { case (_, line) => Some(line) }
   val spos: Seq[Seq[Int]] = (firstLine ++ lastLine).map(_.split(",").map(_.toInt))

   // next line will fail if there are fewer than two lines in the file
   // or if either first or last line doesn't have exactly three comma-separated fields
   // I am just putting it here to illustrate how you could extract the parsed data

   val Seq(Seq(s1, p1, o1), Seq(s2, p2, o2)) = spos

Update

Ok, if you really don't want to have to read through the entire file, you can try something like this (this is a crude approach, based on the fact that your lines are all short, so I can be sure that if I land somewhere ~1000 bytes from the end of the file, I'll definitely be well before the start of the last line.

   val file = new RandomAccessFile("input_file.csv", "r")
   val firstLine = Option(file.readLine)
   if(file.length > 1024 + firstLine.fold(0)(_.length))
      file.skipBytes(file.length - 1024)
   val lastLine = Iterator.continually(file.readLine)
     .takeWhile(_ != null)
     .foldLeft(Option.empty[String]) { case (_, line) => line }

(the rest of the earlier snippet can stay the same).


问:
Data from a DataGridView Configured on Another Form
I have Form1 that has a dataGridView and a button to add contents to that Grid. When selecting this button, I call Form2 which has 2 TextBox and a ComboBox to populate the Name, Directory and Format (for example), plus an OK button to add the row to the dataGridView on Form1.

When I get back on Form1, the dataGridView must be showing the content entered. What happens is that my Grid has three columns: Name, Format and a button column to, when clicking it, reload that screen of Form2 with the previously filled information loaded again in each field to be able to change or just consult.

Firstly I tried to create a function to add the lines to my Grid by parameters, as shown in the code below:

Eu tenho o Form1 que possui uma dataGridView e um botão para adicionar conteúdos nessa Grid. Ao selecionar esse botão, eu chamo o Form2 que possui 2 TextBox e um ComboBox para preencher o Nome, Diretório e Formato (por exemplo), além de um botão OK para adicionar a linha a dataGridView na Form1.

Form 1

```<code>public Form1()
{
    InitializeComponent();
}

public void AddRows(string name, string path)
{
    dataGridView1.Rows.Add(name, path);
    dataGridView1.Update();
}
</code>```

Form 2

```<code>public Form2()
{
    InitializeComponent();
}

private void bt1_Click(object sender, EventArgs e)
{
    var nome = txt_name.Text;
    var path = txt_path.Text;

    var form1 = new Form1();
    form1.AddRows(name, path);
}
</code>```

However, it ended up not working, showing nothing on the Grid. So I thought about creating a class with a name, path and format method (get and set for each) to store everything in a list of objects (I think that's it, forgive me if I'm wrong because I'm a beginner). Or save to a DataSet. But then I thought, I instantiate the class in my Form2 and pass the values filled in the fields, but then, what do I do in my Form1?

I think it's all very confusing, I'd appreciate it if someone could explain a clearer method of resolving this situation and please be very specific since I'm a beginner.

答:
A quick fix to this problem is to use a modal dialog and tag/pass the information through to a list in Form1.

```<code>        frmNewConfig f = new frmNewConfig();
        if (f.ShowDialog() == DialogResult.OK)
        {
            Object c = new Object();
            c = (Object)f.Tag;
            _yourList.Add(c);
          **example**
             valueA = txtValueA.Text;
             valueB = txtValueB.Text;
        }
</code>```

Now in Form1 you should have a means of binding your list to a DGV such as:

```<code>yourDGV.DataSource = typeof(Object);
   //OR
yourDGV.DataSource = yourList;
</code>```

Don't forget to create an instance of the list in your frmLoad before trying to assign objects to it.

Body:
I have Form1 that has a dataGridView and a button to add contents to that Grid. When selecting this button, I call Form2 which has 2 TextBox and a ComboBox to populate the Name, Directory and Format (for example), plus an OK button to add the row to the dataGridView on Form1.

When I get back on Form1, the dataGridView must be showing the content entered. What happens is that my Grid has three columns: Name, Format and a button column to, when clicking it, reload that screen of Form2 with the previously filled information loaded again in each field to be able to change or just consult.

Firstly I tried to create a function to add the lines to my Grid by parameters, as shown in the code below:

Eu tenho o Form1 que possui uma dataGridView e um botão para adicionar conteúdos nessa Grid. Ao selecionar esse botão, eu chamo o Form2 que possui 2 TextBox e um ComboBox para preencher o Nome, Diretório e Formato (por exemplo), além de um botão OK para adicionar a linha a dataGridView na Form1.

Form 1

public Form1()
{
    InitializeComponent();
}

public void AddRows(string name, string path)
{
    dataGridView1.Rows.Add(name, path);
    dataGridView1.Update();
}

Form 2

public Form2()
{
    InitializeComponent();
}

private void bt1_Click(object sender, EventArgs e)
{
    var nome = txt_name.Text;
    var path = txt_path.Text;

    var form1 = new Form1();
    form1.AddRows(name, path);
}

However, it ended up not working, showing nothing on the Grid. So I thought about creating a class with a name, path and format method (get and set for each) to store everything in a list of objects (I think that's it, forgive me if I'm wrong because I'm a beginner). Or save to a DataSet. But then I thought, I instantiate the class in my Form2 and pass the values filled in the fields, but then, what do I do in my Form1?

I think it's all very confusing, I'd appreciate it if someone could explain a clearer method of resolving this situation and please be very specific since I'm a beginner.

Body:
A quick fix to this problem is to use a modal dialog and tag/pass the information through to a list in Form1.

        frmNewConfig f = new frmNewConfig();
        if (f.ShowDialog() == DialogResult.OK)
        {
            Object c = new Object();
            c = (Object)f.Tag;
            _yourList.Add(c);
          **example**
             valueA = txtValueA.Text;
             valueB = txtValueB.Text;
        }

Now in Form1 you should have a means of binding your list to a DGV such as:

yourDGV.DataSource = typeof(Object);
   //OR
yourDGV.DataSource = yourList;

Don't forget to create an instance of the list in your frmLoad before trying to assign objects to it.


问:
CSS and JQuery not working?
So the CSS on my site doesn't seem to be working, at least the updates I made. I want to create a height transition effect with the css transition property and the JQuery.css property but my applied changes aren't working on my site.</p>

```<code>.blog{
    transition: 1500ms ease-in-out !important;
    width: 100%;
    height: 0% !important;
    background-color: #8394EB;
    margin: 0;
    padding: 10px 40px;
    color: white !important;
}

$('.blog').css('height','100%');
</code>```

答:
Setting height using % might not work in a lot of cases.
Try to use px, rem, or vh instead in both css and your js code and see if it makes any difference.

```<code>.blog{
    transition: 1500ms ease-in-out !important;
    width: 100%;
    height: 0px;
    background-color: #8394EB;
    margin: 0;
    padding: 10px 40px;
    color: white !important;
}

$('.blog').css('height','10vh');
</code>```

Title: CSS and JQuery not working?

Body:
So the CSS on my site doesn't seem to be working, at least the updates I made. I want to create a height transition effect with the css transition property and the JQuery.css property but my applied changes aren't working on my site.

.blog{
    transition: 1500ms ease-in-out !important;
    width: 100%;
    height: 0% !important;
    background-color: #8394EB;
    margin: 0;
    padding: 10px 40px;
    color: white !important;
}

$('.blog').css('height','100%');

Body:
Setting height using % might not work in a lot of cases.
Try to use px, rem, or vh instead in both css and your js code and see if it makes any difference.

.blog{
    transition: 1500ms ease-in-out !important;
    width: 100%;
    height: 0px;
    background-color: #8394EB;
    margin: 0;
    padding: 10px 40px;
    color: white !important;
}

$('.blog').css('height','10vh');


问:
where does session save?
I would like to know where PHP session data is saved; is it in client browser? or on the server?

When I disable cookies in my browser setting, PHP can't save session data, but in php.ini, I can change the session save path.

Is session data stored on the server or client browser?

答:
Blockquote "Is session data stored on the server or client browser?"

It makes me think of a valet parking system. The valet (server) keeps your car (session data), but he/she gives you a ticket (session id) to hang onto which proves that the car is yours when you need access to it. If you lose your ticket (by deleting your cache, or closing the browser), your car (session data) is as good as gone since you can't prove it's your car anymore.

Okay, it's just an analogy...and breaks down quickly. E.g. you don't actually own your session information like you do your car. And you don't get to drive it away.

Title: where does session save?


问:
Android: how can you determine the actual mobile carrier name?
I have an app that tries to determine the quality of the mobile network in various locations, and then associate it with which network is in use on the phone.

To get the mobile carrier, I am using

```<code>TelephonyManager manager = (TelephonyManager)mContext.getSystemService(
  Context.TELEPHONY_SERVICE);
String carrierName = manager.getNetworkOperatorName();
</code>```

This generally works, but in some cases, I get the result, "Fi Network".  Since Google Fi switches between T-Mobile, Sprint and US Celluar in the United States, I'd like to know which of the actual carriers is used, so I can use it to determine the quality of the network.

Is there any API that can tell me which of these carriers the phone is actually using?

答: TelephonyManager.getSimOperator() will return MCC & MNC codes which should uniquely identify a carrier, you can easily find lists online that maps MCC+MNC to operators names.

Body:
I have an app that tries to determine the quality of the mobile network in various locations, and then associate it with which network is in use on the phone.

To get the mobile carrier, I am using

TelephonyManager manager = (TelephonyManager)mContext.getSystemService(
  Context.TELEPHONY_SERVICE);
String carrierName = manager.getNetworkOperatorName();

This generally works, but in some cases, I get the result, "Fi Network".  Since Google Fi switches between T-Mobile, Sprint and US Celluar in the United States, I'd like to know which of the actual carriers is used, so I can use it to determine the quality of the network.

Is there any API that can tell me which of these carriers the phone is actually using?


问:
How to use standard SimpsonIntegrator in import org.apache.commons.math3.analysis.integration.SimpsonIntegrator;
```<code>public double evalute(double distance){

    /**
     * equation (3.2)
     */
    this.from = 0;
    this.to = distance;
    this.n = 2;
    return - 10 * Math.log10(Math.exp(-IntSimpson(this.from, this.to, this.n)));
}
</code>```

There is IntSimpson() function i designed manually, but I want to use  standard library! How can i do it and where it can be found?

答:
It works!

```<code>final SimpsonIntegrator si = new SimpsonIntegrator();
final double result1 = si.integrate(10, x -> 2*Math.pow(x, 1), 0.0, 10.0);
System.out.println(result1 + " should be 100.0");
final double result2 = si.integrate(1000, x -> Math.sin(x), 0.0, Math.PI);
System.out.println(result2 + " should be 2.0000...");
</code>```

Thanks Javier Martín !

Body:
public double evalute(double distance){

    /**
     * equation (3.2)
     */
    this.from = 0;
    this.to = distance;
    this.n = 2;
    return - 10 * Math.log10(Math.exp(-IntSimpson(this.from, this.to, this.n)));
}

There is IntSimpson() function i designed manually, but I want to use  standard library! How can i do it and where it can be found?

Body:
It works!

final SimpsonIntegrator si = new SimpsonIntegrator();
final double result1 = si.integrate(10, x -> 2*Math.pow(x, 1), 0.0, 10.0);
System.out.println(result1 + " should be 100.0");
final double result2 = si.integrate(1000, x -> Math.sin(x), 0.0, Math.PI);
System.out.println(result2 + " should be 2.0000...");

Thanks Javier Martín !


问:
Finding all permutations of numbers plucked from an array which sum to 16
I would like to find all the permutations of plucking 3, 4 or 5 numbers from [2,3,4,5,6,7,8], repeats allowed, such that their sum is 16. So [8,5,3], [8,3,5] and [4,3,3,3,3] are valid permutations. Also circular permutations should be removed so [3,3,3,3,4] wouldn't also be added to the answer.
I can do this in Ruby without allowing repeats like this:

```<code>d = [2,3,4,5,6,7,8]
number_of_divisions = [3,4,5]
number_of_divisions.collect do |n|
  d.permutation(n).to_a.reject do |p|
    p[0..n].inject(0) { |sum,x| sum + x } != 16
  end
end
</code>```

How could I allow repeats so that [3,3,3,3,4] was included?

Body:
I would like to find all the permutations of plucking 3, 4 or 5 numbers from [2,3,4,5,6,7,8], repeats allowed, such that their sum is 16. So [8,5,3], [8,3,5] and [4,3,3,3,3] are valid permutations. Also circular permutations should be removed so [3,3,3,3,4] wouldn't also be added to the answer.
I can do this in Ruby without allowing repeats like this:

d = [2,3,4,5,6,7,8]
number_of_divisions = [3,4,5]
number_of_divisions.collect do |n|
  d.permutation(n).to_a.reject do |p|
    p[0..n].inject(0) { |sum,x| sum + x } != 16
  end
end

How could I allow repeats so that [3,3,3,3,4] was included?

Body:
There are far fewer repeated combinations than repeated permutations, so let's find the repeated combinations that sum to the given value, then permute each of those. Moreover, by applying uniq at each of several steps of the calculation we can significantly reduce the number of repeated combinations and permutations considered.

Code

require 'set'

def rep_perms_for_all(arr, n_arr, tot)
  n_arr.flat_map { |n| rep_perms_for_1(arr, n, tot) }
end

def rep_perms_for_1(arr, n, tot)
   rep_combs_to_rep_perms(rep_combs_for_1(arr, n, tot)).uniq
end

def rep_combs_for_1(arr, n, tot)
  arr.repeated_combination(n).uniq.select { |c| c.sum == tot }
end

def rep_combs_to_rep_perms(combs)
  combs.flat_map { |c| comb_to_perms(c) }.uniq
end

def comb_to_perms(comb)
  comb.permutation(comb.size).uniq.uniq do |p|
    p.size.times.with_object(Set.new) { |i,s| s << p.rotate(i) }
  end
end

Examples

rep_perms_for_all([2,3,4,5], [3], 12)
  #=> [[2, 5, 5], [3, 4, 5], [3, 5, 4], [4, 4, 4]]
rep_perms_for_all([2,3,4,5,6,7,8], [3,4,5], 16).size
  #=> 93
rep_perms_for_all([2,3,4,5,6,7,8], [3,4,5], 16)
  #=> [[2, 6, 8], [2, 8, 6], [2, 7, 7], [3, 5, 8], [3, 8, 5], [3, 6, 7],
  #    [3, 7, 6], [4, 4, 8], [4, 5, 7], [4, 7, 5], [4, 6, 6], [5, 5, 6],
  #    [2, 2, 4, 8], [2, 2, 8, 4], [2, 4, 2, 8], [2, 2, 5, 7], [2, 2, 7, 5],
  #    [2, 5, 2, 7], [2, 2, 6, 6], [2, 6, 2, 6], [2, 3, 3, 8], [2, 3, 8, 3],
  #    ...
  #    [3, 3, 3, 7], [3, 3, 4, 6], [3, 3, 6, 4], [3, 4, 3, 6], [3, 3, 5, 5],
  #    [3, 5, 3, 5], [3, 4, 4, 5], [3, 4, 5, 4], [3, 5, 4, 4], [4, 4, 4, 4],
  #    ...
  #    [2, 2, 4, 5, 3], [2, 2, 5, 3, 4], [2, 2, 5, 4, 3], [2, 3, 2, 4, 5],
  #    [2, 3, 2, 5, 4], [2, 3, 4, 2, 5], [2, 3, 5, 2, 4], [2, 4, 2, 5, 3],
  #    ...
  #    [2, 5, 3, 3, 3], [2, 3, 3, 4, 4], [2, 3, 4, 3, 4], [2, 3, 4, 4, 3],
  #    [2, 4, 3, 3, 4], [2, 4, 3, 4, 3], [2, 4, 4, 3, 3], [3, 3, 3, 3, 4]]

Explanation

rep_combs_for_1 uses the method Enumerable#sum, which made its debut in Ruby v2.4. For earlier versions, use c.reduce(:0) == tot.

In comb_to_perms, the first uniq simply removes duplicates. The second uniq, with a block, removes all but one of the p.size elements (arrays) that can be obtained by rotating any of the other p-1 elements. For example,

p = [1,2,3]
p.size.times.with_object(Set.new) { |i,s| s << p.rotate(i) }
  #=> #<Set: {[1, 2, 3], [2, 3, 1], [3, 1, 2]}>


问:
POST 500 Error Bot Emulator Localhost for IIS hosted Bot
I have used IIS to locally host my bot like so: https: //localhost/MyBot. Currently when I try to connect to my bot in the bot emulator I get a POST 500 error, and am unable to send messages. I am new to this and most documentation for publishing a bot to a local server is limited. I can however successfully open this link from my browser.

Am I experiencing this error because I don't have the https: //localhost/Bridget/api/messages directory/url? I tried creating Virtual Directories in IIS but that did not help solve my problem. Do I need tunneling software? Is there a simple tutorial for deploying a bot locally using IIS and connecting to it via the bot emulator?

Here is the error I see in the emulator:

Bot Emulator Error

Using ngrok tunneling software this is what I see:

NGROK Bot Emulator Error

Here is the code that processing incoming POST messages:

```<code>/// <summary>
/// POST: api/Messages
/// Receive a message from a user and reply to it
/// </summary>
public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
    if (activity.Type == ActivityTypes.Message)
    {
        // Strip any @mentions
        Mention[] m = activity.GetMentions();
        for (int x = 0; x < m.Length; x++)
        {
            if (m[x].Mentioned.Id == activity.Recipient.Id)
            {
                if (m[x].Text != null)
                {
                    activity.Text = activity.Text.Replace(m[x].Text, "");
                }
            }
        }

        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

        await Conversation.SendAsync(activity, () => new Dialogs.RootDialog());
    }
    else if (activity.Type == ActivityTypes.Invoke)
    {
            // Some Code...
    }
    else
    {
        HandleSystemMessage(activity);
    }
    var response = Request.CreateResponse(HttpStatusCode.OK);
    return response;
}
</code>```

答:
Am I experiencing this error because I don't have the https: //localhost/Bridget/api/messages directory/url?

Both your screenshots show you trying to connect to /api/messages, which you say you don't have, so naturally, you are going to get an error.

Please post the portion of your bot code to show where you are listening for the messages. For example, a NodeJS bot would have something like:

```<code>var server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, () => {
    console.log('%s listening to %s', server.name, server.url);
});

var connector = new builder.ChatConnector({
    appId: process.env.MICROSOFT_APP_ID,
    appPassword: process.env.MICROSOFT_APP_PASSWORD
});
var bot = new builder.UniversalBot(connector);
server.post('/api/messages', connector.listen());
</code>```

The last line shows the connecting listening for message at /api/messages in the current application (being run by NodeJS using the restify library). What does your's have?

Body:
I have used IIS to locally host my bot like so: https: //localhost/MyBot. Currently when I try to connect to my bot in the bot emulator I get a POST 500 error, and am unable to send messages. I am new to this and most documentation for publishing a bot to a local server is limited. I can however successfully open this link from my browser.

Am I experiencing this error because I don't have the https: //localhost/Bridget/api/messages directory/url? I tried creating Virtual Directories in IIS but that did not help solve my problem. Do I need tunneling software? Is there a simple tutorial for deploying a bot locally using IIS and connecting to it via the bot emulator?

Here is the error I see in the emulator:

Bot Emulator Error

Using ngrok tunneling software this is what I see:

NGROK Bot Emulator Error

Here is the code that processing incoming POST messages:

///
/// POST: api/Messages
/// Receive a message from a user and reply to it
///
public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
    if (activity.Type == ActivityTypes.Message)
    {
        // Strip any @mentions
        Mention[] m = activity.GetMentions();
        for (int x = 0; x < m.Length; x++)
        {
            if (m[x].Mentioned.Id == activity.Recipient.Id)
            {
                if (m[x].Text != null)
                {
                    activity.Text = activity.Text.Replace(m[x].Text, "");
                }
            }
        }

        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

        await Conversation.SendAsync(activity, () => new Dialogs.RootDialog());
    }
    else if (activity.Type == ActivityTypes.Invoke)
    {
            // Some Code...
    }
    else
    {
        HandleSystemMessage(activity);
    }
    var response = Request.CreateResponse(HttpStatusCode.OK);
    return response;
}

Body:
Am I experiencing this error because I don't have the https: //localhost/Bridget/api/messages directory/url?

Both your screenshots show you trying to connect to /api/messages, which you say you don't have, so naturally, you are going to get an error.

Please post the portion of your bot code to show where you are listening for the messages. For example, a NodeJS bot would have something like:

var server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, () => {
    console.log('%s listening to %s', server.name, server.url);
});

var connector = new builder.ChatConnector({
    appId: process.env.MICROSOFT_APP_ID,
    appPassword: process.env.MICROSOFT_APP_PASSWORD
});
var bot = new builder.UniversalBot(connector);
server.post('/api/messages', connector.listen());

The last line shows the connecting listening for message at /api/messages in the current application (being run by NodeJS using the restify library). What does your's have?


问:
VALIDATE statement is causing a value not to be stored in the database
I have been dealing with an issue recently and am stuck. A particular program(a compiled .p) has codes written where its trying to save values to a particular field in the db.

Below this there is a VAILDATE statement on that table. This is causing the value to revert while doing an update operation. I messaged before and after VALIDATE and can see the value updated before VALIDATE and reverted just after VALIDATE. Please can someone help me on this. Many thanks in advance.

答:
I did simulate your problem.
Most likely, the assign violates an index as well as change the value of the field you're monitoring. The whole transaction fails when OE resolves the VALIDATE and it doesn't pass. The record is then restored (rollback) to its last valid value, along with the old value to the field you're looking at. As far as I can tell, that is expected.

To get around that behavior, I believe you should

a) Rewrite the block and validate the record after changing ONLY the unique fields (though this doesn't really solve it. It just saves you from doing operations that will be undone later); or

b) Save the old values to a temp-table record and copy them back if you still want them when VALIDATE fails.

Hope this gives you some ideas, at least.


问:
Bootstrap: Font-Awesome does not work in subfolder?
I downloaded the Creative Bootstrap theme which has the following folder structure

```<code>css/
img/
js/
less/
vendor/
index.html
</code>```

I have now created a subfolder, copied the index.html in the folder and changed the links from the CSS and JS files by adding a ../. In particular the link for fontawesome on line 18 changed to

```<code><link href="../vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
</code>```

To my surprise, the font-awesome links are not working anymore:

In addition, I noticed than when I remove the dots ../ and copy the vendor folder in subfolder then the font-awesome icons are working.

There is no 404 error in my network tab when I open index.html from root or form subfolder. Both times it looks like this (why is Font-Awesome never listed? I pressed F5 and the index.html file in the root folder actually displays teh Font-Awesome icons correctly):

Why are the Font-Awesome icons not displayed correctly when the vendor folder is outside the subfolder?

答: This happens only on local and only in Firefox. Put the files on a server and should work fine in Firefox too.</p>

Body:
I downloaded the Creative Bootstrap theme which has the following folder structure

css/
img/
js/
less/
vendor/
index.html

I have now created a subfolder, copied the index.html in the folder and changed the links from the CSS and JS files by adding a ../. In particular the link for fontawesome on line 18 changed to

<link href="../vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

To my surprise, the font-awesome links are not working anymore:

In addition, I noticed than when I remove the dots ../ and copy the vendor folder in subfolder then the font-awesome icons are working.

There is no 404 error in my network tab when I open index.html from root or form subfolder. Both times it looks like this (why is Font-Awesome never listed? I pressed F5 and the index.html file in the root folder actually displays teh Font-Awesome icons correctly):

Why are the Font-Awesome icons not displayed correctly when the vendor folder is outside the subfolder?


问:
Is there a way to artifically press a button on an xbox controller?
I'm creating an application for a phone that will be able to be used as a controller on a computer. I want the phone to imitate how an xbox 360 controller would work. However, I'm not sure how to go about this. Is there any way I can trick the pc into thinking it's an xbox controller? </p>

答:
View the source code for DS4Windows (Maps a Sony PS4 Controller to an XBox-360 Controller): https://github.com/Jays2Kings/DS4Windows/blob/jay/DS4Windows/DS4Control/X360Device.cs

Basically you need to pair to the device via Bluetooth and read the input. Map the commands to the Xbox ones and broadcast it or write to whatever application needs it.


问:
Technical reason we cannot iterate with forEach() over Map.prototype.keys()
If I create a Map instance like so:

```<code>let m = new Map()
</code>```

I cannot iterative over it's keys like so:

```<code>m.keys().forEach()
</code>```

why is that?

I can iterative over it's key-value pairs like so:

```<code>m.forEach((v,k) => {})
</code>```

what is the reason for this?

答:
Map.prototype.keys() returns an Iterator object, not an Array, which has no .forEach() function in it's prototype.

What you can do, however, is the following:

```<code>let map = new Map();
Array.from(map.keys()).forEach(callback);
</code>```

That will convert the Iterator object into an Array, and you can use the .forEach() method freely. Alternatively, you can use the spread syntax to accomplish the same goal:

```<code>let map = new Map();
let keys = [ ...myMap.keys() ].forEach(callback);
</code>```

Body:
If I create a Map instance like so:

let m = new Map()

I cannot iterative over it's keys like so:

m.keys().forEach()

why is that?

I can iterative over it's key-value pairs like so:

m.forEach((v,k) => {})

what is the reason for this?

Body:
Map.prototype.keys() returns an Iterator object, not an Array, which has no .forEach() function in it's prototype.

What you can do, however, is the following:

let map = new Map();
Array.from(map.keys()).forEach(callback);

That will convert the Iterator object into an Array, and you can use the .forEach() method freely. Alternatively, you can use the spread syntax to accomplish the same goal:

let map = new Map();
let keys = [ ...myMap.keys() ].forEach(callback);


问:
Make optional alt img attribute using preg_replace
I'm using this code

```<code>echo preg_replace('#\{{2}(.*?)\}{2}#', '<img src="/base/$1">', $input);
</code>```

To display an input like this:

```<code>foo foo {{picture.jpg}} foo
</code>```

In img html tag.
I would like to add an optional alt attribute in this format:

```<code>{{picture.jpg|optional}}
</code>```

and translate into:

```<code><img src="/base/$1" alt="$2">
</code>```

only if it is present, without make another preg_replace but only improving the existing one.

How can i do this?

答:
Since you only forbid to use another preg_replace not another regex this works:

```<code>preg_replace(['#\{{2}(.*?)\|(.*?)\}{2}#', '#\{{2}(.*?)\}{2}#'], ['<img src="/base/$1" alt="$2">', '<img src="/base/$1">'], $input);
</code>```

Working example:

```<code>function replacer($input) {
    return preg_replace(['#\{{2}(.*?)\|(.*?)\}{2}#', '#\{{2}(.*?)\}{2}#'], ['<img src="/base/$1" alt="$2">', '<img src="/base/$1">'], $input);
}

echo replacer('{{picture.jpg}}');
echo replacer('{{picture.jpg|optional}}');
</code>```

Output:

```<code><img src="/base/picture.jpg">
<img src="/base/picture.jpg" alt="optional">
</code>```

Body:
I'm using this code

echo preg_replace('#\{{2}(.*?)\}{2}#', '', $input);

To display an input like this:

foo foo {{picture.jpg}} foo

In img html tag.
I would like to add an optional alt attribute in this format:

{{picture.jpg|optional}}

and translate into:

only if it is present, without make another preg_replace but only improving the existing one.

How can i do this?

Body:
Since you only forbid to use another preg_replace not another regex this works:

preg_replace(['#\{{2}(.*?)\|(.*?)\}{2}#', '#\{{2}(.*?)\}{2}#'], ['<img src="/base/$1" alt="$2">', '<img src="/base/$1">'], $input);

Working example:

function replacer($input) {
    return preg_replace(['#\{{2}(.*?)\|(.*?)\}{2}#', '#\{{2}(.*?)\}{2}#'], ['<img src="/base/$1" alt="$2">', '<img src="/base/$1">'], $input);
}

echo replacer('{{picture.jpg}}');
echo replacer('{{picture.jpg|optional}}');

Output:

<img src="/base/picture.jpg">
<img src="/base/picture.jpg" alt="optional">


问:
Customize fswebcam file name in python
Is it possible to make the image names generated from fswebcam take a name from a variable in python? The idea is that I have a card swipe system that takes a webcam shot of whoever swipes their card and stores the image in a folder. I want to have the serial number of the card and time be the name of the image generated. Right now, I only found a way to get the time written in the name but not the serial number. Can anyone help me out?

Card Swipe System Code:

```<code>import datetime
import time
import os
import RPi.GPIO as gpio

t = datetime.datetime.now()

gpio.setmode(gpio.BOARD)
gpio.setwarnings(False)

while True:
    card = raw_input()
    f = open("Laptop Sign Out" + '.txt', 'a')
    f.write("Card Number: " + card[1:10] + " Time: " + t.strftime("%m-%d-%Y %H:%M:%S"))
    f.write('\n')
    f.close()
    time.sleep(1)
    os.system('fswebcam ~/Desktop/Photos/%H%M%S.jpeg')
    time.sleep(3)

gpio.cleanup()
</code>```

答:
Just concatenate the appropriate text, in this case use format.

```<code>os.system('fswebcam ~/Desktop/Photos/{}_{}.jpeg'.format(card, t.strftime("%m-%d-%Y %H:%M:%S")))
</code>```

complete code:

```<code>import datetime
import time
import os
import RPi.GPIO as gpio

gpio.setmode(gpio.BOARD)
gpio.setwarnings(False)

while True:
    card = raw_input()
    t = datetime.datetime.now()
    f = open("Laptop Sign Out" + '.txt', 'a')
    f.write("Card Number: " + card[1:10] + " Time: " + t.strftime("%m-%d-%Y %H:%M:%S"))
    f.write('\n')
    f.close()
    time.sleep(1)
    os.system('fswebcam ~/Desktop/Photos/{}_{}.jpeg'.format(card, t.strftime("%m-%d-%Y %H:%M:%S")))
    time.sleep(3)

gpio.cleanup()
</code>```

Note: I have moved the location of the variable t since if it is inside the loop it will never be updated.

Title: Customize fswebcam file name in python

Body:
Is it possible to make the image names generated from fswebcam take a name from a variable in python? The idea is that I have a card swipe system that takes a webcam shot of whoever swipes their card and stores the image in a folder. I want to have the serial number of the card and time be the name of the image generated. Right now, I only found a way to get the time written in the name but not the serial number. Can anyone help me out?

Card Swipe System Code:

import datetime
import time
import os
import RPi.GPIO as gpio

t = datetime.datetime.now()

gpio.setmode(gpio.BOARD)
gpio.setwarnings(False)

while True:
    card = raw_input()
    f = open("Laptop Sign Out" + '.txt', 'a')
    f.write("Card Number: " + card[1:10] + " Time: " + t.strftime("%m-%d-%Y %H:%M:%S"))
    f.write('\n')
    f.close()
    time.sleep(1)
    os.system('fswebcam ~/Desktop/Photos/%H%M%S.jpeg')
    time.sleep(3)

gpio.cleanup()

Body:
Just concatenate the appropriate text, in this case use format.

os.system('fswebcam ~/Desktop/Photos/{}_{}.jpeg'.format(card, t.strftime("%m-%d-%Y %H:%M:%S")))

complete code:

import datetime
import time
import os
import RPi.GPIO as gpio

gpio.setmode(gpio.BOARD)
gpio.setwarnings(False)

while True:
    card = raw_input()
    t = datetime.datetime.now()
    f = open("Laptop Sign Out" + '.txt', 'a')
    f.write("Card Number: " + card[1:10] + " Time: " + t.strftime("%m-%d-%Y %H:%M:%S"))
    f.write('\n')
    f.close()
    time.sleep(1)
    os.system('fswebcam ~/Desktop/Photos/{}_{}.jpeg'.format(card, t.strftime("%m-%d-%Y %H:%M:%S")))
    time.sleep(3)

gpio.cleanup()

Note: I have moved the location of the variable t since if it is inside the loop it will never be updated.


答:
You could use

```<code>{{(.+?)(?:\|([^}]+))?}}
</code>```

See a demo on regex101.com.

Which in PHP, with the help of preg_replace_callback() would be:

```<code><?php

$string = <<<DATA
foo foo {{picture.jpg}} foo
{{picture.jpg|optional}}
DATA;

$regex = '~{{(.+?)(?:\|([^}]+))?}}~';

$string = preg_replace_callback($regex,
    function($match) {
        if (!empty($match[2])) {
            return "<img src='/base/{$match[1]}' alt='{$match[2]}'>";
        } else {
            return "<img src='/base/{$match[1]}'>";
        }
}, $string);

echo $string;
</code>```

This yields

```<code>foo foo <img src='/base/picture.jpg'> foo
<img src='/base/picture.jpg' alt='optional'>
</code>```

Title: Make optional alt img attribute using preg_replace

Body:
You could use

{{(.+?)(?:\|([^}]+))?}}

See a demo on regex101.com.

Which in PHP, with the help of preg_replace_callback() would be:

<?php

$string = <<<DATA
foo foo {{picture.jpg}} foo
{{picture.jpg|optional}}
DATA;

$regex = '~{{(.+?)(?:\|([^}]+))?}}~';

$string = preg_replace_callback($regex,
    function($match) {
        if (!empty($match[2])) {
            return "<img src='/base/{$match[1]}' alt='{$match[2]}'>";
        } else {
            return "<img src='/base/{$match[1]}'>";
        }
}, $string);

echo $string;

This yields

foo foo <img src='/base/picture.jpg'> foo
<img src='/base/picture.jpg' alt='optional'>


问:
Creating object with specific keys in jQuery?
How can I create the following object with jQuery:</p>

```<code>{"41500":{"color":"black","qty":1},"41501":{"color":"red","qty":1}}
</code>```

答:
// you'll need them in an array
var arr = [];

// make an empty object
var obj = {};

// name a key and set the value as another obj
obj["41500"] = {
  "color": "black",
  "qty": 1
}
arr.push(obj);

// repeat
var obj = {};
obj["41501"] = {
  "color": "red",
  "qty": 1
}
arr.push(obj);

console.log(arr)```
</div>
</div>
</p>

<h2>//UPDATE//</h2>

<p>If you need the index to be at the value then do this: </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var array = [];
array[41500] = {
  "color": "black",
  "qty": 1
}
array[41501] = {
  "color": "red",
  "qty": 1
}
console.log(array[41500]);
var id = 41501;
console.log(array[id]);

// notice all the undefined values at the indexes
console.log(array);</code>```

Body:
How can I create the following object with jQuery:

{"41500":{"color":"black","qty":1},"41501":{"color":"red","qty":1}}

Body:
// you'll need them in an array
var arr = [];

// make an empty object
var obj = {};

// name a key and set the value as another obj
obj["41500"] = {
  "color": "black",
  "qty": 1
}
arr.push(obj);

// repeat
var obj = {};
obj["41501"] = {
  "color": "red",
  "qty": 1
}
arr.push(obj);

console.log(arr)

//UPDATE//

If you need the index to be at the value then do this:

var array = [];
array[41500] = {
  "color": "black",
  "qty": 1
}
array[41501] = {
  "color": "red",
  "qty": 1
}
console.log(array[41500]);
var id = 41501;
console.log(array[id]);

// notice all the undefined values at the indexes
console.log(array);


问:
How to convert a file to a tcl list?
I have a file named time.dat and acc.dat both of which contains a single column containing numerical values.
I want to create lists from these files which contain the values in the files. Anyone knows how to do it? </p>

```<code>proc ReadRecord {inFilename outFilenameT outFilenameS} {

   if [catch {open $inFilename r} inFileID] {
      puts stderr "Cannot open $inFilename for reading"
   } else {
      set outFileIDS [open $outFilenameS w]
      set outFileIDT [open $outFilenameT w]
      foreach line [split [read $inFileID] \n] {

         if {[llength $line] == 0} {
            continue
         } else {
            puts $outFileIDT [lindex $line 0]
            puts $outFileIDS [lindex $line 1]
         }
      }
      close $outFileIDT
      close $outFileIDS
      close $inFileID
   }
};
</code>```

答:
Using fileutil this becomes trivial:

```<code>package require fileutil

fileutil::write testfile.dat {a b c}
set myList [fileutil::cat testfile.dat]
lindex $a 1
</code>```

This actually writes a list to a file first, and then reads this data back in. As tcl represents lists as strings, we just have to assign the file contents to a variable.

In case your list uses newlines as element seperators, or something other than plain whitespace (tab, space), you will have to use split, i.e. split [fileutil::cat testfile.dat] \n as discussed in above posts.

NOTE: internally lists can also use a list representation besides their string representation. Calling sting and list functions onto a list alternativly triggers conversions between the representation and invalidates the other representation. For that reason it is bad to switch between the too, but that is a different topic, for those interested check the tcl wiki on shimmering.

Title: How to convert a file to a tcl list?

Body:
I have a file named time.dat and acc.dat both of which contains a single column containing numerical values.
I want to create lists from these files which contain the values in the files. Anyone knows how to do it?

proc ReadRecord {inFilename outFilenameT outFilenameS} {

   if [catch {open $inFilename r} inFileID] {
      puts stderr "Cannot open $inFilename for reading"
   } else {
      set outFileIDS [open $outFilenameS w]
      set outFileIDT [open $outFilenameT w]
      foreach line [split [read $inFileID] \n] {

         if {[llength $line] == 0} {
            continue
         } else {
            puts $outFileIDT [lindex $line 0]
            puts $outFileIDS [lindex $line 1]
         }
      }
      close $outFileIDT
      close $outFileIDS
      close $inFileID
   }
};

Body:
Using fileutil this becomes trivial:

package require fileutil

fileutil::write testfile.dat {a b c}
set myList [fileutil::cat testfile.dat]
lindex $a 1

This actually writes a list to a file first, and then reads this data back in. As tcl represents lists as strings, we just have to assign the file contents to a variable.

In case your list uses newlines as element seperators, or something other than plain whitespace (tab, space), you will have to use split, i.e. split [fileutil::cat testfile.dat] \n as discussed in above posts.

NOTE: internally lists can also use a list representation besides their string representation. Calling sting and list functions onto a list alternativly triggers conversions between the representation and invalidates the other representation. For that reason it is bad to switch between the too, but that is a different topic, for those interested check the tcl wiki on shimmering.


问:
c# string that has to contain quote "
```<code>string aniPattern=@"(?si:<option value=\\\"(?<year>.*?)\\)";
</code>```

This breakes because the " in the middle. But I need that because I use it in a regex.

I tried to use string aniPattern="(?si:<option value=\\\"(?<year>.*?)\\\\)";(without @) but it isnot a valid regex.

答:
```<code>string aniPattern=@"(?si:<option value=""(?<year>.*?)\)";
</code>```

For @ escaped strings, you double the quotation mark to escape it, since backslash is not used.

ContentLicense: CC BY-SA 2.5

Title: c# string that has to contain quote "

Body:
string aniPattern=@"(?si:<option value=\\\"(?<year>.*?)\\)";

This breakes because the " in the middle. But I need that because I use it in a regex.

I tried to use string aniPattern="(?si:<option value=\\\"(?<year>.*?)\\\\)";(without @) but it isnot a valid regex.

Body:
string aniPattern=@"(?si:<option value=""(?<year>.*?)\)";

For @ escaped strings, you double the quotation mark to escape it, since backslash is not used.


问:
List submodules in a Git repository
I have a Git repository that has several submodules in it. How do I list the names of all the submodules after git submodule init has been run?

The git submodule foreach command could echo the names of the submodule, but that only works once they have been checked out which has not happened after the init step. There are more steps in the chain that need to happen before they can be checked out, and I don't want to have to hard-wire names of submodules into the script.

So is there a Git command to get the names of all currently registered, but not yet checked out submodules?

答:
If you don't mind operating only on initialized submodules, you can use git submodule foreach to avoid text parsing.

```<code>git submodule foreach --quiet 'echo $name'
</code>```

Title: List submodules in a Git repository

Body:
If you don't mind operating only on initialized submodules, you can use git submodule foreach to avoid text parsing.

git submodule foreach --quiet 'echo $name'


问:
MYSQL - Removing number from One Table in SQL if it exists in another Table
I need some assistance with deleting data within an SQL Table if it matches data from another table.

There are two Tables

```<code>Table 1: DNC
Table 2: Call_Logs
</code>```

Table 1 has only one column called phone_number.
Table 2 has multiple columns, but the main one that is important is also named phone_number.

Basically, I want to remove any numbers that are in Table 2 from Table 1, if they exist.  Now, I don't want to delete every number from Table 1 if they exist in Table 2.  What numbers I collect from Table 2 are based on some criteria.

To pull the data from Table 2 that I need to delete from Table 1,  I use the following:

```<code>select phone_number from call_logs where call_date < 'DATE' and Status = 'DNC'
</code>```

This query will give me a list of all phone numbers that I would want to remove from Table 1 if it exists.

EXAMPLE:
https://drive.google.com/file/d/0B4NE4ZDXd6steW5odWhBMDJSY1U/view

I am not sure how I would go about running the query in SQL.  Any types would be appreciated it.

答:
Looking to your sample in img

You could use a left join on table 2 (where table2.phone_number is null alias don't match)

```<code>delete from table1
left join table2 on table1.phone_number = table2.phone_number
where table2.phone_number is null
</code>```

Body:
I need some assistance with deleting data within an SQL Table if it matches data from another table.

There are two Tables

Table 1: DNC
Table 2: Call_Logs

Table 1 has only one column called phone_number.
Table 2 has multiple columns, but the main one that is important is also named phone_number.

Basically, I want to remove any numbers that are in Table 2 from Table 1, if they exist.  Now, I don't want to delete every number from Table 1 if they exist in Table 2.  What numbers I collect from Table 2 are based on some criteria.

To pull the data from Table 2 that I need to delete from Table 1,  I use the following:

select phone_number from call_logs where call_date < 'DATE' and Status = 'DNC'

This query will give me a list of all phone numbers that I would want to remove from Table 1 if it exists.

EXAMPLE:
https://drive.google.com/file/d/0B4NE4ZDXd6steW5odWhBMDJSY1U/view

I am not sure how I would go about running the query in SQL.  Any types would be appreciated it.

Body:
Looking to your sample in img

You could use a left join on table 2 (where table2.phone_number is null alias don't match)

delete from table1
left join table2 on table1.phone_number = table2.phone_number
where table2.phone_number is null


问:
filter IPaddress from list
I am a newbie to python I managed to pull data from an excel sheet using xlrd and put into a list and remove all white/empty spaces

I need to pull out the IP addresses from the list or remove all text. I have looked at strip regex and the module IP address but just seem overwhelmed, please help me find a solution.

```<code>ipList = ['Device name:', 'Management IPs:', 'Virtual Server IP', '10.100.33.131 (Prod)', '10.100.33.132 (Prod)', '10.100.33.133 (Prod)', '10.100.33.134 (Prod)', '10.100.33.148 (QA)', '10.100.33.149 (QA)', '10.100.33.150 (QA)', 'Scripted / HTTP Health check details', 'Name', 'iRule requirements']
#
</code>```

答:
You can use this regex to extract the IP from the list.</p>

```<code>import re

ipList = ['Device name:', 'Management IPs:', 'Virtual Server IP', '10.100.33.131 (Prod)', '10.100.33.132 (Prod)', '10.100.33.133 (Prod)', '10.100.33.134 (Prod)', '10.100.33.148 (QA)', '10.100.33.149 (QA)', '10.100.33.150 (QA)', 'Scripted / HTTP Health check details', 'Name', 'iRule requirements']
IP = []
for element in ipList:
    ip = re.findall( r'[0-9]+(?:\.[0-9]+){3}', element)
    if len(ip) > 0:
        IP.append(ip)
print IP
</code>```

Title: filter IPaddress from list

Body:
I am a newbie to python I managed to pull data from an excel sheet using xlrd and put into a list and remove all white/empty spaces

I need to pull out the IP addresses from the list or remove all text. I have looked at strip regex and the module IP address but just seem overwhelmed, please help me find a solution.

ipList = ['Device name:', 'Management IPs:', 'Virtual Server IP', '10.100.33.131 (Prod)', '10.100.33.132 (Prod)', '10.100.33.133 (Prod)', '10.100.33.134 (Prod)', '10.100.33.148 (QA)', '10.100.33.149 (QA)', '10.100.33.150 (QA)', 'Scripted / HTTP Health check details', 'Name', 'iRule requirements']
#

Body:
You can use this regex to extract the IP from the list.

import re

ipList = ['Device name:', 'Management IPs:', 'Virtual Server IP', '10.100.33.131 (Prod)', '10.100.33.132 (Prod)', '10.100.33.133 (Prod)', '10.100.33.134 (Prod)', '10.100.33.148 (QA)', '10.100.33.149 (QA)', '10.100.33.150 (QA)', 'Scripted / HTTP Health check details', 'Name', 'iRule requirements']
IP = []
for element in ipList:
    ip = re.findall( r'[0-9]+(?:\.[0-9]+){3}', element)
    if len(ip) > 0:
        IP.append(ip)
print IP


问:
How do I convert a JSON file into a list of dicts?
So I have a JSON file with the following contents:

```<code>{"prtg-version":"17.1.29.1531","treesize":8,"probes":
    [
        {"objid":1,"name":"ASHBURN CORE"},
        {"objid":30201,"name":"GRAND RAPIDS PROBE"},
        {"objid":2,"name":"Cluster Probe"},
        {"objid":6015,"name":"AWS Oregon"},
        {"objid":2666,"name":"ASHBURN PROBE"},
        {"objid":9607,"name":"HERNDON PROBE"},
        {"objid":9218,"name":"DENVER"},
        {"objid":7259,"name":"AWS Ohio"}
    ]
}
</code>```

I want to use this data in a python script but first I need to convert this JSON into a list of dicts and then store that list of dicts to a variable in Python. Also, I am fetching this JSON file using an API call from a PRTG server if that helps at all. I've also imported the JSON module.

Essentially, if I can strip off the outer dictionary, I will be left with a list of dicts that already follows Python format. Any ideas how to do that?

答:
This might be helpful

```<code>import json

a = '{"prtg-version":"17.1.29.1531","treesize":8,"probes":[{"objid":1,"name":"ASHBURN CORE"},{"objid":30201,"name":"GRAND RAPIDS PROBE"},{"objid":2,"name":"Cluster Probe"},{"objid":6015,"name":"AWS Oregon"},{"objid":2666,"name":"ASHBURN PROBE"},{"objid":9607,"name":"HERNDON PROBE"},{"objid":9218,"name":"DENVER"},{"objid":7259,"name":"AWS Ohio"}]}'

data = json.loads(a)

for a in data:
  print(a,data[a])
</code>```

I am converting the response to json and iterating over it in the for loop

Body:
So I have a JSON file with the following contents:

{"prtg-version":"17.1.29.1531","treesize":8,"probes":
    [
        {"objid":1,"name":"ASHBURN CORE"},
        {"objid":30201,"name":"GRAND RAPIDS PROBE"},
        {"objid":2,"name":"Cluster Probe"},
        {"objid":6015,"name":"AWS Oregon"},
        {"objid":2666,"name":"ASHBURN PROBE"},
        {"objid":9607,"name":"HERNDON PROBE"},
        {"objid":9218,"name":"DENVER"},
        {"objid":7259,"name":"AWS Ohio"}
    ]
}

I want to use this data in a python script but first I need to convert this JSON into a list of dicts and then store that list of dicts to a variable in Python. Also, I am fetching this JSON file using an API call from a PRTG server if that helps at all. I've also imported the JSON module.

Essentially, if I can strip off the outer dictionary, I will be left with a list of dicts that already follows Python format. Any ideas how to do that?

Body:
This might be helpful

import json

a = '{"prtg-version":"17.1.29.1531","treesize":8,"probes":[{"objid":1,"name":"ASHBURN CORE"},{"objid":30201,"name":"GRAND RAPIDS PROBE"},{"objid":2,"name":"Cluster Probe"},{"objid":6015,"name":"AWS Oregon"},{"objid":2666,"name":"ASHBURN PROBE"},{"objid":9607,"name":"HERNDON PROBE"},{"objid":9218,"name":"DENVER"},{"objid":7259,"name":"AWS Ohio"}]}'

data = json.loads(a)

for a in data:
  print(a,data[a])

I am converting the response to json and iterating over it in the for loop