问:
How to convert a 2D point on defined plane in planar uv coordinates back to 3D xyz coordinates?
I have a defined plane (one which happens to be orthogonal to the vector defined by two xyz points in 3D space).  I can project any xyz point onto the plane and represent that projection uv coordinate space.  I would like to take an arbitrary point in uv coordinate space and find out what its coordinates are in xyz space.

a = x2 - x1
b = y2 - y1
c = z2 - z1
d = -1*(a*x1 + b*y1 + c*z1)
magnitude = (a**2 + b**2 + c**2)**.5
u_magnitude = (b**2 + a**2)**.5

normal = [a/magnitude, b/magnitude, c/magnitude]
u = [b/u_magnitude, -a/u_magnitude, 0]
v = np.cross(normal, u)

p_u = np.dot(u,[x1,y1,z1])
p_v = np.dot(v,[x1,y1,z1])
```

This code I believe accurately produces the plane I want and will assign the x1,y1,z1 point in uv coordinates to p_u,p_v. My sense is that I have everything I need to do the reverse operation, but I don't know how.  If I have a point u0,v0 how can I find x0,y0,z0 that describes its location in 3D space?

答:
From the definition in the text (not reading the code), the problem is not well defined - as there is an infinite number of planes orthogonal to a given vector (think of all the options as planes at different "offsets" along the line from the first point to the second). What you need is first to pick some point through which the plane has to go.

Secondly, when we convert a (U, V) pair to 3D point, I assume you mean a 3D point on the plane.

Trying to be more concrete though, here is your code, with documentation on how I understand it, and how to do the reverse:

```<code># ### The original computation of the plane equation ###
# Given points p1 and p2, the vector through them is W = (p2 - p1)
# We want the plane equation Ax + By + Cz + d = 0, and to make
# the plane prepandicular to the vector, we set (A, B, C) = W
p1 = np.array([x1, y1, z1])
p2 = np.array([x2, y2, z2])

A, B, C = W = p2 - p1

# Now we can solve D in the plane equation. This solution assumes that
# the plane goes through p1.
D = -1 * np.dot(W, p1)

# ### Normalizing W ###
magnitude = np.linalg.norm(W)
normal = W / magnitude

# Now that we have the plane, we want to define
# three things:
# 1. The reference point in the plane (the "origin"). Given the
#    above computation of D, that is p1.
# 2. The vectors U and V that are prepandicular to W
#    (and therefore spanning the plane)

# We take a vector U that we know that is perpendicular to
# W, but we also need to make sure it's not zero.
if A != 0:
    u_not_normalized = np.array([B, -A, 0])
else:
    # If A is 0, then either B or C have to be nonzero
    u_not_normalized = np.array([0, B, -C])
u_magnitude = np.linalg.norm(u_not_normalized)

# ### Normalizing W ###
U = u_not_normalized / u_magnitude
V = np.cross(normal, U)

# Now, for a point p3 = (x3, y3, z3) it's (u, v) coordinates would be
# computed relative to our reference point (p1)
p3 = np.array([x3, y3, z3])

p3_u = np.dot(U, p3 - p1)
p3_v = np.dot(V, p3 - p1)

# And to convert the point back to 3D, we just use the same reference point
# and multiply U and V by the coordinates
p3_again = p1 + p3_u * U + p3_v * V
</code>```

Body:
I have a defined plane (one which happens to be orthogonal to the vector defined by two xyz points in 3D space).  I can project any xyz point onto the plane and represent that projection uv coordinate space.  I would like to take an arbitrary point in uv coordinate space and find out what its coordinates are in xyz space.

a = x2 - x1
b = y2 - y1
c = z2 - z1
d = -1*(a*x1 + b*y1 + c*z1)
magnitude = (a**2 + b**2 + c**2)**.5
u_magnitude = (b**2 + a**2)**.5

normal = [a/magnitude, b/magnitude, c/magnitude]
u = [b/u_magnitude, -a/u_magnitude, 0]
v = np.cross(normal, u)

p_u = np.dot(u,[x1,y1,z1])
p_v = np.dot(v,[x1,y1,z1])

This code I believe accurately produces the plane I want and will assign the x1,y1,z1 point in uv coordinates to p_u,p_v. My sense is that I have everything I need to do the reverse operation, but I don't know how.  If I have a point u0,v0 how can I find x0,y0,z0 that describes its location in 3D space?

Body:
From the definition in the text (not reading the code), the problem is not well defined - as there is an infinite number of planes orthogonal to a given vector (think of all the options as planes at different "offsets" along the line from the first point to the second). What you need is first to pick some point through which the plane has to go.

Secondly, when we convert a (U, V) pair to 3D point, I assume you mean a 3D point on the plane.

Trying to be more concrete though, here is your code, with documentation on how I understand it, and how to do the reverse:

# ### The original computation of the plane equation ###
# Given points p1 and p2, the vector through them is W = (p2 - p1)
# We want the plane equation Ax + By + Cz + d = 0, and to make
# the plane prepandicular to the vector, we set (A, B, C) = W
p1 = np.array([x1, y1, z1])
p2 = np.array([x2, y2, z2])

A, B, C = W = p2 - p1

# Now we can solve D in the plane equation. This solution assumes that
# the plane goes through p1.
D = -1 * np.dot(W, p1)

# ### Normalizing W ###
magnitude = np.linalg.norm(W)
normal = W / magnitude

# Now that we have the plane, we want to define
# three things:
# 1. The reference point in the plane (the "origin"). Given the
#    above computation of D, that is p1.
# 2. The vectors U and V that are prepandicular to W
#    (and therefore spanning the plane)

# We take a vector U that we know that is perpendicular to
# W, but we also need to make sure it's not zero.
if A != 0:
    u_not_normalized = np.array([B, -A, 0])
else:
    # If A is 0, then either B or C have to be nonzero
    u_not_normalized = np.array([0, B, -C])
u_magnitude = np.linalg.norm(u_not_normalized)

# ### Normalizing W ###
U = u_not_normalized / u_magnitude
V = np.cross(normal, U)

# Now, for a point p3 = (x3, y3, z3) it's (u, v) coordinates would be
# computed relative to our reference point (p1)
p3 = np.array([x3, y3, z3])

p3_u = np.dot(U, p3 - p1)
p3_v = np.dot(V, p3 - p1)

# And to convert the point back to 3D, we just use the same reference point
# and multiply U and V by the coordinates
p3_again = p1 + p3_u * U + p3_v * V


来源: stackexchange

问:
Passing the shell script through the function
I am creating an application to manage ad groups through MVC using Power Shell Script Interaction. I have created a function that will return the values to fill in the razor components of HTML. However, when I passing the shell scripts from the base directory location the component is not getting filled with the value.

I have tried to set the path of the script using AppDomain.CurrentDomain.BaseDirectory, there is no error being generated nor I am getting any output.

** Razor Code **

```<code>@functions {

    public string PowerShellExecutor(string script) {
        var shell = PowerShell.Create();
        string outString = "";
        shell.Commands.AddScript(script);
        var results = shell.Invoke();
        if (results.Count>0)
        {
            var builder = new StringBuilder();
            foreach (var psObj in results)
            {
                builder.Append(psObj.BaseObject.ToString() + "\r\n");

            }
            outString = Server.HtmlEncode(builder.ToString());
        }
        return outString;
    }

<div class="row">
    <div class="col-md-12">
        @Html.TextBox("txtDir", @PowerShellExecutor(AppDomain.CurrentDomain.BaseDirectory.ToString()+ "Shell\\Get-StewardName.ps1"), new { @class = "form-control" })
            @*@Html.TextBox("txtDirectory", @PowerShellExecutor("$env:USERDNSDOMAIN") , new { @class = "form-control"})*@
     </div>
 </div>
</code>```

** Powershell Script **

```<code>    $StewardName = Get-ADUser $env:USERNAME -Properties DisplayName | Select -ExpandProperty DisplayName
    $EmployeeNumber = Get-ADUser $env:UserName -Properties EmployeeNumber| Select -ExpandProperty EmployeeNumber
    Write-Output "Steward: $StewardName ($EmployeeNumber)"
</code>```

When I type the environment variables I get the domain I am member of. When I pass script it should be getting some value.

答: Ok, so replacing AddScript() with AddCommand() executes the script however, while using environment variables to fetch the data it throws command not found exception.</p>

ContentLicense: CC BY-SA 4.0

Body:
I am creating an application to manage ad groups through MVC using Power Shell Script Interaction. I have created a function that will return the values to fill in the razor components of HTML. However, when I passing the shell scripts from the base directory location the component is not getting filled with the value.

I have tried to set the path of the script using AppDomain.CurrentDomain.BaseDirectory, there is no error being generated nor I am getting any output.

** Razor Code **

@functions {

    public string PowerShellExecutor(string script) {
        var shell = PowerShell.Create();
        string outString = "";
        shell.Commands.AddScript(script);
        var results = shell.Invoke();
        if (results.Count>0)
        {
            var builder = new StringBuilder();
            foreach (var psObj in results)
            {
                builder.Append(psObj.BaseObject.ToString() + "\r\n");

            }
            outString = Server.HtmlEncode(builder.ToString());
        }
        return outString;
    }

        @Html.TextBox("txtDir", @PowerShellExecutor(AppDomain.CurrentDomain.BaseDirectory.ToString()+ "Shell\\Get-StewardName.ps1"), new { @class = "form-control" })
            @*@Html.TextBox("txtDirectory", @PowerShellExecutor("$env:USERDNSDOMAIN") , new { @class = "form-control"})*@

** Powershell Script **

    $StewardName = Get-ADUser $env:USERNAME -Properties DisplayName | Select -ExpandProperty DisplayName
    $EmployeeNumber = Get-ADUser $env:UserName -Properties EmployeeNumber| Select -ExpandProperty EmployeeNumber
    Write-Output "Steward: $StewardName ($EmployeeNumber)"

When I type the environment variables I get the domain I am member of. When I pass script it should be getting some value.


问:
Lost .pem file. Need help connecting to EC2 remote server
My secretary created a new instance in Amazon using their EC2 server but lost the .pem file. Doing research online I was able to go to the instance system settings/get system log and retrieve some type of password there. The instance system log shows something like this:

```<code>2019/04/15 12:15:19Z: Username: Username
2019/04/15 12:15:19Z: Password: <Password>
</code>```

It is a very long code of random characters.

Is there any way I can use this to log in via remote desktop or is there a way to decrypt it? I tried several decryption methods online and they said this was not a valid "hash"...whatever this means. I am not a technical person so I need hopefully a response in layman terms.

答:
It appears that you are connecting to a Windows instance. When a new Amazon EC2 Windows instance is launched, a program on the AMI (disk image) automatically generates a random Administrator password. This is done so that you can access the instance, but nobody else can.

To keep the password secret, the program encrypts the password with the keypair nominated when the instance was launched. The encrypted password is passed back to AWS via the console. That is the string of 'random characters' you saw.

To decrypt the password, you can use the Get Windows Password feature, which requires you to supply the nominated keypair. It will then decrypt the password, which can be used to login to the instance as Administrator.

Since you no longer have the keypair, you cannot decrypt the password and therefore cannot login to the server. This is good! This proves that security works, because you would not want other people to be able to login to the server.

So, can do you regain access?

Refer to the steps on: I need to reset the administrator password on a Windows Server instance in Amazon EC2

Basically, there are two methods:

If Systems Manager is enabled for the instance, you can run a "rescue" script

Otherwise, there is a series of scripts that assist with the process of:

Detaching the disk

Attaching it to another instance

Resetting a configuration on the disk

Reattaching the disk to the original instance

The second process is a bit like plugging a USB disk into another computer to change a file (except that EC2 disks are managed differently).

Body:
My secretary created a new instance in Amazon using their EC2 server but lost the .pem file. Doing research online I was able to go to the instance system settings/get system log and retrieve some type of password there. The instance system log shows something like this:

2019/04/15 12:15:19Z: Username: Username
2019/04/15 12:15:19Z: Password: <Password>

It is a very long code of random characters.

Is there any way I can use this to log in via remote desktop or is there a way to decrypt it? I tried several decryption methods online and they said this was not a valid "hash"...whatever this means. I am not a technical person so I need hopefully a response in layman terms.


问:
Eloquent Javascript Chapter 4: arrayToList/listToArray Execise
Question from eloquentjavascript:

Write a function arrayToList that builds up a data structure like the
  previous one when given [1, 2, 3] as argument, and write a listToArray
  function that produces an array from a list. Also write the helper
  functions prepend, which takes an element and a list and creates a new
  list that adds the element to the front of the input list, and nth,
  which takes a list and a number and returns the element at the given
  position in the list, or undefined when there is no such element.

Can anyone explain this answer without any jargon?
I can only learn by instructions.

Here is what I came up with for arrayToList:
So start list null, create for loop decrementing and inside define "i" then return list.

```<code>function arrayToList(array){ //pass list as parameter
    var list = null; // don't know why we make it null
    for (var i=array.length-1; i>=0; i--)  // why -1 on the length?
        list = {value: array[i], rest:list}; //clueless
    return list;
}
</code>```

what is rest:list inside the list object?

答:
As a disclaimer, I wanna say that I am a newbie myself and I'm here to learn things and maybe help others by doing it. Here's how I understood that the second problem it's done.

Also write a listToArray function that produces an array from a list.

The following code will work:

```<code>function listToArray(list) {
    let arr = [];
    for(; list !== null; list = list.rest) {
      arr.push(list.value);
    }
    return arr;
}
</code>```

The list parameter will just hold the argument that will be inserted. In our case is: {value: 10, rest: {value: 20, rest: null}

Have in mind that the code in the Eloquent Javascript will make a list from an array with 3 elements [10, 20, 30], but for this example, we'll just use a list made from 2 elements.

On execution, the code will do the following things:

1st time(first loop):

omit the initialization of the for loop(don't define any variable or
do anything)

check if the list is not null - it's not, because at this moment
list is equal to  {value: 10, rest: {value: 20, rest: null}

make list(the parameter of the function) to be equal to list.rest

remember that .rest is just a property of the object list and that it points to another object - it will point to {value: 20, rest: null} in our case

2nd time(second loop):

omit the initialization of the for loop(don't define any variable or
do anything)

check if the list is not null - it's not, because at
    this moment list is equal to {value: 20, rest: null}

make list again to be equal to list.rest - but at this time it will
point to rest: null, so this time the value of the list will be the
value of the rest key, which is null

3rd time(third loop):

omit

check if the list is not null - it is in this case, so stop the
execution and go to the return statement

return arr

My answer is based on: https://gist.github.com/laichejl/32d98af04caa66bd195f#file-exercise-js-L18

ContentLicense: CC BY-SA 3.0

Body:
Question from eloquentjavascript:

Write a function arrayToList that builds up a data structure like the
  previous one when given [1, 2, 3] as argument, and write a listToArray
  function that produces an array from a list. Also write the helper
  functions prepend, which takes an element and a list and creates a new
  list that adds the element to the front of the input list, and nth,
  which takes a list and a number and returns the element at the given
  position in the list, or undefined when there is no such element.

Can anyone explain this answer without any jargon?
I can only learn by instructions.

Here is what I came up with for arrayToList:
So start list null, create for loop decrementing and inside define "i" then return list.

function arrayToList(array){ //pass list as parameter
    var list = null; // don't know why we make it null
    for (var i=array.length-1; i>=0; i--)  // why -1 on the length?
        list = {value: array[i], rest:list}; //clueless
    return list;
}

what is rest:list inside the list object?

Body:
As a disclaimer, I wanna say that I am a newbie myself and I'm here to learn things and maybe help others by doing it. Here's how I understood that the second problem it's done.

Also write a listToArray function that produces an array from a list.

The following code will work:

function listToArray(list) {
    let arr = [];
    for(; list !== null; list = list.rest) {
      arr.push(list.value);
    }
    return arr;
}

The list parameter will just hold the argument that will be inserted. In our case is: {value: 10, rest: {value: 20, rest: null}

Have in mind that the code in the Eloquent Javascript will make a list from an array with 3 elements [10, 20, 30], but for this example, we'll just use a list made from 2 elements.

On execution, the code will do the following things:

1st time(first loop):

omit the initialization of the for loop(don't define any variable or
do anything)

check if the list is not null - it's not, because at this moment
list is equal to  {value: 10, rest: {value: 20, rest: null}

make list(the parameter of the function) to be equal to list.rest

remember that .rest is just a property of the object list and that it points to another object - it will point to {value: 20, rest: null} in our case

2nd time(second loop):

omit the initialization of the for loop(don't define any variable or
do anything)

check if the list is not null - it's not, because at
    this moment list is equal to {value: 20, rest: null}

make list again to be equal to list.rest - but at this time it will
point to rest: null, so this time the value of the list will be the
value of the rest key, which is null

3rd time(third loop):

omit

check if the list is not null - it is in this case, so stop the
execution and go to the return statement

return arr

My answer is based on: https://gist.github.com/laichejl/32d98af04caa66bd195f#file-exercise-js-L18


问:
How does the CPU know how many bytes it should read for the next instruction, considering instructions have different lengths?
So i was reading a paper, and in it, they said that statically disassembling the code of a binary is undecidable, because a series of bytes could be represented as many possible ways as shown in picture ( its x86 )

so my question is :

how does the CPU execute this then? for example in the picture, when we reach after C3, how does it know how many bytes it should  read for the next instruction?

how does the CPU know how much it should increment the PC after executing one instruction? does it somehow store the size of the current instruction and add that when it wants to increment PC?

if the CPU can somehow know how many bytes it should read for the next instruction or basically how to interpret the next instruction, why cant we do it statically?

答:
The simple way is to just read one byte, decode it and then determine if it's a complete instruction. If not read another byte, decode it if necessary and then determine if a complete instruction has been read. If not continue reading/decoding bytes until the complete instruction is read.

This means that if the instruction pointer is pointing at a given sequence of bytes there's only possible way to decode that first instruction of that sequence of bytes. The ambiguity only comes because the next instruction to be executed might not be located at the bytes immediately that follow the first instruction. That's because the first instruction in the sequence of bytes may change the instruction pointer so some other instruction other than the following one gets executed.

The RET (retn) instruction in your example could be the end of a function.  Functions often end with e RET instruction, but not necessarily so.  It's possible for a function to have multiple RET instructions, none of which are at the end of the function.  Instead the last instruction will be some sort of JMP instruction that jumps back to some location in the function, or to another function entirely.

That means in your example code, without more context, it's impossible to know if any of the bytes following the RET instruction will be ever be executed, and if so, which of the bytes would be the first instruction of the following function. There could be data in between functions or this RET instruction could be the end of the last function in the program.

The x86 instruction set in particular has a pretty complex format of optional prefix bytes, one or more opcode bytes, one or two possible addressing form bytes, and then possible displacement and immediate bytes.  The prefix bytes can be prepended to just about any instruction. The opcode bytes determine how many opcode bytes there are and whether the instruction can have a operand bytes and immediate bytes. The opcode may also indicate that there's displacement bytes. The first operand byte determines if there's a second operand byte and if there's displacement bytes.

The Intel 64 and IA-32 Architectures Software Developer's Manual has this figure showing the format of x86 instructions:

Python-like pseudo-code for decoding x86 instructions would look something like this:

```<code># read possible prefixes

prefixes = []
while is_prefix(memory[IP]):
    prefixes.append(memory[IP))
    IP += 1

# read the opcode

opcode = [memory[IP]]
IP += 1
while not is_opcode_complete(opcode):
    opcode.append(memory[IP])
    IP += 1

# read addressing form bytes, if any

modrm = None
addressing_form = []
if opcode_has_modrm_byte(opcode):
    modrm = memory[IP]
    IP += 1
    if modrm_has_sib_byte(modrm):
        addressing_form = [modrm, memory[IP]]
        IP += 1
    else:
        addressing_form = [modrm]

# read displacement bytes, if any

displacement = []
if (opcode_has_displacement_bytes(opcode)
    or modrm_has_displacement_bytes(modrm)):
    length = determine_displacement_length(prefixes, opcode, modrm)
    displacement = memory[IP : IP + length]
    IP += length

# read immediate bytes, if any

immediate = []
if opcode_has_immediate_bytes(opcode):
    length = determine_immediate_length(prefixes, opcode)
    immediate = memory[IP : IP + length]
    IP += length

# the full instruction

instruction = prefixes + opcode + addressing_form + displacement + immediate
</code>```

One important detail left out of the pseudo-code above is that instructions are limited to 15 bytes in length. It's possible to construct otherwise valid x86 instructions that are 16 bytes or longer, but such instruction will generate an undefined opcode CPU exception if executed. (There are other details I've left out, like how part of the opcode can be encoded inside of the Mod R/M byte, but I don't think this affects the length of instructions.)

However x86 CPUs don't actually decode instructions like how I've described above, they only decode instructions as if they read each byte one at a time.  Instead modern CPUs will read an entire 15 bytes in to a buffer and then decode bytes in parallel, usually in a single cycle. When it fully decodes the instruction, determining its length, and is ready to read the next instruction it shifts over the remaining bytes in the buffer that weren't part of the instruction.  It then reads more bytes to fill the buffer to 15 bytes again and starts decoding the next instruction.

Another thing modern CPUs will do that's isn't implied by what I've written above, is speculatively execute instructions. This means the CPU will decode instructions and tentatively try to execute them even before it has finished executing the previous instructions. This in turn means that the CPU may end up decoding the instructions following the RET instruction, but only if it can't determine where the RET will return to. Because there can be performance penalties from trying to decode and tentatively execute random data that's not intended to be executed, compilers don't normally put data in between functions. Though they may pad this space with NOP instructions that will never be executed in order to align functions for performance reasons.

(They used to put read-only data in between functions long ago, but this was before x86 CPUs that could speculatively execute instructions became common place.)

Body:
The simple way is to just read one byte, decode it and then determine if it's a complete instruction. If not read another byte, decode it if necessary and then determine if a complete instruction has been read. If not continue reading/decoding bytes until the complete instruction is read.

This means that if the instruction pointer is pointing at a given sequence of bytes there's only possible way to decode that first instruction of that sequence of bytes. The ambiguity only comes because the next instruction to be executed might not be located at the bytes immediately that follow the first instruction. That's because the first instruction in the sequence of bytes may change the instruction pointer so some other instruction other than the following one gets executed.

The RET (retn) instruction in your example could be the end of a function.  Functions often end with e RET instruction, but not necessarily so.  It's possible for a function to have multiple RET instructions, none of which are at the end of the function.  Instead the last instruction will be some sort of JMP instruction that jumps back to some location in the function, or to another function entirely.

That means in your example code, without more context, it's impossible to know if any of the bytes following the RET instruction will be ever be executed, and if so, which of the bytes would be the first instruction of the following function. There could be data in between functions or this RET instruction could be the end of the last function in the program.

The x86 instruction set in particular has a pretty complex format of optional prefix bytes, one or more opcode bytes, one or two possible addressing form bytes, and then possible displacement and immediate bytes.  The prefix bytes can be prepended to just about any instruction. The opcode bytes determine how many opcode bytes there are and whether the instruction can have a operand bytes and immediate bytes. The opcode may also indicate that there's displacement bytes. The first operand byte determines if there's a second operand byte and if there's displacement bytes.

The Intel 64 and IA-32 Architectures Software Developer's Manual has this figure showing the format of x86 instructions:

Python-like pseudo-code for decoding x86 instructions would look something like this:

# read possible prefixes

prefixes = []
while is_prefix(memory[IP]):
    prefixes.append(memory[IP))
    IP += 1

# read the opcode

opcode = [memory[IP]]
IP += 1
while not is_opcode_complete(opcode):
    opcode.append(memory[IP])
    IP += 1

# read addressing form bytes, if any

modrm = None
addressing_form = []
if opcode_has_modrm_byte(opcode):
    modrm = memory[IP]
    IP += 1
    if modrm_has_sib_byte(modrm):
        addressing_form = [modrm, memory[IP]]
        IP += 1
    else:
        addressing_form = [modrm]

# read displacement bytes, if any

displacement = []
if (opcode_has_displacement_bytes(opcode)
    or modrm_has_displacement_bytes(modrm)):
    length = determine_displacement_length(prefixes, opcode, modrm)
    displacement = memory[IP : IP + length]
    IP += length

# read immediate bytes, if any

immediate = []
if opcode_has_immediate_bytes(opcode):
    length = determine_immediate_length(prefixes, opcode)
    immediate = memory[IP : IP + length]
    IP += length

# the full instruction

instruction = prefixes + opcode + addressing_form + displacement + immediate

One important detail left out of the pseudo-code above is that instructions are limited to 15 bytes in length. It's possible to construct otherwise valid x86 instructions that are 16 bytes or longer, but such instruction will generate an undefined opcode CPU exception if executed. (There are other details I've left out, like how part of the opcode can be encoded inside of the Mod R/M byte, but I don't think this affects the length of instructions.)

However x86 CPUs don't actually decode instructions like how I've described above, they only decode instructions as if they read each byte one at a time.  Instead modern CPUs will read an entire 15 bytes in to a buffer and then decode bytes in parallel, usually in a single cycle. When it fully decodes the instruction, determining its length, and is ready to read the next instruction it shifts over the remaining bytes in the buffer that weren't part of the instruction.  It then reads more bytes to fill the buffer to 15 bytes again and starts decoding the next instruction.

Another thing modern CPUs will do that's isn't implied by what I've written above, is speculatively execute instructions. This means the CPU will decode instructions and tentatively try to execute them even before it has finished executing the previous instructions. This in turn means that the CPU may end up decoding the instructions following the RET instruction, but only if it can't determine where the RET will return to. Because there can be performance penalties from trying to decode and tentatively execute random data that's not intended to be executed, compilers don't normally put data in between functions. Though they may pad this space with NOP instructions that will never be executed in order to align functions for performance reasons.

(They used to put read-only data in between functions long ago, but this was before x86 CPUs that could speculatively execute instructions became common place.)


问:
How to fix a compile error with this code?
This is the link to the tutorial
https://wellsr.com/vba/2018/excel/excel-vba-send-email-with-attachment/

```<code>Sub AttachMultipleFilesToEmail()
Dim outlookApp As Outlook.Application
Dim myMail As Outlook.MailItem

Set outlookApp = New Outlook.Application
Set myMail = outlookApp.CreateItem(olMailItem)

For i = 2 To 5
  source_file = "C:\Work Files\" & Cells(i, 3)
  myMail.Attachments.Add source_file
Next i
End Sub
</code>```

Where the error occurs

The error code

This is the big picture of what I am trying to do. Got this image from https://wellsr.com/vba/2018/excel/excel-vba-send-email-with-attachment/ but the files and directory exist and correct. What could be the problem?

答: You might need to add a reference (Tools-->Reference) and change the "ThisWorbook" to "ActiveWorkoob".  ThisWorkbook is not going to work if you are runnign your macro from your Personal module.

Body:
This is the link to the tutorial
https://wellsr.com/vba/2018/excel/excel-vba-send-email-with-attachment/

Sub AttachMultipleFilesToEmail()
Dim outlookApp As Outlook.Application
Dim myMail As Outlook.MailItem

Set outlookApp = New Outlook.Application
Set myMail = outlookApp.CreateItem(olMailItem)

For i = 2 To 5
  source_file = "C:\Work Files\" & Cells(i, 3)
  myMail.Attachments.Add source_file
Next i
End Sub

Where the error occurs

The error code

This is the big picture of what I am trying to do. Got this image from https://wellsr.com/vba/2018/excel/excel-vba-send-email-with-attachment/ but the files and directory exist and correct. What could be the problem?


问:
Android Development: How To Get All EditText Children of a ViewGroup?
Basically, I have a LinearLayout that holds a random amount of horizontal LinearLayouts, and in each of the horizontal LinearLayouts there's a TextView and an EditText. I want to be able to get the value of each EditText children of the master LinearLayout.

Sorry if it's confusing, I'm no good at explaining things!

Could I just set the same ID for each of the EditTexts then use findViewById, or would that only return the first instance of an EditText?

Thanks,
Alex.

答: You would need to call findViewById on each of the LinearLayouts. If you do this, you can set the same ID for each EditText.</p>


问:
I dont know how to use fetch_message correctly
I dont know where to put the Coroutine "fetch_message"
I want to edit a message, but it doesnt work the old way

I tried the old way, but it told me it got 2 positional arguments instead of 1...

```<code>creator = ctx.message.author.id
await channel.send(f"<@{creator}>", embed=embed)

message_channel = ctx.message.channel
destruction_message = await message_channel .send("Self destruct in 3")
message = await client.fetch_message(destruction_message)
time.sleep(1)
print(message)
print(destruction_message)

await message.edit("Self destruct in 2")
message.edit()
time.sleep(1)
await message.edit("Self destruct in 1")
time.sleep(1)
await message.delete()
message = ctx.message
await client.message.delete(message )
</code>```

It just tells me "AttributeError: module 'client' has no attribute 'fetch_message'"

This code is part of a embed message, everything including The "Self destruct in 3" gets posted, but the editing fails...

答:
I'm not sure why do you want to fetch message when you already got the message object with

```<code>message = await nachrichtchannel.send("self destruct in 3")
</code>```

You can just call edit on that object, you don't have to call the fetch_message

For your edit error you have to pass content as an argument.
Seems like you are trying to do a counter so here's an example:

```<code> @commands.command()
 async def counter(self, ctx):
     message = await ctx.channel.send("Timer 3")
     await asyncio.sleep(1)

     await message.edit(content="Timer 2")
     await asyncio.sleep(1)

     await message.edit(content="Timer 1")
     await asyncio.sleep(1)

     await message.delete()
</code>```

You should use await asyncio.sleep(1) instead of time.sleep(1) to avoid any code hangups.

Body:
I dont know where to put the Coroutine "fetch_message"
I want to edit a message, but it doesnt work the old way

I tried the old way, but it told me it got 2 positional arguments instead of 1...

creator = ctx.message.author.id
await channel.send(f"<@{creator}>", embed=embed)

message_channel = ctx.message.channel
destruction_message = await message_channel .send("Self destruct in 3")
message = await client.fetch_message(destruction_message)
time.sleep(1)
print(message)
print(destruction_message)

await message.edit("Self destruct in 2")
message.edit()
time.sleep(1)
await message.edit("Self destruct in 1")
time.sleep(1)
await message.delete()
message = ctx.message
await client.message.delete(message )

It just tells me "AttributeError: module 'client' has no attribute 'fetch_message'"

This code is part of a embed message, everything including The "Self destruct in 3" gets posted, but the editing fails...

Body:
I'm not sure why do you want to fetch message when you already got the message object with

message = await nachrichtchannel.send("self destruct in 3")

You can just call edit on that object, you don't have to call the fetch_message

For your edit error you have to pass content as an argument.
Seems like you are trying to do a counter so here's an example:

 @commands.command()
 async def counter(self, ctx):
     message = await ctx.channel.send("Timer 3")
     await asyncio.sleep(1)

     await message.edit(content="Timer 2")
     await asyncio.sleep(1)

     await message.edit(content="Timer 1")
     await asyncio.sleep(1)

     await message.delete()

You should use await asyncio.sleep(1) instead of time.sleep(1) to avoid any code hangups.


问:
new variable multiple if/then code from sas to r
I would like to transform in R this sas code to create a new variable from an existing one:

```<code>if eta=0 then eta1=0;
if 0<eta<=4 then eta1=1;
if 4<eta<=9 then eta1=2;
if 9<eta<=14 then eta1=3;
if 14<eta<=19 then eta1=4;
if 19<eta<=24 then eta1=5;
if 24<eta<=29 then eta1=6;
</code>```

.... and so on..

I tried with ifelse but here my new variable eta1 is not binary..

then i tried this:

```<code>eta1[eta<1]<- 0
eta1[eta>=1 & eta<=4]<- 1
eta1[eta>=5 & eta<=9]<- 2
</code>```

and this:

```<code>pop%>%
  mutate(
    eta1=case_when(
      eta%in% c(1,2,3,4)~1,
      eta%in% c(5,6,7,8,9)~2

    )
  )
</code>```

and this

```<code>pop%>%
  mutate(
    eta1=case_when(
      eta%in% c("1","2","3","4")~"1",
      eta%in% c("5","6","7","8","9")~"2"

    )
  )
</code>```

but these don't work..
so I can't understand how to create it without losing infos

How can I fix it?

Thank you!

Body:
I would like to transform in R this sas code to create a new variable from an existing one:

if eta=0 then eta1=0;
if 0<eta<=4 then eta1=1;
if 4<eta<=9 then eta1=2;
if 9<eta<=14 then eta1=3;
if 14<eta<=19 then eta1=4;
if 19<eta<=24 then eta1=5;
if 24<eta<=29 then eta1=6;

.... and so on..

I tried with ifelse but here my new variable eta1 is not binary..

then i tried this:

eta1[eta<1]<- 0
eta1[eta>=1 & eta<=4]<- 1
eta1[eta>=5 & eta<=9]<- 2

and this:

pop%>%
  mutate(
    eta1=case_when(
      eta%in% c(1,2,3,4)~1,
      eta%in% c(5,6,7,8,9)~2

    )
  )

and this

pop%>%
  mutate(
    eta1=case_when(
      eta%in% c("1","2","3","4")~"1",
      eta%in% c("5","6","7","8","9")~"2"

    )
  )

but these don't work..
so I can't understand how to create it without losing infos

How can I fix it?

Thank you!

Body:
i fixed it

pop$eta1<-cut(pop$ETA, c(0,1,5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,120), right=FALSE, labels=c(1:21))


问:
How do you change size of labels in the Bokeh legend in python?
I have several curves (of different colours) plotted in the same figure and would like to widen the corresponding coloured lines in the legend so that they are easier to differentiate when projected onto a large screen.

I can access the properties of the legend fine, for example the legend's label text font size with:

```<code>p1.legend.label_text_font_size = "15pt"
</code>```

where p1 is the figure in question. The problem is I don't know what the term for the "coloured lines" in the legend is and sadly the relevant section in the docs is empty.

答:
In the current version of Bokeh(1.2) you can change the object size in the legend by using:

```<code>p.legend.glyph_height = #some int
p.legend.glyph_width = #some int
p.show()
</code>```

Make sure that you change your legend properties after youve drawn all your geometries.

Body:
I have several curves (of different colours) plotted in the same figure and would like to widen the corresponding coloured lines in the legend so that they are easier to differentiate when projected onto a large screen.

I can access the properties of the legend fine, for example the legend's label text font size with:

p1.legend.label_text_font_size = "15pt"

where p1 is the figure in question. The problem is I don't know what the term for the "coloured lines" in the legend is and sadly the relevant section in the docs is empty.

Body:
In the current version of Bokeh(1.2) you can change the object size in the legend by using:

p.legend.glyph_height = #some int
p.legend.glyph_width = #some int
p.show()

Make sure that you change your legend properties after youve drawn all your geometries.


问:
Django - No such table: main.auth_user__old
I was following the first app tutorial from the official Django docs and got this error when trying to save some changes made through the admin page. I did some research on it, but the possible solutions I was able to find, such as migrating the db, simply won't work. Just let me know if you want to see some specific part of my code.

Following is error:

OperationalError at /admin/polls/question/1/change/ no such table:
  main.auth_user__old Request Method:   POST Request
  URL:  http://127.0.0.1:8000/admin/polls/question/1/change/ Django
  Version:  2.1.4 Exception Type:   OperationalError Exception Value:    no
  such table: main.auth_user__old Exception
  Location: /Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py
  in execute, line 296 Python
  Executable:   /Users/gfioravante/Projects/test_app/ta_env/bin/python3
  Python Version:   3.7.1 Python Path:

  ['/Users/gfioravante/Projects/test_app/test_app',
  '/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python37.zip',
  '/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7',
  '/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload',
  '/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages']
  Server time:  Wed, 5 Dec 2018 16:45:00 +0000

and the traceback:

Environment:

Request Method: POST Request URL:
  http://127.0.0.1:8000/admin/polls/question/1/change/

Django Version: 2.1.4 Python Version: 3.7.1 Installed Applications:
  ['polls.apps.PollsConfig',  'django.contrib.admin',
  'django.contrib.auth',  'django.contrib.contenttypes',
  'django.contrib.sessions',  'django.contrib.messages',
  'django.contrib.staticfiles'] Installed Middleware:
  ['django.middleware.security.SecurityMiddleware',
  'django.contrib.sessions.middleware.SessionMiddleware',
  'django.middleware.common.CommonMiddleware',
  'django.middleware.csrf.CsrfViewMiddleware',
  'django.contrib.auth.middleware.AuthenticationMiddleware',
  'django.contrib.messages.middleware.MessageMiddleware',
  'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File
  "/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/utils.py"
  in _execute
    85.                 return self.cursor.execute(sql, params)

File
  "/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py"
  in execute
    296.         return Database.Cursor.execute(self, query, params)

The above exception (no such table: main.auth_user__old) was the
  direct cause of the following exception:

File
  "/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/core/handlers/exception.py"
  in inner
    34.             response = get_response(request)

File
  "/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/core/handlers/base.py"
  in _get_response
    126.                 response = self.process_exception_by_middleware(e, request)

File
  "/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/core/handlers/base.py"
  in _get_response
    124.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File
  "/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/contrib/admin/options.py"
  in wrapper
    604.                 return self.admin_site.admin_view(view)(*args, **kwargs)

File
  "/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/utils/decorators.py"
  in _wrapped_view
    142.                     response = view_func(request, *args, **kwargs)

File
  "/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/views/decorators/cache.py"
  in _wrapped_view_func
    44.         response = view_func(request, *args, **kwargs)

File
  "/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/contrib/admin/sites.py" in inner
    223.             return view(request, *args, **kwargs)

File
  "/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/contrib/admin/options.py"
  in change_view
    1640.         return self.changeform_view(request, object_id, form_url, extra_context)

File
  "/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/utils/decorators.py"
  in _wrapper
    45.         return bound_method(*args, **kwargs)

File
  "/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/utils/decorators.py"
  in _wrapped_view
    142.                     response = view_func(request, *args, **kwargs)

File
  "/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/contrib/admin/options.py"
  in changeform_view
    1525.             return self._changeform_view(request, object_id, form_url, extra_context)

File
  "/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/contrib/admin/options.py"
  in _changeform_view
    1571.                     self.log_change(request, new_object, change_message)

File
  "/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/contrib/admin/options.py"
  in log_change
    826.             change_message=message,

File
  "/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/contrib/admin/models.py"
  in log_action
    35.             change_message=change_message,

File
  "/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/manager.py"
  in manager_method
    82.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File
  "/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/query.py"
  in create
    413.         obj.save(force_insert=True, using=self.db)

File
  "/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/base.py"
  in save
    718.                        force_update=force_update, update_fields=update_fields)

File
  "/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/base.py"
  in save_base
    748.             updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)

File
  "/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/base.py"
  in _save_table
    831.             result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)

File
  "/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/base.py"
  in _do_insert
    869.                                using=using, raw=raw)

File
  "/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/manager.py"
  in manager_method
    82.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File
  "/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/query.py"
  in _insert
    1136.         return query.get_compiler(using=using).execute_sql(return_id)

File
  "/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/sql/compiler.py"
  in execute_sql
    1289.                 cursor.execute(sql, params)

File
  "/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/utils.py"
  in execute
    100.             return super().execute(sql, params)

File
  "/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/utils.py"
  in execute
    68.         return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)

File
  "/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/utils.py"
  in _execute_with_wrappers
    77.         return executor(sql, params, many, context)

File
  "/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/utils.py"
  in _execute
    85.                 return self.cursor.execute(sql, params)

File
  "/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/utils.py"
  in exit
    89.                 raise dj_exc_value.with_traceback(traceback) from exc_value

File
  "/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/utils.py"
  in _execute
    85.                 return self.cursor.execute(sql, params)

File
  "/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py"
  in execute
    296.         return Database.Cursor.execute(self, query, params)

Exception Type: OperationalError at /admin/polls/question/1/change/
  Exception Value: no such table: main.auth_user__old

答:
Get rid of this issue easily maintaining the following steps:

keep django version 2.1.5 (the issue addressed in this version)
pip install django==2.1.5

Delete the SQLite db

Migrate again python manage.py makemigrations and then python manage.py migrate

Start the server python manage.py runserver

DONE!


问:
How to store an array as a value of a key in another array in PHP?
I am trying to store an array as a value of a key in another array.
I can't use functions like array_push() or a for loop because the second array is being created as a parameter of a function.

I've googled for hours and can't find any answers! I'm new to PHP so I have no idea if this is even possible.

The first array is something like:

    $choices[] = array('1'=>'Blue','2'=>'Red)
```

<p>EDIT: <em>this is the code I meant to add</em></p>

<pre class="lang-php prettyprint-override"><code>    $choices[] = array('1'=>'Blue','2'=>'Red');
</code>```

The lack of ' and ; were a typo. The array is being created in a much more complex way. In my attempt to abstract and simplify it to post it here I missed the ' and ; . Kudos to @diéfani-favareto-piovezan for spotting that.

Now I want to insert this array as a value of a key in another array that is being created in another part of the code:

     return randomFunction('random text', array(
                                   'a' => 'apple',
                                   'b' => 'banana',
                                   'c' =>  ,
                                  )

                          )
```

<p>I want array <code>$choices</code> to be the value of key <code>'c'</code>.</p>

<p>I tried this </p>

<pre class="lang-php prettyprint-override"><code>     return randomFunction('random text', array(
                                   'a' => 'apple',
                                   'b' => 'banana',
                                   'c' => $choices,
                                  ),

                          )
</code>```

but it gives me an error

EDIT: I meant to say that I tried this

     return randomFunction('random text', array(
                                   'a' => 'apple',
                                   'b' => 'banana',
                                   'c' => $choices,
                                  )

                          )
```

<p><em>Once again, when trying to abstract and simplify (the actual array created in the RandomFunction has about 250 lines) I added the extra comma by mistake. Kudos to @brevis, @Nick and @tim for spotting this and bringing it to my attention.</em></p>

<pre class="lang-php prettyprint-override"><code>    Parse error: syntax error, unexpected '=>' (T_DOUBLE_ARROW), expecting ')' in /filename.php line 120
</code>```

The error mentions another line down the code, but I know that it is not the cause because if I remove

                                   'c' => $choices,
```

<p>there is no error.</p>

<p>EDIT: <em>I meant to say "before I added the <code>'c'</code> line" (and not "if I remove it" ), there were no errors. I also could have added that the creation of <code>$choices</code> comes before the <code>randomFunction</code> array, so that's another reason why I knew there were no errors there.</em></p>

<p><em>CONCLUSION:
As I mentioned, the error was an extra <code>),</code> after the <code>'c'</code> line, which I failed to reproduce here when trying to simplify the code. I think that when I added the <code>'c'</code> line in my actual code I must have added an extra <code>),</code> by mistake. I was only able to find that because @nick said that the <code>randomFunction</code> code (the one after "I tried this") should be working. That was the answer I needed to confirm that the error was not on that line. Thanks to to @dont-panic's comment, I looked more carefully into the error message I was getting and found the extra <code>)'</code>. At the end of the day, eveybody helped me. So thank you all!</em></p>

<p><em>To anyone who has come across this, the working code is</em>:</p>

<pre class="lang-php prettyprint-override"><code>    $choices[] = array('1'=>'Blue','2'=>'Red');

     return randomFunction('random text', array(
                                   'a' => 'apple',
                                   'b' => 'banana',
                                   'c' => $choices,
                                  )

                          );
</code>```

*

答:
Your code is missing a single quote mark and semicolon after Red.

Try this and see if it works:

```<code>$choices[] = array('1'=>'Blue','2'=>'Red');
</code>```

Body:
I am trying to store an array as a value of a key in another array.
I can't use functions like array_push() or a for loop because the second array is being created as a parameter of a function.

I've googled for hours and can't find any answers! I'm new to PHP so I have no idea if this is even possible.

The first array is something like:

    $choices[] = array('1'=>'Blue','2'=>'Red)

EDIT: this is the code I meant to add

    $choices[] = array('1'=>'Blue','2'=>'Red');

The lack of ' and ; were a typo. The array is being created in a much more complex way. In my attempt to abstract and simplify it to post it here I missed the ' and ; . Kudos to @diéfani-favareto-piovezan for spotting that.

Now I want to insert this array as a value of a key in another array that is being created in another part of the code:

     return randomFunction('random text', array(
                                   'a' => 'apple',
                                   'b' => 'banana',
                                   'c' =>  ,
                                  )

                          )

I want array $choices to be the value of key 'c'.

I tried this

     return randomFunction('random text', array(
                                   'a' => 'apple',
                                   'b' => 'banana',
                                   'c' => $choices,
                                  ),

                          )

but it gives me an error

EDIT: I meant to say that I tried this

     return randomFunction('random text', array(
                                   'a' => 'apple',
                                   'b' => 'banana',
                                   'c' => $choices,
                                  )

                          )

Once again, when trying to abstract and simplify (the actual array created in the RandomFunction has about 250 lines) I added the extra comma by mistake. Kudos to @brevis, @Nick and @tim for spotting this and bringing it to my attention.

    Parse error: syntax error, unexpected '=>' (T_DOUBLE_ARROW), expecting ')' in /filename.php line 120

The error mentions another line down the code, but I know that it is not the cause because if I remove

                                   'c' => $choices,

there is no error.

EDIT: I meant to say "before I added the 'c' line" (and not "if I remove it" ), there were no errors. I also could have added that the creation of $choices comes before the randomFunction array, so that's another reason why I knew there were no errors there.

CONCLUSION:
As I mentioned, the error was an extra ), after the 'c' line, which I failed to reproduce here when trying to simplify the code. I think that when I added the 'c' line in my actual code I must have added an extra ), by mistake. I was only able to find that because @nick said that the randomFunction code (the one after "I tried this") should be working. That was the answer I needed to confirm that the error was not on that line. Thanks to to @dont-panic's comment, I looked more carefully into the error message I was getting and found the extra )'. At the end of the day, eveybody helped me. So thank you all!

To anyone who has come across this, the working code is:

    $choices[] = array('1'=>'Blue','2'=>'Red');

     return randomFunction('random text', array(
                                   'a' => 'apple',
                                   'b' => 'banana',
                                   'c' => $choices,
                                  )

                          );

*

Body:
Your code is missing a single quote mark and semicolon after Red.

Try this and see if it works:

$choices[] = array('1'=>'Blue','2'=>'Red');


问:
Add empty document to collection
I am trying to add a new document and collection to my database. I know I can just add a document and if the collection where it is supposed to be will be added if doe not exist.
My question is: how can I add an empty document to a new collection in my database?

I have tried this code, from the android developers site:

```<code>ApiFuture<WriteResult> future = db.collection("cities").document("LA");
// ...
// future.get() blocks on response
System.out.println("Update time : " + future.get().getUpdateTime());
</code>```

But it gives me error in the ApiFuture part that I can't resolve.
So I tried this:

```<code>db.collection(mail).document("tarefa");
</code>```

(mail is a string)
But it does not work.
Does anyone know what I should do?

答:
The db.collection("cities").document("LA") only creates a reference to a document. It doesn't write any data yet.

This is probably the shortest way to write an empty document:

```<code>db.collection("cities").document("LA").set(new HashMap<String, Object>())
</code>```

If that doesn't work, an update should definitely work:

```<code>db.collection("cities").document("BJ")
    .set(new HashMap<String, Object>(), SetOptions.merge());
</code>```

Title: Add empty document to collection

Body:
I am trying to add a new document and collection to my database. I know I can just add a document and if the collection where it is supposed to be will be added if doe not exist.
My question is: how can I add an empty document to a new collection in my database?

I have tried this code, from the android developers site:

ApiFuture<WriteResult> future = db.collection("cities").document("LA");
// ...
// future.get() blocks on response
System.out.println("Update time : " + future.get().getUpdateTime());

But it gives me error in the ApiFuture part that I can't resolve.
So I tried this:

db.collection(mail).document("tarefa");

(mail is a string)
But it does not work.
Does anyone know what I should do?

Body:
The db.collection("cities").document("LA") only creates a reference to a document. It doesn't write any data yet.

This is probably the shortest way to write an empty document:

db.collection("cities").document("LA").set(new HashMap<String, Object>())

If that doesn't work, an update should definitely work:

db.collection("cities").document("BJ")
    .set(new HashMap<String, Object>(), SetOptions.merge());


问:
Unity Transform position isn't changing position
I am trying to change the position of a border to be just off the top of the screen. I did this by taking the top of the screen, then adding half the scale of the object (since it is centered in the middle). However, when I do this nothing changes at all. I printed out the coordinates and it says it moved, but it didn't. Here is my code (from the Start() method in WallScalar class).

Note: The following code is the only code in the WallScalar class, this script is applied to the "Top" gameObject.

```<code>      transform.position =
      new Vector3(0, Camera.main.orthographicSize + (transform.localScale.y / 2), 1);

      print("yCoor: " + transform.position.y);
</code>```

Since the object has a scale of one, and the top is at y = 5, the object should be placed at y = 5.5f. With that print statement, it says it is at y = 5.5f but it didn't move on my screen. Here is an image for more details:

As you can see, it says it was moved to yCoor = 5.5f, but it didnt, because when I manually type 5.5 for y, it isn't visible, it is just off the screen.
Any help with figuring this out would be greatly appreciated.

Update: If i put a print statement such as

```<code>      print("yCoorU: " + transform.position.y);
</code>```

In my update method, it reads y = 5, so something is forcing it back to be 5, but know that nothing else has any call to the "Top" GameObject that the script is being applied to.

答:
So, what I figured out is that you have to disable the object you are trying to change position on, set the position and than enable it.

```<code>Player.SetActive(false);
Player.transform.position = new Vector3(PositionX, PositionY, PositionZ);
Player.SetActive(true);
</code>```

This might be because during gameplay the player or the object you are trying to move is in static mode.

Chirag Shah

Body:
I am trying to change the position of a border to be just off the top of the screen. I did this by taking the top of the screen, then adding half the scale of the object (since it is centered in the middle). However, when I do this nothing changes at all. I printed out the coordinates and it says it moved, but it didn't. Here is my code (from the Start() method in WallScalar class).

Note: The following code is the only code in the WallScalar class, this script is applied to the "Top" gameObject.

      transform.position =
      new Vector3(0, Camera.main.orthographicSize + (transform.localScale.y / 2), 1);

      print("yCoor: " + transform.position.y);

Since the object has a scale of one, and the top is at y = 5, the object should be placed at y = 5.5f. With that print statement, it says it is at y = 5.5f but it didn't move on my screen. Here is an image for more details:

As you can see, it says it was moved to yCoor = 5.5f, but it didnt, because when I manually type 5.5 for y, it isn't visible, it is just off the screen.
Any help with figuring this out would be greatly appreciated.

Update: If i put a print statement such as

      print("yCoorU: " + transform.position.y);

In my update method, it reads y = 5, so something is forcing it back to be 5, but know that nothing else has any call to the "Top" GameObject that the script is being applied to.

Body:
So, what I figured out is that you have to disable the object you are trying to change position on, set the position and than enable it.

Player.SetActive(false);
Player.transform.position = new Vector3(PositionX, PositionY, PositionZ);
Player.SetActive(true);

This might be because during gameplay the player or the object you are trying to move is in static mode.

Chirag Shah


问:
Suggested Method to Forward POST Parameters Through login_required Decorator?
I am currently having the problem that when I use the login_required decorator from django.contrib.auth.decorators on any of my views, my POST parameters do not arrive at the protected view whenever the decorator did redirect (to the login page) and back again to the protected view.  Suggestions about how to work around this (preferably maintaining the convenience of the login_required decorator and the POST method) appreciated!

This page appears to be a contested Django ticket about the matter.  Although the bug/enhancement was framed in terms of template vs. view logic instead of just making parameters accessible to a view, which is my problem.

答:
There's no easy way to do this, not to mention the fact that you want to use the "login_required" decorator. You can do your own view that checks for the is_authenticated method and does the right thing, like serializing the POST data and passing around, but this is very error prone.

The easy workaround is to change your form to do GET instead of POST.

OwnerDisplayName: DGGenuine

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: DGGenuine

OwnerDisplayName: Tiago


问:
C# Lambda expression for CreateWebHostBuilder
I want to use the WaitForSystemsManagerReloadToComplete() Extensions as documented in the "Reloading in AWS Lambda" section of this Read Me.

I believe I have written the right syntax to call it but since it is not an easy process to test I wanted to confirm the syntax. The code:

```<code>public class Program
{
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args)
        {
            return WebHost.CreateDefaultBuilder(args)
                      .ConfigureAppConfiguration(builder =>
                      {
                          builder
                            .AddSystemsManager("/AppName")
                            .Build()
                            .WaitForSystemsManagerReloadToComplete(TimeSpan.FromSeconds(5));
                      })
                      .UseStartup<Startup>();
        }
 }
</code>```

My concern is that I although I call WaitForSystemsManagerReloadToComplete() in the Lambda Expression, I'm wondering if it affects the executing thread as designed.

答:
From looking at the samples on Github I would say that calling it in the expression is wrong. You should not have to build the configuration in the expression just to make that call. Instead move that code to the Startup and call it there.

```<code>public class Program {
    public static void Main(string[] args) {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) {
        return WebHost.CreateDefaultBuilder(args)
                  .ConfigureAppConfiguration(builder => {
                      builder.AddSystemsManager("/AppName");
                  })
                  .UseStartup<Startup>();
    }
}
</code>```

Startup

```<code>public class Startup {
    public Startup(IConfiguration configuration) {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services) {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

        //...
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
        if (env.IsDevelopment()) {
            app.UseDeveloperExceptionPage();
        }

        app.UseMvc();

        Configuration.WaitForSystemsManagerReloadToComplete(TimeSpan.FromSeconds(5));
    }
}
</code>```

Body:
I want to use the WaitForSystemsManagerReloadToComplete() Extensions as documented in the "Reloading in AWS Lambda" section of this Read Me.

I believe I have written the right syntax to call it but since it is not an easy process to test I wanted to confirm the syntax. The code:

public class Program
{
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args)
        {
            return WebHost.CreateDefaultBuilder(args)
                      .ConfigureAppConfiguration(builder =>
                      {
                          builder
                            .AddSystemsManager("/AppName")
                            .Build()
                            .WaitForSystemsManagerReloadToComplete(TimeSpan.FromSeconds(5));
                      })
                      .UseStartup<Startup>();
        }
 }

My concern is that I although I call WaitForSystemsManagerReloadToComplete() in the Lambda Expression, I'm wondering if it affects the executing thread as designed.

Body:
From looking at the samples on Github I would say that calling it in the expression is wrong. You should not have to build the configuration in the expression just to make that call. Instead move that code to the Startup and call it there.

public class Program {
    public static void Main(string[] args) {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) {
        return WebHost.CreateDefaultBuilder(args)
                  .ConfigureAppConfiguration(builder => {
                      builder.AddSystemsManager("/AppName");
                  })
                  .UseStartup<Startup>();
    }
}

Startup

public class Startup {
    public Startup(IConfiguration configuration) {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services) {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

        //...
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
        if (env.IsDevelopment()) {
            app.UseDeveloperExceptionPage();
        }

        app.UseMvc();

        Configuration.WaitForSystemsManagerReloadToComplete(TimeSpan.FromSeconds(5));
    }
}


问:
How to re-ID multidimensional arrays in PHP?
I have a multidimensional array in php. I have also a DB, which has the same data, but different ID for them. I have to match the two ...

```<code>$ad_types = array(
    array('Személyi kölcsön', 0, array(
        'Adósságrendező hitel',
        'Hitel autóvásárlásra',
        'Szabad felhasználású hitel',
        'Hitelkiváltás',
        'Hitel fix részletre',
        'Online hitel',
        'Akciós hitel',
        'Gyorskölcsön',
        'Hitel alacsony kamatra',
        'Kis összegű hitel',
    )),
    array('Jelzáloghitel', 0, array(
        'Jelzáloghitel használt lakásra',
        'CSOK',
        'Akciós jelzáloghitelek',
        'Adósságrendező hitel',
        'Szabad felhasználású hitel',
        'Jelzáloghitel építésre/bővítésre',
        'Jelzáloghitel korszerűsítésre',
        'Jelzáloghitel fix részletre',
        'Jelzáloghitel alacsony kamatra'
    )),
    array('Hitelkártya', 5, array(
        'Pontgyűjtő',
        'Akciós',
        'Aranykártya',
        'Kedvező tankolás'
    )),
);
</code>```

I have to re-ID them, so their ID would look like:

```<code>+----+-----------------------------------------+
| id | name                                    |
+----+-----------------------------------------+
|  0 | Személyi kölcsön                        |
|  1 | Adósságrendező hitel                    |
|  2 | Hitel autóvásárlásra                    |
|  3 | Szabad felhasználású hitel              |
|  4 | Hitelkiváltás                           |
|  5 | Hitel fix részletre                     |
|  6 | Online hitel                            |
|  7 | Akciós hitel                            |
|  8 | Gyorskölcsön                            |
|  9 | Hitel alacsony kamatra                  |
| 10 | Kis összegű hitel                       |
| 11 | Jelzáloghitel                           |
| 12 | Jelzáloghitel használt lakásra          |
| 13 | CSOK                                    |
| 14 | Akciós jelzáloghitelek                  |
| 15 | Adósságrendező hitel                    |
| 16 | Szabad felhasználású hitel              |
| 17 | Jelzáloghitel építésre/bővítésre        |
| 18 | Jelzáloghitel korszerűsítésre           |
| 19 | Jelzáloghitel fix részletre             |
| 20 | Jelzáloghitel alacsony kamatra          |
| 21 | Hitelkártya                             |
| 22 | Pontgyűjtő                              |
| 23 | Akciós                                  |
| 24 | Aranykártya                             |
| 25 | Kedvező tankolás                        |
+----+-----------------------------------------+
</code>```

how can i do that, do their ID will match with the one in my DB?

答:
```<code>function reIdArray($array)
{
    $reIdArray = array();
    foreach ($array as $subArray) {
        $reIdArray = array_merge($reIdArray, array($subArray[0]), $subArray[2]);
    }
    return $reIdArray;
}

// print_r(reIdArray($ad_types));
</code>```

Body:
I have a multidimensional array in php. I have also a DB, which has the same data, but different ID for them. I have to match the two ...

$ad_types = array(
    array('Személyi kölcsön', 0, array(
        'Adósságrendező hitel',
        'Hitel autóvásárlásra',
        'Szabad felhasználású hitel',
        'Hitelkiváltás',
        'Hitel fix részletre',
        'Online hitel',
        'Akciós hitel',
        'Gyorskölcsön',
        'Hitel alacsony kamatra',
        'Kis összegű hitel',
    )),
    array('Jelzáloghitel', 0, array(
        'Jelzáloghitel használt lakásra',
        'CSOK',
        'Akciós jelzáloghitelek',
        'Adósságrendező hitel',
        'Szabad felhasználású hitel',
        'Jelzáloghitel építésre/bővítésre',
        'Jelzáloghitel korszerűsítésre',
        'Jelzáloghitel fix részletre',
        'Jelzáloghitel alacsony kamatra'
    )),
    array('Hitelkártya', 5, array(
        'Pontgyűjtő',
        'Akciós',
        'Aranykártya',
        'Kedvező tankolás'
    )),
);

I have to re-ID them, so their ID would look like:

+----+-----------------------------------------+
| id | name                                    |
+----+-----------------------------------------+
|  0 | Személyi kölcsön                        |
|  1 | Adósságrendező hitel                    |
|  2 | Hitel autóvásárlásra                    |
|  3 | Szabad felhasználású hitel              |
|  4 | Hitelkiváltás                           |
|  5 | Hitel fix részletre                     |
|  6 | Online hitel                            |
|  7 | Akciós hitel                            |
|  8 | Gyorskölcsön                            |
|  9 | Hitel alacsony kamatra                  |
| 10 | Kis összegű hitel                       |
| 11 | Jelzáloghitel                           |
| 12 | Jelzáloghitel használt lakásra          |
| 13 | CSOK                                    |
| 14 | Akciós jelzáloghitelek                  |
| 15 | Adósságrendező hitel                    |
| 16 | Szabad felhasználású hitel              |
| 17 | Jelzáloghitel építésre/bővítésre        |
| 18 | Jelzáloghitel korszerűsítésre           |
| 19 | Jelzáloghitel fix részletre             |
| 20 | Jelzáloghitel alacsony kamatra          |
| 21 | Hitelkártya                             |
| 22 | Pontgyűjtő                              |
| 23 | Akciós                                  |
| 24 | Aranykártya                             |
| 25 | Kedvező tankolás                        |
+----+-----------------------------------------+

how can i do that, do their ID will match with the one in my DB?


问:
how to test the relevant row in the db table has been locked using postgresql
I have one table and i locked it using id for update.

```<code>select name from tablename where id=2 for update
</code>```

how can i test the relevant row in the db table has been locked.

答:
If you're sure that the row with id=2 exists, you can use:

```<code>select name from tablename where id=2
for update skip locked
</code>```

If the result is empty, it means the row is locked by another user (or it doesn't exist).

You could also use:

```<code>select name from tablename where id=2
for update nowait
</code>```

If the row exists, and is locked by another user, then the query will throw an error.

Body:
I have one table and i locked it using id for update.

select name from tablename where id=2 for update

how can i test the relevant row in the db table has been locked.

Body:
If you're sure that the row with id=2 exists, you can use:

select name from tablename where id=2
for update skip locked

If the result is empty, it means the row is locked by another user (or it doesn't exist).

You could also use:

select name from tablename where id=2
for update nowait

If the row exists, and is locked by another user, then the query will throw an error.


问:
Get the amount of days between two given days of the week
I want to find out how many days there are between two given days of the week.

This looks to be a case for a well executed slice method; but I just can't get my head around it.

```<code>const days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']

let today = 'Thursday'
let dispatch = 'Monday'
let remaining = '???'

console.log(`${remaining} Days until the next dispatch`)
</code>```

Monday to Thursday is easy enough :

```<code>let remaining = days.slice(days.indexOf('Monday'), days.indexOf('Thursday')).length + 1
</code>```

But Thursday to Monday (for example) needs some logic that I can't figure out.

答:
I think you can directly subtract two .indexOf() values without calling .slice(), no? Like this:

const days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']

let today = 'Thursday'
let dispatch = 'Monday'
let remaining = days.indexOf(dispatch) - days.indexOf(today) + 1
if (remaining < 1) {
    remaining += days.length
}

console.log(`${remaining} Days until the next dispatch`)```

Body:
I want to find out how many days there are between two given days of the week.

This looks to be a case for a well executed slice method; but I just can't get my head around it.

const days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']

let today = 'Thursday'
let dispatch = 'Monday'
let remaining = '???'

console.log(`${remaining} Days until the next dispatch`)

Monday to Thursday is easy enough :

let remaining = days.slice(days.indexOf('Monday'), days.indexOf('Thursday')).length + 1

But Thursday to Monday (for example) needs some logic that I can't figure out.


问:
Single Sign On - Cross Domain Authentication (@auth0/angular2-jwt)
I have several angular applications (in different sub-domains) and a main angular application (in the main domain). I'm using @auth0/angular2-jwt library to manage the authentication. It's working well, but not working for Single Sign On. I have to sign in every sub-domain and I need this to be done just once (in the main domain or any of the sub-domains).

I've tried with a regular expression for the whitelistedDomains, but it's not working:

```<code>JwtModule.forRoot({
  config: {
    tokenGetter: tokenGetter,
    whitelistedDomains: [new RegExp(`(?:([^.]+)\.)*example\.com`)]
    ]
  }
})
</code>```

So, how can I authenticate users to all sub-domains if the user signed in to the main domain or any of the sub-domains?

user signed-in successfully in example.com or x.example.com

the user must be automatically authenticated to y.example.com, z.example.com, etc.

答:
I would be happy to help with your question!

How can I authenticate users to all sub-domains if the user signed in to the main domain or any of the sub-domains?

Single Sign On seems to be a great fit for your use case vs Regex as it will enable you to authenticate your users across all your sub domains. SSO is enabled by default for all tenants that are that have been created within the last year. The easiest way to use SSO is by leveraging the Universal Login.

If you can use Universal Login you can just set the auth requests to always do prompt=none and this should check for cookies in the hidden iframe. However, if interaction is required you will get the "login required" warn in tenant logs and the end user will be challenged for credentials. I have referenced some core documentation that should help you on your journey.

https://auth0.com/docs/sso/current/sso-auth0

https://auth0.com/docs/quickstart/spa/angular2/01-login

Body:
I have several angular applications (in different sub-domains) and a main angular application (in the main domain). I'm using @auth0/angular2-jwt library to manage the authentication. It's working well, but not working for Single Sign On. I have to sign in every sub-domain and I need this to be done just once (in the main domain or any of the sub-domains).

I've tried with a regular expression for the whitelistedDomains, but it's not working:

JwtModule.forRoot({
  config: {
    tokenGetter: tokenGetter,
    whitelistedDomains: [new RegExp(`(?:([^.]+)\.)*example\.com`)]
    ]
  }
})

So, how can I authenticate users to all sub-domains if the user signed in to the main domain or any of the sub-domains?

user signed-in successfully in example.com or x.example.com

the user must be automatically authenticated to y.example.com, z.example.com, etc.


问:
How do I append more than one child element to a parent element Javascript
Good day everyone, I am new to programming, so I am sorry if my question looks stupid or too simple. I am trying to append 4 different child elements on a parent element.

I am building a To Do List app, and I want the app to work in such a way that when the 'task' is entered and saved, the entered task will appear on a list with a checkbox, a delete button, and an edit button. I tried appending the child elements on their parent element using .appendchild() but it's not working.

```<code><Ol id="ol">
    <li>
        <input type="checkbox">Read a novel
        <button>Edit</button>
        <button>Delete</button>
    </li>
    <li>
        <input type="checkbox">Take a walk
        <button>Edit</button>
        <button>Delete</button>
    </li>
</Ol>

let inputToDoList= document.getElementById('inputToDoList');

let addButton=  document.getElementById('addButton');
let editButton= document.createElement('button');
let deleteButton= document.createElement('button');
let checkInput= document.createElement('input');

checkInput.type= "checkbox"
deleteButton.innerText= "Delete"
editButton.innerText= "Edit"

addButton.addEventListener('click', () => {
   let ol= document.getElementsByTagName('ol')[0];
   let li= document.createElement('li');

   li.textContent= inputToDoList.value
   ol.appendChild(checkInput)
   ol.appendChild(li)
   ol.appendChild(editButton)
   ol.appendChild(deleteButton)

   if(inputToDoList.value.length > 0){
      inputToDoList.value='';
}
});
</code>```

What I want the program to do is to add inputToDoList.value, checkbox, edit button and delete button to the  each time the 'save' button is clicked on but the function only works when I click on the save button the first time. When I click on the 'save' button the subsequent times, it's only the inputToDoList.value that is added to the list. The other elements i.e. checkbox, edit button and delete button will no longer be added.

答:
you have to use cloneNode => https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode

// making of LI type element, with checkBox, Text and buttons Edit / delete :
const LI_toDo      = document.createElement('li')
,     chk_toDo     = document.createElement('input')
,     txt_toDo     = document.createElement('span')
,     bt_edit_toDo = document.createElement('button')
,     bt_del_toDo  = document.createElement('button')
;
chk_toDo.type            = "checkbox";
bt_edit_toDo.textContent = 'Edit';
bt_del_toDo.textContent  = 'Delete';

LI_toDo.appendChild(chk_toDo);
LI_toDo.appendChild(txt_toDo);
LI_toDo.appendChild(bt_edit_toDo);
LI_toDo.appendChild(bt_del_toDo);
// - - - - - - - - - -- - - - -- - - -making completed...

const inputToDoList = document.getElementById('inputToDoList')
,     List_ol       = document.getElementById('ol')
;

document.getElementById('addButton').onclick = function()
{
  txt_toDo.textContent  = inputToDoList.value;
  inputToDoList.value   = '';
  List_ol.appendChild( LI_toDo.cloneNode(true) );
}

List_ol.onclick = function(e)              //  clicks events over 'ol' elements
{
  if (!e.target.matches('button')) return; // check if it is on a button

  switch (e.target.textContent)
  {
    case 'Edit':    EditButton(e.target.parentNode);    break; //  e.target.parentNode
    case 'Delete':  DeleteButton(e.target.parentNode);  break; // === LI parent of clicked button
  }
}

function EditButton(toDo_LI)
{
  let SpanTxt = toDo_LI.querySelector('span')
  ,   change  = prompt('Edit..',SpanTxt.textContent )
  ;
  if (change) { SpanTxt.textContent = change }
}

function DeleteButton(toDo_LI)
{
  let SpanTxt = toDo_LI.querySelector('span')
  ,   Del     = confirm(`please confirm delete of ${SpanTxt.textContent}`)
  ;
  if (Del) { List_ol.removeChild( toDo_LI ) }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>span {
  display: inline-block;
  width: 200px;
  padding : 0 5px 5px 0;
  border-bottom :1px solid lightblue;
}
button { margin: 5px }</code>```

  what to do : <input id="inputToDoList" type="text">
  <button id="addButton">add</button>

```

Body:
Good day everyone, I am new to programming, so I am sorry if my question looks stupid or too simple. I am trying to append 4 different child elements on a parent element.

I am building a To Do List app, and I want the app to work in such a way that when the 'task' is entered and saved, the entered task will appear on a list with a checkbox, a delete button, and an edit button. I tried appending the child elements on their parent element using .appendchild() but it's not working.

        <input type="checkbox">Read a novel
        <button>Edit</button>
        <button>Delete</button>

        <input type="checkbox">Take a walk
        <button>Edit</button>
        <button>Delete</button>

let inputToDoList= document.getElementById('inputToDoList');

let addButton=  document.getElementById('addButton');
let editButton= document.createElement('button');
let deleteButton= document.createElement('button');
let checkInput= document.createElement('input');

checkInput.type= "checkbox"
deleteButton.innerText= "Delete"
editButton.innerText= "Edit"

addButton.addEventListener('click', () => {
   let ol= document.getElementsByTagName('ol')[0];
   let li= document.createElement('li');

   li.textContent= inputToDoList.value
   ol.appendChild(checkInput)
   ol.appendChild(li)
   ol.appendChild(editButton)
   ol.appendChild(deleteButton)

   if(inputToDoList.value.length > 0){
      inputToDoList.value='';
}
});

What I want the program to do is to add inputToDoList.value, checkbox, edit button and delete button to the  each time the 'save' button is clicked on but the function only works when I click on the save button the first time. When I click on the 'save' button the subsequent times, it's only the inputToDoList.value that is added to the list. The other elements i.e. checkbox, edit button and delete button will no longer be added.

Body:
you have to use cloneNode => https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode

// making of LI type element, with checkBox, Text and buttons Edit / delete :
const LI_toDo      = document.createElement('li')
,     chk_toDo     = document.createElement('input')
,     txt_toDo     = document.createElement('span')
,     bt_edit_toDo = document.createElement('button')
,     bt_del_toDo  = document.createElement('button')
;
chk_toDo.type            = "checkbox";
bt_edit_toDo.textContent = 'Edit';
bt_del_toDo.textContent  = 'Delete';

LI_toDo.appendChild(chk_toDo);
LI_toDo.appendChild(txt_toDo);
LI_toDo.appendChild(bt_edit_toDo);
LI_toDo.appendChild(bt_del_toDo);
// - - - - - - - - - -- - - - -- - - -making completed...

const inputToDoList = document.getElementById('inputToDoList')
,     List_ol       = document.getElementById('ol')
;

document.getElementById('addButton').onclick = function()
{
  txt_toDo.textContent  = inputToDoList.value;
  inputToDoList.value   = '';
  List_ol.appendChild( LI_toDo.cloneNode(true) );
}

List_ol.onclick = function(e)              //  clicks events over 'ol' elements
{
  if (!e.target.matches('button')) return; // check if it is on a button

  switch (e.target.textContent)
  {
    case 'Edit':    EditButton(e.target.parentNode);    break; //  e.target.parentNode
    case 'Delete':  DeleteButton(e.target.parentNode);  break; // === LI parent of clicked button
  }
}

function EditButton(toDo_LI)
{
  let SpanTxt = toDo_LI.querySelector('span')
  ,   change  = prompt('Edit..',SpanTxt.textContent )
  ;
  if (change) { SpanTxt.textContent = change }
}

function DeleteButton(toDo_LI)
{
  let SpanTxt = toDo_LI.querySelector('span')
  ,   Del     = confirm(`please confirm delete of ${SpanTxt.textContent}`)
  ;
  if (Del) { List_ol.removeChild( toDo_LI ) }
}

span {
  display: inline-block;
  width: 200px;
  padding : 0 5px 5px 0;
  border-bottom :1px solid lightblue;
}
button { margin: 5px }

<div>
  <label>what to do : </label><input id="inputToDoList" type="text">
  <button id="addButton">add</button>
</div>

<ol id="ol"></ol>


问:
Trying to send an array in a circle through several ranks in MPI, but am getting seg faults. Can anyone please tell me why?
I'm trying to send an array from one process (rank) to another in a "circle" using MPI in C. I can get it to work just fine using single integers, but am getting segmentation faults when I try to send the array through.

```<code>{
int rank;
int numRanks;

MPI_Init(&argc, &argv);

MPI_Comm_size(MPI_COMM_WORLD, &numRanks);

MPI_Comm_rank(MPI_COMM_WORLD, &rank);

int arraysize = 100;

int *array;

if (rank == 0) {
    array = malloc(sizeof(int)*arrasize);
    for (int i = 0; i < arraysize; i++) {
        array[i] = 1;
    }
    double starttime = MPI_Wtime();
    MPI_Send(&array, arraysize, MPI_INT, (rank+1), 0, MPI_COMM_WORLD);
    MPI_Recv(&array, arraysize, MPI_INT, numRanks-1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
    double endtime = MPI_Wtime();
    printf("Rank %d got array from Rank %d in %lf", rank, numRanks-1, endtime-starttime);
} else if (rank == (numRanks-1)) {
    MPI_Recv(&array, arraysize, MPI_INT, rank-1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
    printf("Rank %d got array from Rank %d", rank, rank-1);
    MPI_Send(&array, arraysize, MPI_INT, 0, 0, MPI_COMM_WORLD);
} else {
    MPI_Recv(&array, arraysize, MPI_INT, rank-1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
    printf("Rank %d got array from Rank %d", rank, rank-1);
    MPI_Send(&array, arraysize, MPI_INT, (rank+1), 0, MPI_COMM_WORLD);
}

free(array);

MPI_Finalize();
return 0;

}
</code>```

Here's the error message (I'm only using three ranks right now for simplicity):

```<code>Rank 1 got array from Rank 0
[winston:42137] *** Process received signal ***
[winston:42137] Signal: Segmentation fault (11)
[winston:42137] Signal code: Address not mapped (1)
[winston:42137] Failing at address: 0x7add28
</code>```

and then more of the same for each rank trying to send and receive the array

any help anyone can provide would be greatly appreciated!!

答:
Your array is not pointing to a valid memory address in every process (rank) other than the 0-th.
This will make your program crash when trying to write something in a random (i.e. invalid) address, which is when you call MPI_Recv(&array, arraysize....

(Thanks to Gilles Gouaillardet pointed out in the comment) And you should pass array (not &array) to MPI functions because itself is the pointer to an address where is allocated to you to store some int.

So, the solution will be:

Run array = malloc(sizeof(int)*arrasize); on every process.

Change MPI_Recv(&array (and MPI_Send(&array) to MPI_Recv(array (and MPI_Send(array.

Body:
I'm trying to send an array from one process (rank) to another in a "circle" using MPI in C. I can get it to work just fine using single integers, but am getting segmentation faults when I try to send the array through.

{
int rank;
int numRanks;

MPI_Init(&argc, &argv);

MPI_Comm_size(MPI_COMM_WORLD, &numRanks);

MPI_Comm_rank(MPI_COMM_WORLD, &rank);

int arraysize = 100;

int *array;

if (rank == 0) {
    array = malloc(sizeof(int)*arrasize);
    for (int i = 0; i < arraysize; i++) {
        array[i] = 1;
    }
    double starttime = MPI_Wtime();
    MPI_Send(&array, arraysize, MPI_INT, (rank+1), 0, MPI_COMM_WORLD);
    MPI_Recv(&array, arraysize, MPI_INT, numRanks-1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
    double endtime = MPI_Wtime();
    printf("Rank %d got array from Rank %d in %lf", rank, numRanks-1, endtime-starttime);
} else if (rank == (numRanks-1)) {
    MPI_Recv(&array, arraysize, MPI_INT, rank-1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
    printf("Rank %d got array from Rank %d", rank, rank-1);
    MPI_Send(&array, arraysize, MPI_INT, 0, 0, MPI_COMM_WORLD);
} else {
    MPI_Recv(&array, arraysize, MPI_INT, rank-1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
    printf("Rank %d got array from Rank %d", rank, rank-1);
    MPI_Send(&array, arraysize, MPI_INT, (rank+1), 0, MPI_COMM_WORLD);
}

free(array);

MPI_Finalize();
return 0;

}

Here's the error message (I'm only using three ranks right now for simplicity):

Rank 1 got array from Rank 0
[winston:42137] *** Process received signal ***
[winston:42137] Signal: Segmentation fault (11)
[winston:42137] Signal code: Address not mapped (1)
[winston:42137] Failing at address: 0x7add28

and then more of the same for each rank trying to send and receive the array

any help anyone can provide would be greatly appreciated!!


问:
How can I read pre-fetched server side data with a typescript client?
I'm using the below function to return initial server-rendered markup and data in case of lack of javascript support:

```<code>    export const serverRender = async () => {
        const { port, host } = config;
        const resp = await
    axios.get(`http://${host}:${port}/testData.json`);

        const initialData = resp.data;
        return {
            initialMarkup: ReactDOMServer.renderToString(<App initialData={initialData} />),
            initialData,
        };
    };
</code>```

I serve this data to my template as follows (details aren't that important):

```<code>    app.setViewEngine("pug");
    app.use(express.static(path.join(__dirname, "../public")));
    app.use(express.static(path.join(__dirname, "../assets")));
    app.enableCors();
    await app.listen(PORT, () => {
        console.log(`Nest App listening on port ${PORT}`);
    });
</code>```

In my template, I use pug interpolation to read initialData into the window object in javascript (window.initialData = #{initialData}). If my client was a javascript client I could read from the window object like this: window.initialData, but Typescript doesn't allow this.

My question is, what is the best way to pass pre-fetched data and pass it to the client side? Ie. so I can do something like this when I render the client:

```<code>    /* somehow grab pre-fetched data */
    ReactDOM.hydrate(<App />, document.getElementById("root")); // entry point for webpack
</code>```

I'm not saying this is the best way (which is another reason why I'm asking this question), but in the past for small pure javascript projects I've assigned the data to window as above and then in the client rendering of my react, I've done something like this:

```<code>    const initialData = window.initialData;
    ReactDOM.hydrate(<App initialData={initialData} />, document.getElementById("root")); // entry point for webpack
</code>```

This doesn't fly in Typescript

N/a

Error message for the window case:
Property 'initialData' does not exist on type 'Window'

But I want to find some other way anyways.

答:
Declare how the window global object looks like with your custom initialData value:

```<code>declare global {
    interface Window {
        initialData: any;
    }
}
</code>```

Once you've declared this, then:

```<code>const initialData = window.initialData;
</code>```

should work.

Body:
I'm using the below function to return initial server-rendered markup and data in case of lack of javascript support:

    export const serverRender = async () => {
        const { port, host } = config;
        const resp = await
    axios.get(`http://${host}:${port}/testData.json`);

        const initialData = resp.data;
        return {
            initialMarkup: ReactDOMServer.renderToString(<App initialData={initialData} />),
            initialData,
        };
    };

I serve this data to my template as follows (details aren't that important):

    app.setViewEngine("pug");
    app.use(express.static(path.join(__dirname, "../public")));
    app.use(express.static(path.join(__dirname, "../assets")));
    app.enableCors();
    await app.listen(PORT, () => {
        console.log(`Nest App listening on port ${PORT}`);
    });

In my template, I use pug interpolation to read initialData into the window object in javascript (window.initialData = #{initialData}). If my client was a javascript client I could read from the window object like this: window.initialData, but Typescript doesn't allow this.

My question is, what is the best way to pass pre-fetched data and pass it to the client side? Ie. so I can do something like this when I render the client:

    /* somehow grab pre-fetched data */
    ReactDOM.hydrate(<App />, document.getElementById("root")); // entry point for webpack

I'm not saying this is the best way (which is another reason why I'm asking this question), but in the past for small pure javascript projects I've assigned the data to window as above and then in the client rendering of my react, I've done something like this:

    const initialData = window.initialData;
    ReactDOM.hydrate(<App initialData={initialData} />, document.getElementById("root")); // entry point for webpack

This doesn't fly in Typescript

N/a

Error message for the window case:
Property 'initialData' does not exist on type 'Window'

But I want to find some other way anyways.

Body:
Declare how the window global object looks like with your custom initialData value:

declare global {
    interface Window {
        initialData: any;
    }
}

Once you've declared this, then:

const initialData = window.initialData;

should work.


问:
Is s3 sync supported from sdk instead of cli?
Here is answer about how move files from one s3 bucket to another using sync command from command line (cli):

```<code>aws s3 sync s3://from_my_bucket s3://to_my_other_bucket
</code>```

Can this be invoked from javascript sdk? With searching I did not find any sync named method. So is it supported in sdk?

答:
I needed to sync thousands of files, and decided to make use of AWS Data Pipeline to do it. I update the pipeline definition to point to the correct source and destination folders from my Lambda function, and then invoke it.

It uses 2 S3DataNodes and a CopyActivity.

Body:
Here is answer about how move files from one s3 bucket to another using sync command from command line (cli):

aws s3 sync s3://from_my_bucket s3://to_my_other_bucket

Can this be invoked from javascript sdk? With searching I did not find any sync named method. So is it supported in sdk?