问:
How Update mysql database from form with many row chekecd that contain many data in each row
in table:

<form action="" method="post">

      ID
      Customer Name
      Price
      Control

      <input type="text" value="111" name="userID" />
      <input type="text" value="john" name="fname" />
      <input type="text" value="1000" name="price" />
      <input type="checkbox" value="120" name="checkbox[]" />

      <input type="text" value="115" name="userID" />
      <input type="text" value="mike" name="fname" />
      <input type="text" value="800" name="price" />
      <input type="checkbox" value="120" name="checkbox[]" />

      <input type="text" value="98" name="userID" />
      <input type="text" value="tetra" name="fname" />
      <input type="text" value="125" name="price" />
      <input type="checkbox" value="120" name="checkbox[]" />

  <button type="submit">Update Database</button>
</form>```

when checked one or more checkbox then press button how update mySql table rows contain name and price together?

answers that i see in this site or other sites can solve this problem but with only one record in each row.
in this case each row contain more than one data such as username and price and ett that must update in mysql table.

thanks in advance

答:
If I understood correctly then perhaps the following might be of interest / help.

Firstly modify the form elements to use the same syntax as you assigned to the checkbox field - an unusual name however.

```<code><form action="" method="post">
  <table>
    <tr>
      <td>ID</td>
      <td>Customer Name</td>
      <td>Price</td>
      <td>Control</td>
    </tr>
    <tr>
      <td><input type="text" value="111" name="userID[]" /></td>
      <td><input type="text" value="john" name="fname[]" /></td>
      <td><input type="text" value="1000" name="price[]" /></td>
      <td><input type="checkbox" value="120" name="checkbox[]" /></td>
    </tr>
    <tr>
      <td><input type="text" value="115" name="userID[]" /></td>
      <td><input type="text" value="mike" name="fname[]" /></td>
      <td><input type="text" value="800" name="price[]" /></td>
      <td><input type="checkbox" value="120" name="checkbox[]" /></td>
    </tr>
    <tr>
      <td><input type="text" value="98" name="userID[]" /></td>
      <td><input type="text" value="tetra" name="fname[]" /></td>
      <td><input type="text" value="125" name="price[]" /></td>
      <td><input type="checkbox" value="120" name="checkbox[]" /></td>
    </tr>
  </table>

  <button type="submit">Update Database</button>
</form>
</code>```

Then the PHP to process the request might look like this in basic form:

```<code><?php

    if( $_SERVER['REQUEST_METHOD']=='POST' ){

        $userids=!empty( $_POST['userID'] ) ? $_POST['userID'] : false;
        $fnames=!empty( $_POST['fname'] ) ? $_POST['fname'] : false;
        $prices=!empty( $_POST['price'] ) ? $_POST['price'] : false;
        $checkboxes=!empty( $_POST['checkbox'] ) ? $_POST['checkbox'] : false;

        $sql='update `TABLE` set `fname`=?, `price`=?, `control`=? where `userID`=?';
        $stmt=$db->prepare( $sql );

        if( $stmt ){

            $stmt->bind_param('siii', $fname, $price, $control, $uid );

            foreach( $checkboxes as $index => $control ){
                if( !empty( $control ) ){
                    $uid=$userids[ $index ];
                    $fname=$fnames[ $index ];
                    $price=$prices[ $index ];

                    $stmt->execute();
                }
            }
            $stmt->close();
            $db->close();
        }
    }

?>
</code>```

Body:
in table:

<form action="" method="post">

      ID
      Customer Name
      Price
      Control

      <input type="text" value="111" name="userID" />
      <input type="text" value="john" name="fname" />
      <input type="text" value="1000" name="price" />
      <input type="checkbox" value="120" name="checkbox[]" />

      <input type="text" value="115" name="userID" />
      <input type="text" value="mike" name="fname" />
      <input type="text" value="800" name="price" />
      <input type="checkbox" value="120" name="checkbox[]" />

      <input type="text" value="98" name="userID" />
      <input type="text" value="tetra" name="fname" />
      <input type="text" value="125" name="price" />
      <input type="checkbox" value="120" name="checkbox[]" />

  <button type="submit">Update Database</button>
</form>

when checked one or more checkbox then press button how update mySql table rows contain name and price together?

answers that i see in this site or other sites can solve this problem but with only one record in each row.
in this case each row contain more than one data such as username and price and ett that must update in mysql table.

thanks in advance

Body:
If I understood correctly then perhaps the following might be of interest / help.

Firstly modify the form elements to use the same syntax as you assigned to the checkbox field - an unusual name however.

<form action="" method="post">
  <table>
    <tr>
      <td>ID</td>
      <td>Customer Name</td>
      <td>Price</td>
      <td>Control</td>
    </tr>
    <tr>
      <td><input type="text" value="111" name="userID[]" /></td>
      <td><input type="text" value="john" name="fname[]" /></td>
      <td><input type="text" value="1000" name="price[]" /></td>
      <td><input type="checkbox" value="120" name="checkbox[]" /></td>
    </tr>
    <tr>
      <td><input type="text" value="115" name="userID[]" /></td>
      <td><input type="text" value="mike" name="fname[]" /></td>
      <td><input type="text" value="800" name="price[]" /></td>
      <td><input type="checkbox" value="120" name="checkbox[]" /></td>
    </tr>
    <tr>
      <td><input type="text" value="98" name="userID[]" /></td>
      <td><input type="text" value="tetra" name="fname[]" /></td>
      <td><input type="text" value="125" name="price[]" /></td>
      <td><input type="checkbox" value="120" name="checkbox[]" /></td>
    </tr>
  </table>

  <button type="submit">Update Database</button>
</form>

Then the PHP to process the request might look like this in basic form:

<?php

    if( $_SERVER['REQUEST_METHOD']=='POST' ){

        $userids=!empty( $_POST['userID'] ) ? $_POST['userID'] : false;
        $fnames=!empty( $_POST['fname'] ) ? $_POST['fname'] : false;
        $prices=!empty( $_POST['price'] ) ? $_POST['price'] : false;
        $checkboxes=!empty( $_POST['checkbox'] ) ? $_POST['checkbox'] : false;

        $sql='update `TABLE` set `fname`=?, `price`=?, `control`=? where `userID`=?';
        $stmt=$db->prepare( $sql );

        if( $stmt ){

            $stmt->bind_param('siii', $fname, $price, $control, $uid );

            foreach( $checkboxes as $index => $control ){
                if( !empty( $control ) ){
                    $uid=$userids[ $index ];
                    $fname=$fnames[ $index ];
                    $price=$prices[ $index ];

                    $stmt->execute();
                }
            }
            $stmt->close();
            $db->close();
        }
    }

?>


来源: stackexchange

问:
how to modify the BFS algorithm to find a path between 2 vertices with a given condition?
I just started to learn graphs and get stuck on this problem.
I'm trying to find the shortest path(minimum number of edges) between two vertices of a graph with the condition that between every 2 intermediary vertices of the path there are 2 alternative paths (doesn't mather the lenght).

This is my BFS algorithm.
Colors mean:

white = didn't reached yet

gray = a reached vertex will stay that color until all his neighbors won't be reached

black = reached vertices

pi[] contains the parent of the curent vertex

```<code>void bfs(int s)
{
    int i;

    for (i=1; i<=v; i++)
    {
        if (i != s)
        {
            color[i] = WHITE;
            d[i] = INFTY;
            pi[i] = NIL;
        }
    }
    color[s] = GRAY;
    d[s] = 0;
    pi[s] = NIL;
    queueInit(&q);
    queuePush(&q,s);
    while (!queueEmpty(&q))
    {
        int u = queueFront(&q);
        int j;
        for (j=1; j<=adj[u][0]; j++)
        {
            int x = adj[u][j];
            if (color[x] == WHITE)
            {
                color[x] = GRAY;
                d[x] = d[u]+1;
                pi[x] = u;
                queuePush(&q,x);
            }
        }
        queuePop(&q);
        color[u] = BLACK;
    }
}
</code>```

Please help me to change the algorithm to find the shortest path with the given condition or at least give me an advice !

答:
If you start debugging your code, you'll see one of the problems is that nodes aren't popped before looping on their adjacent nodes, so after all, the algorithm is run again on them, and some of nodes are popped before the algorithm is run on them.

I also don't understand line for (j=1; j<=adj[u][0]; j++), which is looping on adjacent vertices.

An implementation of BFS algorithms from cp-algorithms:

vector<vector<int>> adj;  // adjacency list representation
int n; // number of nodes
int s; // source vertex

queue<int> q;
vector<bool> used(n);
vector<int> d(n), p(n);

q.push(s);
used[s] = true;
p[s] = -1;
while (!q.empty()) {
    int v = q.front();
    q.pop(); // The node should be poped before looping on it's adjacent nodes
    for (int u : adj[v]) {
        if (!used[u]) {
            used[u] = true;
            q.push(u);
            d[u] = d[v] + 1;
            p[u] = v;
        }
    }
}
```

<p>And then, let's say we want to print the shortest path:</p>

<pre class="lang-cpp prettyprint-override"><code>if (!used[u]) {
    cout << "No path!";
} else {
    vector<int> path;
    for (int v = u; v != -1; v = p[v])
        path.push_back(v);
    reverse(path.begin(), path.end());
    cout << "Path: ";
    for (int v : path)
        cout << v << " ";
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I just started to learn graphs and get stuck on this problem.
I'm trying to find the shortest path(minimum number of edges) between two vertices of a graph with the condition that between every 2 intermediary vertices of the path there are 2 alternative paths (doesn't mather the lenght).

This is my BFS algorithm.
Colors mean:

white = didn't reached yet

gray = a reached vertex will stay that color until all his neighbors won't be reached

black = reached vertices

pi[] contains the parent of the curent vertex

void bfs(int s)
{
    int i;

    for (i=1; i<=v; i++)
    {
        if (i != s)
        {
            color[i] = WHITE;
            d[i] = INFTY;
            pi[i] = NIL;
        }
    }
    color[s] = GRAY;
    d[s] = 0;
    pi[s] = NIL;
    queueInit(&q);
    queuePush(&q,s);
    while (!queueEmpty(&q))
    {
        int u = queueFront(&q);
        int j;
        for (j=1; j<=adj[u][0]; j++)
        {
            int x = adj[u][j];
            if (color[x] == WHITE)
            {
                color[x] = GRAY;
                d[x] = d[u]+1;
                pi[x] = u;
                queuePush(&q,x);
            }
        }
        queuePop(&q);
        color[u] = BLACK;
    }
}

Please help me to change the algorithm to find the shortest path with the given condition or at least give me an advice !

Body:
If you start debugging your code, you'll see one of the problems is that nodes aren't popped before looping on their adjacent nodes, so after all, the algorithm is run again on them, and some of nodes are popped before the algorithm is run on them.

I also don't understand line for (j=1; j<=adj[u][0]; j++), which is looping on adjacent vertices.

An implementation of BFS algorithms from cp-algorithms:

vector<vector<int>> adj;  // adjacency list representation
int n; // number of nodes
int s; // source vertex

queue<int> q;
vector<bool> used(n);
vector<int> d(n), p(n);

q.push(s);
used[s] = true;
p[s] = -1;
while (!q.empty()) {
    int v = q.front();
    q.pop(); // The node should be poped before looping on it's adjacent nodes
    for (int u : adj[v]) {
        if (!used[u]) {
            used[u] = true;
            q.push(u);
            d[u] = d[v] + 1;
            p[u] = v;
        }
    }
}

And then, let's say we want to print the shortest path:

if (!used[u]) {
    cout << "No path!";
} else {
    vector<int> path;
    for (int v = u; v != -1; v = p[v])
        path.push_back(v);
    reverse(path.begin(), path.end());
    cout << "Path: ";
    for (int v : path)
        cout << v << " ";
}


问:
ArgumentException: Requested value 'X86' was not found
i try to import GoogleMobileAds sdk to unity. when i import PlayServicesResolver package, i am getting error on console like this 'ArgumentException: Requested value 'X86' was not found.' I cant figure out why?

ArgumentException: Requested value 'X86' was not found.
  System.Enum+EnumResult.SetFailure (System.Enum+ParseFailureKind failure, System.String failureMessageID, System.Object failureMessageFormatArgument) (at <23c160f925be47d7a4fd083a3a62c920>:0)
  System.Enum.TryParseEnum (System.Type enumType, System.String value, System.Boolean ignoreCase, System.Enum+EnumResult& parseResult) (at <23c160f925be47d7a4fd083a3a62c920>:0)
  System.Enum.Parse (System.Type enumType, System.String value, System.Boolean ignoreCase) (at <23c160f925be47d7a4fd083a3a62c920>:0)
  System.Enum.Parse (System.Type enumType, System.String value) (at <23c160f925be47d7a4fd083a3a62c920>:0)
  GooglePlayServices.AndroidAbis.EnumValueStringToULong (System.Type enumType, System.String enumValueString) (at /Users/smiles/dev/src/unity-jar-resolver/source/PlayServicesResolver/src/AndroidAbis.cs:220)
  GooglePlayServices.AndroidAbis.get_Current () (at /Users/smiles/dev/src/unity-jar-resolver/source/PlayServicesResolver/src/AndroidAbis.cs:278)
  GooglePlayServices.PlayServicesResolver.m__1B () (at /Users/smiles/dev/src/unity-jar-resolver/source/PlayServicesResolver/src/PlayServicesResolver.cs:1201)
  GooglePlayServices.PlayServicesResolver+PropertyPoller1[T].Poll (System.Func1[TResult] getCurrentValue, GooglePlayServices.PlayServicesResolver+PropertyPoller`1+Changed[T] changed) (at /Users/smiles/dev/src/unity-jar-resolver/source/PlayServicesResolver/src/PlayServicesResolver.cs:278)
  GooglePlayServices.PlayServicesResolver.PollAndroidAbis () (at /Users/smiles/dev/src/unity-jar-resolver/source/PlayServicesResolver/src/PlayServicesResolver.cs:1201)
  UnityEditor.EditorApplication.Internal_CallUpdateFunctions () (at C:/buildslave/unity/build/Editor/Mono/EditorApplication.cs:303)

答: I think i found that why i am getting this exception. In Unity3d 2019.3.0a3 version, there is no x86 option at Project Settings-> Player-> Target Architectures. But in older version of Unity3d, there is. Maybe the imported PlayServicesResolver sdk search for this option too, so throws ArgumentException.</p>


问:
Why does Android "kills" backgrounds apps? What can you do about it?
I'm only on search for the reason why Android does this and what can you do to "stop" it or handle it when coding any app. I haven't found any info about this except some yt videos that teach you how to stop it when using your Android smartphone. I'm looking for documentation or something like that to read and learn why does this happen and how to handle it.

Sorry for my bad english, not native. Thank you.

答:
Why? Because a device is a computer and therefore the limited resources should be optimized. The optimizations favors the app with the user is interacting, making the user experience fluid.

How this happen and how to handle it is the life cycle

And how to make things even if the app is not open it is about the workmanager


答:
From the official documentation

It is important that application developers understand how different application components (in particular Activity, Service, and BroadcastReceiver) impact the lifetime of the application's process. Not using these components correctly can result in the system killing the application's process while it is doing important work.

and how it happens :

To determine which processes should be killed when low on memory, Android places each process into an "importance hierarchy" based on the components running in them and the state of those components

Title: Why does Android "kills" backgrounds apps? What can you do about it?

Body:
I'm only on search for the reason why Android does this and what can you do to "stop" it or handle it when coding any app. I haven't found any info about this except some yt videos that teach you how to stop it when using your Android smartphone. I'm looking for documentation or something like that to read and learn why does this happen and how to handle it.

Sorry for my bad english, not native. Thank you.


问:
Detect Enter key is pressed with jQuery
I have a text field which is showing a value. What I want is when the user writes a new value in that text field and presses enter, an ajax function is triggered to do a pagination operation. I have a text field like this:

```<code><input type="text" id="page" name="page" value="<?php echo($this->pn);?> />
</code>```

And when a user writes any new value and presses enter, I want the following ajax function triggered:

```
update_ajax2({rpp:<?php echo($this->rpp);?>,pn:document.page.paged.value,filter:'<?php echo($this->filter);?>',orderby:'<?php echo($this->orderby);?>'});
```

I tried using the keypress event to detect if(e.which===13) but this doesn't solve the problem. Can anyone guide me?

答:
```<code><input type="text" id="txt">

$('#txt').keydown(function (e) {
    if (e.keyCode == 13) {
        alert('you pressed enter ^_^');
    }
})
</code>```

On jsfiddle.

Update (June 2022)

Note that keyCode has been deprecated. Use KeyboardEvent.code or KeyboardEvent.key properties instead:

```<code>if (e.key === "Enter") {
   // Pressed enter
}
</code>```

Title: Detect Enter key is pressed with jQuery

Body:
I have a text field which is showing a value. What I want is when the user writes a new value in that text field and presses enter, an ajax function is triggered to do a pagination operation. I have a text field like this:

<input type="text" id="page" name="page" value="<?php echo($this->pn);?> />

And when a user writes any new value and presses enter, I want the following ajax function triggered:

update_ajax2({rpp:<?php echo($this->rpp);?>,pn:document.page.paged.value,filter:'<?php echo($this->filter);?>',orderby:'<?php echo($this->orderby);?>'});

I tried using the keypress event to detect if(e.which===13) but this doesn't solve the problem. Can anyone guide me?

Body:
<input type="text" id="txt">

$('#txt').keydown(function (e) {
    if (e.keyCode == 13) {
        alert('you pressed enter ^_^');
    }
})

On jsfiddle.

Update (June 2022)

Note that keyCode has been deprecated. Use KeyboardEvent.code or KeyboardEvent.key properties instead:

if (e.key === "Enter") {
   // Pressed enter
}


问:
Decrement a hex value stored in a string
Let's assume I have:

```<code>char str[]="0x7fffffffe181"
</code>```

basically I want to decrement the hex to 0x7fffffffe180.

How do I do this?

Note: if the final character is letter e.g c after decrement it should be b

答:
You can convert it to an integer and back like this:</p>

```<code>char *str2;
unsigned long long int len, a = strtoull(str, NULL, 16);
a--;
len = snprintf(NULL, 0, "0x%llx", a);
str2 = malloc(len+1);
sprintf(str2, "0x%llx", a);
</code>```

Body:
Let's assume I have:

char str[]="0x7fffffffe181"

basically I want to decrement the hex to 0x7fffffffe180.

How do I do this?

Note: if the final character is letter e.g c after decrement it should be b

Body:
You can convert it to an integer and back like this:

char *str2;
unsigned long long int len, a = strtoull(str, NULL, 16);
a--;
len = snprintf(NULL, 0, "0x%llx", a);
str2 = malloc(len+1);
sprintf(str2, "0x%llx", a);


问:
Automation of different parts of a framework
I have a software framework consisting of multiple components which need to run sequentially. For example, I have a Python script which parses data, another Python script which POSTs the data through a REST API and persists it into a DB, and a Java program which retrieves the parsed data from the DB and performs some analysis on it. So one output is linked to the input of the other component.

I want to know how I can automate these tasks to run one after the other sequentially on a Windows platform. Is PowerShell a good tool to achieve this sort of sequential execution of programs with inter-related input/output flow?

If PowerShell is a suitable choice, it would be great if someone could give me an example of how to achieve this sort of sequential application execution. I have never used PowerShell before and the tutorials I looked up on PowerShell didn't specifically mention this sort of task.

答:
It may be that I do not yet fully understand the complexity of the situation. I would start by writing a script that runs three (3) programs using the invocation operator &.

=== Run-Them.ps1

```<code>& prog1.exe
& prog2.exe
& prog3.exe
</code>```

Body:
It may be that I do not yet fully understand the complexity of the situation. I would start by writing a script that runs three (3) programs using the invocation operator &.

=== Run-Them.ps1

& prog1.exe
& prog2.exe
& prog3.exe


问:
Encoding problem with file generated by Java program for a VB application
I have a tiny Java Encryption program that reads in a csv and generates an encrypted csv file to be uploaded to a VB application but the VB application after decrypting is not able to display the characters properly.

I opened the file in Notepad++ and converted it to UTF-8 in notepad++ and the VB application was able to decrypt and display all the right characters.
I then went ahead and modified my code to read in the lines from the csv using UTF-8 but I didn't work. I tried reading the file converting it to bytes and creating a new string using UTF-8 encoding and that didn't work either. Why does it work when I use notepad++ to convert to UTF-8 but not when I attempt to that in my code.

VB function

```<code>//each line from the encrypted file is processed by this VB RC4 function
Private Function RC4(ByVal Str As String, ByVal Pwd As String) As String

    Dim strReturnValue As String = ""
    Dim Sbox(0 To 255) As Integer
    Dim A, B, c
    Dim Key() As Byte, ByteArray() As Byte, Tmp As Byte

    If Len(Pwd) = 0 Or Len(Str) = 0 Then GoTo Exit_Function
    If Len(Pwd) > 256 Then
      Key = System.Text.Encoding.Default.GetBytes(Microsoft.VisualBasic.Left(Pwd, 256)) ''StrConv(Left$(Pwd, 256), vbFromUnicode)
    Else
      Key = System.Text.Encoding.Default.GetBytes(Pwd)  ''StrConv(Pwd, vbFromUnicode)
    End If

    For A = 0 To 255
      Sbox(A) = A
    Next A
    A = 0 : B = 0 : c = 0
    For A = 0 To 255
      B = (B + Sbox(A) + Key(A Mod Len(Pwd))) Mod 256
      Tmp = Sbox(A)
      Sbox(A) = Sbox(B)
      Sbox(B) = Tmp
    Next A
    A = 0 : B = 0 : c = 0
    ByteArray = System.Text.Encoding.Default.GetBytes(Str) '' StrConv(Str, vbFromUnicode)
    For A = 0 To Len(Str) - 1
      B = (B + 1) Mod 256
      c = (c + Sbox(B)) Mod 256
      Tmp = Sbox(B)
      Sbox(B) = Sbox(c)
      Sbox(c) = Tmp
      ByteArray(A) = ByteArray(A) Xor (Sbox((Sbox(B) + Sbox(c)) Mod 256))
    Next A
    strReturnValue = System.Text.Encoding.Default.GetString(ByteArray)  ''StrConv(ByteArray, vbUnicode)
Exit_Function:
    Return strReturnValue
  End Function
</code>```

Java

//processing line from the input file and writing to file
try
 {
FileOutputStream fos = newFileOutputStream("stackOverFlow\\EncryptedFile.csv",true);
byte [] encrypt = EncryptFile.RC4(line.getBytes(), pwd);
fos.write(encrypt);
fos.close();
}
catch (Exception e1)
{
e1.printStackTrace();
}
```

答:
After decompiling the VB application and reading the post below I found a solution:

Read a file line by line with VB.NET

I changed the way the Reader declaration from

Dim reader As StreamReader

to

Dim reader As New StreamReader(filetoimport.Text, Encoding.Default)

Body:
I have a tiny Java Encryption program that reads in a csv and generates an encrypted csv file to be uploaded to a VB application but the VB application after decrypting is not able to display the characters properly.

I opened the file in Notepad++ and converted it to UTF-8 in notepad++ and the VB application was able to decrypt and display all the right characters.
I then went ahead and modified my code to read in the lines from the csv using UTF-8 but I didn't work. I tried reading the file converting it to bytes and creating a new string using UTF-8 encoding and that didn't work either. Why does it work when I use notepad++ to convert to UTF-8 but not when I attempt to that in my code.

VB function

//each line from the encrypted file is processed by this VB RC4 function
Private Function RC4(ByVal Str As String, ByVal Pwd As String) As String

    Dim strReturnValue As String = ""
    Dim Sbox(0 To 255) As Integer
    Dim A, B, c
    Dim Key() As Byte, ByteArray() As Byte, Tmp As Byte

    If Len(Pwd) = 0 Or Len(Str) = 0 Then GoTo Exit_Function
    If Len(Pwd) > 256 Then
      Key = System.Text.Encoding.Default.GetBytes(Microsoft.VisualBasic.Left(Pwd, 256)) ''StrConv(Left$(Pwd, 256), vbFromUnicode)
    Else
      Key = System.Text.Encoding.Default.GetBytes(Pwd)  ''StrConv(Pwd, vbFromUnicode)
    End If

    For A = 0 To 255
      Sbox(A) = A
    Next A
    A = 0 : B = 0 : c = 0
    For A = 0 To 255
      B = (B + Sbox(A) + Key(A Mod Len(Pwd))) Mod 256
      Tmp = Sbox(A)
      Sbox(A) = Sbox(B)
      Sbox(B) = Tmp
    Next A
    A = 0 : B = 0 : c = 0
    ByteArray = System.Text.Encoding.Default.GetBytes(Str) '' StrConv(Str, vbFromUnicode)
    For A = 0 To Len(Str) - 1
      B = (B + 1) Mod 256
      c = (c + Sbox(B)) Mod 256
      Tmp = Sbox(B)
      Sbox(B) = Sbox(c)
      Sbox(c) = Tmp
      ByteArray(A) = ByteArray(A) Xor (Sbox((Sbox(B) + Sbox(c)) Mod 256))
    Next A
    strReturnValue = System.Text.Encoding.Default.GetString(ByteArray)  ''StrConv(ByteArray, vbUnicode)
Exit_Function:
    Return strReturnValue
  End Function

Java

//processing line from the input file and writing to file
try
 {
FileOutputStream fos = newFileOutputStream("stackOverFlow\\EncryptedFile.csv",true);
byte [] encrypt = EncryptFile.RC4(line.getBytes(), pwd);
fos.write(encrypt);
fos.close();
}
catch (Exception e1)
{
e1.printStackTrace();
}


问:
Check if an attribute has changed in Laravel 5.5 model events
I've seen that there is a function called wasChanged() where you can check if an attribute was changed on an update. Not is dirty, but was changed and persisted

However I'm trying to check this inside my model events boot function:

```<code>public static function boot()
{
    parent::boot();

    self::updated(function($appointment){

        if($appointment->wasChanged('appointment_date')) {
         // do something
        }

    });
}
</code>```

This never works for me. Any ideas how I can check this?

the isDirty function has different behavior as that is used to check if an attribute was submitted in the request.

答:
U can check if save() method return true:</p>

```<code>$object = new Model;
$object->attribute = $value;
if($object->save(){
 // attribute changed
}
</code>```

Body:
I've seen that there is a function called wasChanged() where you can check if an attribute was changed on an update. Not is dirty, but was changed and persisted

However I'm trying to check this inside my model events boot function:

public static function boot()
{
    parent::boot();

    self::updated(function($appointment){

        if($appointment->wasChanged('appointment_date')) {
         // do something
        }

    });
}

This never works for me. Any ideas how I can check this?

the isDirty function has different behavior as that is used to check if an attribute was submitted in the request.

Body:
U can check if save() method return true:

$object = new Model;
$object->attribute = $value;
if($object->save(){
 // attribute changed
}


问:
Clipping UIImageView if is moved out of CGRect
I want to clip an UIImageView if it moves out of given rect.

The image is moving across the screen by setting the frame, but I need to clip it when it moves out of a given fixed rect (say (0,0,650,650)).

答:
```<code>myImageView.contentMode = UIViewContentModeCenter;
</code>```

Try this.

Body:
myImageView.contentMode = UIViewContentModeCenter;

Try this.

ContentLicense: CC BY-SA 3.0


问:
By click on icon hide first parent
On click delete icon how can i remove first parent? I mean div with class box. I try everything and I haven't come to the solution yet

var deleteIcon = document.querySelectorAll('.delete-icon');
var box = document.querySelectorAll('.box');

deleteIcon.forEach(function(icon) {
        icon.addEventListener("click", function() {
            box.style.display = "none";
            // icon.style.display = "none";
        });
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box {
  width: 150px;
  height: 200px;
  background-color: #ccc;
  display: inline-block;
  margin: 10px;
  position: relative;
}

.delete-icon {
  position: absolute;
  bottom: 10px;
  right: 10px;
  cursor: pointer;
}</code>```

<link href"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.2/css/all.min.css" rel="stylesheet">

1

2

3

4

     bla bla

nothing1

nothing2

nothing3

1

2

3

4

     bla bla

nothing1

nothing2

nothing3

1

2

3

4

     bla bla

nothing1

nothing2

nothing3

1

2

3

4

     bla bla

nothing1

nothing2

nothing3

1

2

3

4

     bla bla

nothing1

nothing2

nothing3

1

2

3

4

     bla bla

nothing1

nothing2

nothing3

```

答:
The reason that box.style.display = "none"; doesn't work is because you defined box as being the return value from a .querySelectorAll() call. .querySelectorAll() returns a node list, which doesn't have a .style property. You must style an individual element, not a collection of elements.

Instead, just find the correct element with the .closest() method and then apply a pre-made CSS class to it.

var deleteIcon = document.querySelectorAll('.delete-icon');
var box = document.querySelectorAll('.box');

deleteIcon.forEach(function(icon) {
        icon.addEventListener("click", function() {
            // Find the nearest ancestor that matches the selector
            // and add the hidden class to it.
            this.closest("div.box").classList.add("hidden");
        });
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box {
  width: 150px;
  height: 200px;
  background-color: #ccc;
  display: inline-block;
  margin: 10px;
  position: relative;
}

.delete-icon {
  position: absolute;
  bottom: 10px;
  right: 10px;
  cursor: pointer;
}

.hidden { display:none; }</code>```

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.2/css/all.min.css" rel="stylesheet">

Box 1

2

3

4

     bla bla

nothing1

nothing2

nothing3

Box 2

2

3

4

     bla bla

nothing1

nothing2

nothing3

Box 3

2

3

4

     bla bla

nothing1

nothing2

nothing3

Box 4

2

3

4

     bla bla

nothing1

nothing2

nothing3

Box 5

2

3

4

     bla bla

nothing1

nothing2

nothing3

Box 6

2

3

4

     bla bla

nothing1

nothing2

nothing3

```

Title: By click on icon hide first parent

Body:
On click delete icon how can i remove first parent? I mean div with class box. I try everything and I haven't come to the solution yet

var deleteIcon = document.querySelectorAll('.delete-icon');
var box = document.querySelectorAll('.box');

deleteIcon.forEach(function(icon) {
        icon.addEventListener("click", function() {
            box.style.display = "none";
            // icon.style.display = "none";
        });
    });

.box {
  width: 150px;
  height: 200px;
  background-color: #ccc;
  display: inline-block;
  margin: 10px;
  position: relative;
}

.delete-icon {
  position: absolute;
  bottom: 10px;
  right: 10px;
  cursor: pointer;
}

<link href"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.2/css/all.min.css" rel="stylesheet">

1

2

3

4

     bla bla

nothing1

nothing2

nothing3

1

2

3

4

     bla bla

nothing1

nothing2

nothing3

1

2

3

4

     bla bla

nothing1

nothing2

nothing3

1

2

3

4

     bla bla

nothing1

nothing2

nothing3

1

2

3

4

     bla bla

nothing1

nothing2

nothing3

1

2

3

4

     bla bla

nothing1

nothing2

nothing3

Body:
The reason that box.style.display = "none"; doesn't work is because you defined box as being the return value from a .querySelectorAll() call. .querySelectorAll() returns a node list, which doesn't have a .style property. You must style an individual element, not a collection of elements.

Instead, just find the correct element with the .closest() method and then apply a pre-made CSS class to it.

var deleteIcon = document.querySelectorAll('.delete-icon');
var box = document.querySelectorAll('.box');

deleteIcon.forEach(function(icon) {
        icon.addEventListener("click", function() {
            // Find the nearest ancestor that matches the selector
            // and add the hidden class to it.
            this.closest("div.box").classList.add("hidden");
        });
    });

.box {
  width: 150px;
  height: 200px;
  background-color: #ccc;
  display: inline-block;
  margin: 10px;
  position: relative;
}

.delete-icon {
  position: absolute;
  bottom: 10px;
  right: 10px;
  cursor: pointer;
}

.hidden { display:none; }

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.2/css/all.min.css" rel="stylesheet">
<div class="box">
   <ul class="nothing">
     <li class="blabla">Box 1</li>
     <li class="blabla">2</li>
     <li class="blabla">3</li>
     <li class="blabla">4</li>
     <span>bla bla</span>
  </ul>
  <div>nothing1</div>
  <div>nothing2</div>
  <div>nothing3</div>

  <div class="icon-test">
    <i class="fas fa-times-circle delete-icon"></i>
  </div>
</div>

<div class="box">
   <ul class="nothing">
     <li class="blabla">Box 2</li>
     <li class="blabla">2</li>
     <li class="blabla">3</li>
     <li class="blabla">4</li>
     <span>bla bla</span>
  </ul>
  <div>nothing1</div>
  <div>nothing2</div>
  <div>nothing3</div>

  <div class="icon-test">
    <i class="fas fa-times-circle delete-icon"></i>
  </div>
</div>

<div class="box">
   <ul class="nothing">
     <li class="blabla">Box 3</li>
     <li class="blabla">2</li>
     <li class="blabla">3</li>
     <li class="blabla">4</li>
     <span>bla bla</span>
  </ul>
  <div>nothing1</div>
  <div>nothing2</div>
  <div>nothing3</div>

  <div class="icon-test">
    <i class="fas fa-times-circle delete-icon"></i>
  </div>
</div>

<div class="box">
   <ul class="nothing">
     <li class="blabla">Box 4</li>
     <li class="blabla">2</li>
     <li class="blabla">3</li>
     <li class="blabla">4</li>
     <span>bla bla</span>
  </ul>
  <div>nothing1</div>
  <div>nothing2</div>
  <div>nothing3</div>

  <div class="icon-test">
    <i class="fas fa-times-circle delete-icon"></i>
  </div>
</div>

<div class="box">
   <ul class="nothing">
     <li class="blabla">Box 5</li>
     <li class="blabla">2</li>
     <li class="blabla">3</li>
     <li class="blabla">4</li>
     <span>bla bla</span>
  </ul>
  <div>nothing1</div>
  <div>nothing2</div>
  <div>nothing3</div>

  <div class="icon-test">
    <i class="fas fa-times-circle delete-icon"></i>
  </div>
</div>

<div class="box">
   <ul class="nothing">
     <li class="blabla">Box 6</li>
     <li class="blabla">2</li>
     <li class="blabla">3</li>
     <li class="blabla">4</li>
     <span>bla bla</span>
  </ul>
  <div>nothing1</div>
  <div>nothing2</div>
  <div>nothing3</div>

  <div class="icon-test">
    <i class="fas fa-times-circle delete-icon"></i>
  </div>
</div>


问:
Get 2 parameters from a returning fuction (tuple) in python
I'm having difficulty getting two parameters returned from a function as a tuple:

```<code>>>> ir7(41,7)

(966, 1023, 571, 396, 105, 2, 3)
</code>```

If I want to get specified tuple I use this:

```<code> >>> ir7(41,7)[0]

966
</code>```

but what if I want to get 1st, 3rd and 4th element from the tuple. What is the correct syntax? Something like:

```<code>a,b,c= ir7(41,7)[1][3][4]
</code>```

答:
Call the method only once to make it more efficient. After that, it's just a matter of tuple-assignment. </p>

```<code>v = ir7(41,7)
a, b, c= v[1], v[3], v[4]
</code>```

Body:
I'm having difficulty getting two parameters returned from a function as a tuple:

>>> ir7(41,7)

(966, 1023, 571, 396, 105, 2, 3)

If I want to get specified tuple I use this:

 >>> ir7(41,7)[0]

966

but what if I want to get 1st, 3rd and 4th element from the tuple. What is the correct syntax? Something like:

a,b,c= ir7(41,7)[1][3][4]

Body:
Call the method only once to make it more efficient. After that, it's just a matter of tuple-assignment.

v = ir7(41,7)
a, b, c= v[1], v[3], v[4]


问:
Using cnn models trained on different datasets
I am having 3 different datasets, 3 of them were all blood smear image stained with the same chemical substance. Blood smear images are images that capture your blood, include Red, White blood cells inside.

The first dataset contain 2 classes : normal vs blood cancer
The second dataset contain 2 classes: normal vs blood infection
The third dataset contain 2 classes: normal vs sickle cell disease

So, what i want to do is : when i input a blood smear image, the AI system will tell me whether it was : normal , or blood cancer or blood infection or sickle cell disease (4 classes classification task)

What should i do?

Should i mix these 3 datasets and train only 1 model to detect 4 classes ?

Or should i train 3 different models and them combine them? If yes, what method should i use to combine?

Update : i searched for a while. Can this task called "Learning without forgetting?"

答: This is a multiclass classification problem. You can train just one model, with the final layer being a full connected (dense) layer of 4 units (i.e. output dimension) and softmax activation function.</p>


答:
It only has to work in the range of an unsigned long long.

```<code>const char *eptr;
unsigned long long numeric = strtoull(str, &eptr, 16);
if (eptr == str || numeric == 0) {
    /* handle error */
}
sprintf(str, "0x%llx", numeric - 1);
</code>```

We can't do this for signed hex in place because decrementing 0 or certain negative numbers would make the string longer.

In theory, 0 should work for the third argument to strtoull, but it's buggy in our libc right now so it doesn't.

Title: Decrement a hex value stored in a string

Body:
It only has to work in the range of an unsigned long long.

const char *eptr;
unsigned long long numeric = strtoull(str, &eptr, 16);
if (eptr == str || numeric == 0) {
    /* handle error */
}
sprintf(str, "0x%llx", numeric - 1);

We can't do this for signed hex in place because decrementing 0 or certain negative numbers would make the string longer.

In theory, 0 should work for the third argument to strtoull, but it's buggy in our libc right now so it doesn't.


问:
To_char ,To_date
how do you become conform with this code, only dates of 2019 appear to me? You are not changing To_char. </p>

```<code>SELECT GUEST.GNO, GUEST.GLASTNAME, GUEST.GFIRSTNAME, BOOKING.gNO, BOOKING.GINDATE
FROM GUEST, BOOKING
WHERE GUEST.GNO = BOOKING.gNO AND BOOKING.GINDATE = TO_CHAR (GINDATE,'DD/MM/YYYY');
</code>```

答:
I am interpreting your query as you want bookings in 2019.  If so, then query should look more like this:

```<code>SELECT g.GNO, g.GLASTNAME, g.GFIRSTNAME, b.gNO, b.GINDATE
FROM GUEST g JOIN
     BOOKING b
     ON g.GNO = b.gNO
WHERE b.GINDATE >= DATE '2019-01-01' AND
      b.GINDATE < DATE '2020-01-01';
</code>```

Of course, there might be slight variations depending on your database.

Title: To_char ,To_date

Body:
how do you become conform with this code, only dates of 2019 appear to me? You are not changing To_char.

SELECT GUEST.GNO, GUEST.GLASTNAME, GUEST.GFIRSTNAME, BOOKING.gNO, BOOKING.GINDATE
FROM GUEST, BOOKING
WHERE GUEST.GNO = BOOKING.gNO AND BOOKING.GINDATE = TO_CHAR (GINDATE,'DD/MM/YYYY');

Body:
I am interpreting your query as you want bookings in 2019.  If so, then query should look more like this:

SELECT g.GNO, g.GLASTNAME, g.GFIRSTNAME, b.gNO, b.GINDATE
FROM GUEST g JOIN
     BOOKING b
     ON g.GNO = b.gNO
WHERE b.GINDATE >= DATE '2019-01-01' AND
      b.GINDATE < DATE '2020-01-01';

Of course, there might be slight variations depending on your database.


问:
How to use specific GPU's in keras for multi-GPU training?
I have a server with 4 GPU's. I want to use exactly 2 of them for multi-GPU training.

Keras documentation provided  here  gives some insight about how to use multiple GPU's but I want to select the specific GPU's. Is there a way to achieve this?

答:
```<code>from keras import backend as K
import tensorflow as tf
c = []
for d in ['/device:GPU:2', '/device:GPU:3']:
    with K.tf.device(d):
        config = tf.ConfigProto(intra_op_parallelism_threads=4,\
        inter_op_parallelism_threads=4, allow_soft_placement=True,\
        device_count = {'CPU' : 1, 'GPU' : 2})
        a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3])
        b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2])
        c.append(tf.matmul(a, b))
with tf.device('/cpu:0'):
    sum = tf.add_n(c)
session = tf.Session(config=config)
K.set_session(session)
</code>```

I think this should work . You should be having the number(index) of GPU devices you want to use. In this case its 2 and 3.  Relevant links 1)https://github.com/carla-simulator/carla/issues/116

2) https://www.tensorflow.org/guide/using_gpu#using_multiple_gpus

Body:
from keras import backend as K
import tensorflow as tf
c = []
for d in ['/device:GPU:2', '/device:GPU:3']:
    with K.tf.device(d):
        config = tf.ConfigProto(intra_op_parallelism_threads=4,\
        inter_op_parallelism_threads=4, allow_soft_placement=True,\
        device_count = {'CPU' : 1, 'GPU' : 2})
        a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3])
        b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2])
        c.append(tf.matmul(a, b))
with tf.device('/cpu:0'):
    sum = tf.add_n(c)
session = tf.Session(config=config)
K.set_session(session)

I think this should work . You should be having the number(index) of GPU devices you want to use. In this case its 2 and 3.  Relevant links 1)https://github.com/carla-simulator/carla/issues/116

2) https://www.tensorflow.org/guide/using_gpu#using_multiple_gpus


答:
I think it depends on the data.

You may use three different models and make three binary predictions on each image. So you get a vote (probability) for each x vs. normal. If binary classifications are accurate, this should deliver okay results. But you kind of get a cummulated missclassification or error in this case.

If you can afford, you can train a four class model and compare the test error to the series of binary classifications. I understand that you already have three models. So training another one may be not too expensive.

If ONLY one of the classes can occur, a four class model might be the way to go. If in fact two (or more) classes can occur jointly, a series of binary classifications would make sense.

Title: Using cnn models trained on different datasets

Body:
I am having 3 different datasets, 3 of them were all blood smear image stained with the same chemical substance. Blood smear images are images that capture your blood, include Red, White blood cells inside.

The first dataset contain 2 classes : normal vs blood cancer
The second dataset contain 2 classes: normal vs blood infection
The third dataset contain 2 classes: normal vs sickle cell disease

So, what i want to do is : when i input a blood smear image, the AI system will tell me whether it was : normal , or blood cancer or blood infection or sickle cell disease (4 classes classification task)

What should i do?

Should i mix these 3 datasets and train only 1 model to detect 4 classes ?

Or should i train 3 different models and them combine them? If yes, what method should i use to combine?

Update : i searched for a while. Can this task called "Learning without forgetting?"


答:
When you do ir7(41,7)[1][3][4] you essentially tries to get the 4:th element of the 3:rd element of the 1:st element of an object (basically a 4-dimensional list). Instead you should fetch them separately:

```<code># Get all the values initially in a separate variable
values = ir7(41,7)
a, b, c = values[1], values[3], values[4]
</code>```

Or I you can do it this way:

```<code>_, a, _ b, c = ir7(41,7)
</code>```

By omitting the indexes you don't want with placeholder variables _

Title: Get 2 parameters from a returning fuction (tuple) in python

Body:
When you do ir7(41,7)[1][3][4] you essentially tries to get the 4:th element of the 3:rd element of the 1:st element of an object (basically a 4-dimensional list). Instead you should fetch them separately:

# Get all the values initially in a separate variable
values = ir7(41,7)
a, b, c = values[1], values[3], values[4]

Or I you can do it this way:

_, a, _ b, c = ir7(41,7)

By omitting the indexes you don't want with placeholder variables _


问:
puppetserver as client of another puppetserver
I have a puppet OS v6 install that maintains 'internal' server hosts. I've recently started migrating 'external' servers to a separate puppet domain. I'd like to include the 'external' domain server as a host in the 'internal' domain so I can use the base configuration that I have for other 'internal' hosts.

Is this practical / possible?

If so, how do I specify the 'agent' ssldir to keep it separated from the 'server' ssldir? Looks like there's only one ssldir setting in the [main] section of puppet.conf.

Why have different hosts? There are network / security reasons to separate the two onto different VMs.

答:
I'd like to include the 'external' domain server as a host in the
  'internal' domain so I can use the base configuration that I have for
  other 'internal' hosts.

Is this practical / possible?

It's definitely possible.  You'll have to judge how practical it is.

If so, how do I specify the 'agent' ssldir to keep it separated from the 'server' ssldir? Looks like there's only one
  ssldir setting in the [main] section of puppet.conf.

Most Puppet settings can be specified in multiple sections, so one thing you could try would be to specify ssldir in the [agent] section.  For the agent only, that should override the the default and / or an explicit setting in the [main] section.

Alternatively, you can override the config file via command-line options. Specifically, you could use the --ssldir option (or, more broadly, the --vardir option) when you launch Puppet.

But do you really need a separate set of SSL certificates?  If you set up a central CA instead of having each server provide CA services for its clients, and maybe by other means as well, you ought to be able to have a single cert for each machine that it uses to identify itself to all other machines in your site.


问:
Are there any databases that support protocol buffers?
Are there any databases, in either the SQL or NoSQL worlds, that support protocol buffers?  (Support could mean various things, but hopefully would include being able to index on fields in protocol buffers.)</p>

答: ClickHouse lately added support for protobuf messages. </p>

ContentLicense: CC BY-SA 2.5


答:
There is a convention for using _ as the name for variables that you don't actually want to use. Using this, you can do:

```<code>_, a, _, b, c = ir7(41, 7)
</code>```

Alternatively, you can do:

```<code>value = ir7(41, 7)
a, b, c = value[1], value[3], value[4]
</code>```

If the number of items to exclude is large, you definitely want the second option.

Body:
There is a convention for using _ as the name for variables that you don't actually want to use. Using this, you can do:

_, a, _, b, c = ir7(41, 7)

Alternatively, you can do:

value = ir7(41, 7)
a, b, c = value[1], value[3], value[4]

If the number of items to exclude is large, you definitely want the second option.


问:
asyncio: running task only if all other tasks are awaiting
I am currently running some endless tasks using asyncio.wait

I need a special function to run when all the others are on await

```<code>import asyncio

async def special_function():
    while True:
        # does some work,
        # Passes control back to controller to run main_tasks
        # if they are no longer waiting.
        await asyncio.sleep(0)

async def handler():
    tasks = [task() for task in main_tasks]

    # Adding the task that I want to run when all main_tasks are awaiting:
    tasks.append(special_function())

    await asyncio.wait(tasks)

asyncio.get_event_loop().run_until_complete(handler())
</code>```

How can I get  the special_function to only be run when all main_tasks are on await?

Edit:

What I mean by "all main_tasks are on await": all main_tasks are not ready to continue, e.g. are in asyncio.sleep(100) or I/O bound and still waiting for data.

Therefore the main_tasks cannot continue and the event loop runs the special_function while the tasks are in this state, NOT every iteration of the event loop.

Edit 2:

My use case:

The main_tasks are updating a data structure with new data from web-sockets.

The special_function transfers that data to another process upon an update signal from that process. (multiprocessing with shared variables and data structures)

It needs to be the most up to date data it can be when it transfers, there cannot be pending updates from main_tasks.

This is why I only want to run special_function when there are no main_tasks with new data available to be processed. (i.e. all waiting on await)

答:
When event loop runs some task, this task is being executed until it returns control back to event loop. There's usually only one reason task want to return control to the event loop: task if facing blocking operation (and thus is "not ready to continue").

It means that "every iteration of the event loop" is usually equal to "all main_tasks are on await". Code you already have will (mostly) work as you want. Only thing you should do is to make special_function() task.

There's some chance task returned control to event loop before it faced "real" blocking call and it usually looks like await asyncio.sleep(0) (like you do in special_function). It means task want to ensure all other tasks being called before continue: you probably want to respect that.

Body:
I am currently running some endless tasks using asyncio.wait

I need a special function to run when all the others are on await

import asyncio

async def special_function():
    while True:
        # does some work,
        # Passes control back to controller to run main_tasks
        # if they are no longer waiting.
        await asyncio.sleep(0)

async def handler():
    tasks = [task() for task in main_tasks]

    # Adding the task that I want to run when all main_tasks are awaiting:
    tasks.append(special_function())

    await asyncio.wait(tasks)

asyncio.get_event_loop().run_until_complete(handler())

How can I get  the special_function to only be run when all main_tasks are on await?

Edit:

What I mean by "all main_tasks are on await": all main_tasks are not ready to continue, e.g. are in asyncio.sleep(100) or I/O bound and still waiting for data.

Therefore the main_tasks cannot continue and the event loop runs the special_function while the tasks are in this state, NOT every iteration of the event loop.

Edit 2:

My use case:

The main_tasks are updating a data structure with new data from web-sockets.

The special_function transfers that data to another process upon an update signal from that process. (multiprocessing with shared variables and data structures)

It needs to be the most up to date data it can be when it transfers, there cannot be pending updates from main_tasks.

This is why I only want to run special_function when there are no main_tasks with new data available to be processed. (i.e. all waiting on await)


答: Check out this plugin: https://github.com/jeresig/jquery.hotkeys</p>

Title: Detect Enter key is pressed with jQuery

Body:
I have a text field which is showing a value. What I want is when the user writes a new value in that text field and presses enter, an ajax function is triggered to do a pagination operation. I have a text field like this:

<input type="text" id="page" name="page" value="<?php echo($this->pn);?> />

And when a user writes any new value and presses enter, I want the following ajax function triggered:

update_ajax2({rpp:<?php echo($this->rpp);?>,pn:document.page.paged.value,filter:'<?php echo($this->filter);?>',orderby:'<?php echo($this->orderby);?>'});

I tried using the keypress event to detect if(e.which===13) but this doesn't solve the problem. Can anyone guide me?


答:
You can unpack the return values:

```<code>_, a, _, b, c, _, _ = ir(41, 7)
</code>```

The _ indicates the value being assigned here are not important.

Body:
You can unpack the return values:

_, a, _, b, c, _, _ = ir(41, 7)

The _ indicates the value being assigned here are not important.


问:
Is there any command that allows me to check if any class has objects created from it?
So, I'm writing some code for practice and I've come to a point where I want to make a function where I can check a class for objects made from it and then, be able to use the methods and/or data fields I've written on the objects

Like, let me use a kind of blunt example

Dog.CheckForObjectsOfSameClass();

I've tried using a static number to refer to to then refer to the parent of such data, but I can't find a command for that either.

I would post the code I've tried to use before, but it would just make this the more confusing.

Thanks in advance for any answer that can help me solve this doubt

答:
It sounds like you're asking for something like built-in reference counting. Other than the garbage collector there isn't anything like this in the language, and trying to hook into the garbage collector just to write normal application code would in my opinion be an utterly weird, crazy and plain dreadful thing to do.

As one of the comments suggests, this sounds like an XY problem, where the real solution is to understand why holding a reference to the object you want to access is difficult, and change your coding approach to do this in a more straightforward way. Depending on exactly what you are trying to do, adding a newly created object to a dictionary:

var dogs = new Dictionary<string, Dog>();
var rover = new Dog();
dogs.Add("rover", rover);

using a meaningful key to distinguish which object is which, might be a way of solving the problem.


问:
Why HTML selection returns random string?
I have a <select> form on my webpage containing 4 options with values from 1 to 4, when choosing an option the form should return one of the numbers but it returns 6 random characters instead.

The page does not contain any JavaScript and it is running on my local network, I've also disabled JavaScript on my browser.

The PHP i'm using to retrieve the value is the following:

```<code>if (isset($_POST[$key])) {
    return $_POST[$key];
}
</code>```

I removed any form of validation, i simply retrieve the value with $_POST and if set it prints out 6 random characters ( every time i submit the form ).

The form is the following:

```<code><form action="/select_country" method="post" >
<select name="Country" class="country-selection">
    <option required="" selected="" disabled="" style="color: #b5b5be;">Country Location</option>
    <option value="1" >Asia</option>
    <option value="2" >Australia</option>
    <option value="3" >United States</option>
    <option value="4" >Europe</option>
</select>
</form>
</code>```

Expected result: 1 or 2 or 3 or 4

Actual result: czWe8m or alBwKD and so on...

EDIT:

The $_GET was a typo, sorry for that. Corrected.

I'm retrieving other input data from the same form using the same PHP code, the other tags are simple text and number <input> and they're working just fine:

<input name="Title" type="text" placeholder="Insert Title" maxlength="100" required="">
```

<pre class="lang-html prettyprint-override"><code><input name="Description" style="width:100%" type="text" placeholder="Insert Description" maxlength="1000" required="">
</code>```

答:
You are supposed to be using $_POST["Your Input item Name Here"] because your form was using POST method and not GET.

Leaving your Html as is, please try the following:

```<code>//your name attribute = "Country" for select element
if (isset($_POST["Country"])) {
    return $_POST["Country"];
}
</code>```

Body:
I have a <select> form on my webpage containing 4 options with values from 1 to 4, when choosing an option the form should return one of the numbers but it returns 6 random characters instead.

The page does not contain any JavaScript and it is running on my local network, I've also disabled JavaScript on my browser.

The PHP i'm using to retrieve the value is the following:

if (isset($_POST[$key])) {
    return $_POST[$key];
}

I removed any form of validation, i simply retrieve the value with $_POST and if set it prints out 6 random characters ( every time i submit the form ).

The form is the following:

<form action="/select_country" method="post" >
<select name="Country" class="country-selection">
    <option required="" selected="" disabled="" style="color: #b5b5be;">Country Location</option>
    <option value="1" >Asia</option>
    <option value="2" >Australia</option>
    <option value="3" >United States</option>
    <option value="4" >Europe</option>
</select>
</form>

Expected result: 1 or 2 or 3 or 4

Actual result: czWe8m or alBwKD and so on...

EDIT:

The $_GET was a typo, sorry for that. Corrected.

I'm retrieving other input data from the same form using the same PHP code, the other tags are simple text and number <input> and they're working just fine:

<input name="Title" type="text" placeholder="Insert Title" maxlength="100" required="">

<input name="Description" style="width:100%" type="text" placeholder="Insert Description" maxlength="1000" required="">

Body:
You are supposed to be using $_POST["Your Input item Name Here"] because your form was using POST method and not GET.

Leaving your Html as is, please try the following:

//your name attribute = "Country" for select element
if (isset($_POST["Country"])) {
    return $_POST["Country"];
}


问:
How to mock inputRef of a textfield
My UI contains a textfield, a button and the text result.

When enter a string, then click REMOVE button, the text result doesn't contain 'dog'

```<code>    class MyComponent extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      text: '',
    };
  };

  handleConvertString = (event) => {
    let str = this.inputRef.value;
    this.setState({
      text: str.replace(/dog/gi, ''),
    })
  };
  render() {
    const { classes } = this.props;
    return (
      <div className={classes.root}>
        <TextField
          label="the string what you want to remove 'dog' "
          style={{ margin: 8 }}
          fullWidth
          margin="normal"
          ref="myField"
          inputRef={ref => { this.inputRef = ref; }}
          InputLabelProps={{
            shrink: true,
          }}
        />
        <div style={styleDivButton}>
          <Button className={classes.button} onClick={this.handleConvertString}>Remove</Button>
        </div>
        <p>{'"' + this.state.text + '"'}</p>
      </div>
    )
  }
}

export default MyComponent;
</code>```

How to mock this.inputRef.value

```<code>it('test handler handleRemove', () => {
  const wrapper = shallow(<Exercise1 />);
  //how to mock this.inputRef.value = "dog is a loyal pet"

  wrapper.instance().handleConvertString();
  expect(wrapper.state('text')).toBe(" is a loyal pet");
});
</code>```

答:
I mock by assign directly to wrapper. The test is passed. But I'm not sure this is a correct approach

```<code>it('test handler handleRemove', () => {
  const wrapper = shallow(<Exercise1 />);
  wrapper.instance().inputRef = {value: "dog is a loyal pet"} //mock this.inputRef.value = "dog is a loyal pet"

  wrapper.instance().handleConvertString();
  expect(wrapper.state('text')).toBe(" is a loyal pet");
});
</code>```

Title: How to mock inputRef of a textfield

Body:
My UI contains a textfield, a button and the text result.

When enter a string, then click REMOVE button, the text result doesn't contain 'dog'

    class MyComponent extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      text: '',
    };
  };

  handleConvertString = (event) => {
    let str = this.inputRef.value;
    this.setState({
      text: str.replace(/dog/gi, ''),
    })
  };
  render() {
    const { classes } = this.props;
    return (

        <TextField
          label="the string what you want to remove 'dog' "
          style={{ margin: 8 }}
          fullWidth
          margin="normal"
          ref="myField"
          inputRef={ref => { this.inputRef = ref; }}
          InputLabelProps={{
            shrink: true,
          }}
        />

          <Button className={classes.button} onClick={this.handleConvertString}>Remove</Button>

{'"' + this.state.text + '"'}

    )
  }
}

export default MyComponent;

How to mock this.inputRef.value

it('test handler handleRemove', () => {
  const wrapper = shallow(<Exercise1 />);
  //how to mock this.inputRef.value = "dog is a loyal pet"

  wrapper.instance().handleConvertString();
  expect(wrapper.state('text')).toBe(" is a loyal pet");
});

Body:
I mock by assign directly to wrapper. The test is passed. But I'm not sure this is a correct approach

it('test handler handleRemove', () => {
  const wrapper = shallow(<Exercise1 />);
  wrapper.instance().inputRef = {value: "dog is a loyal pet"} //mock this.inputRef.value = "dog is a loyal pet"

  wrapper.instance().handleConvertString();
  expect(wrapper.state('text')).toBe(" is a loyal pet");
});


问:
How to change Shipping Zones depending on the payment option in Woocommerce?
Target: I want to add different shipping cost for the different payment gateways depending on the pin code user have.

Tried Using Shipping Zones:

I have 3 different shipping zones added in my woo-commerce dashboard. All the zones are created using the pin codes of the city and flat rate. However, if the pin code exists in multiple zones, then the top level zone gets the first priority and all other zones get ignored at the checkout page.

Now I want to change that zone depending on the Payment Gateway user chooses. For example user, 'A' has the pin code '123456' and this pin code exists in two Shipping Zones: 'SH1', 'SH2'. So, if the user chose 'Cash On Delivery' option, then I want to disable shipping zone 'SH1' for him while activating 'SH2'.

Here is the code I tried, but not works.

```<code>add_filter( 'woocommerce_available_payment_gateways', 'change_user_zone', 20, 1);
function change_user_zone(  $gateways ){

    $targeted_zones_names = array('COD FCity'); // Targeted zone names
    $current_payment_gateway = WC()->session->get('chosen_payment_method'); // Selected payment gateway

    // Current zone name
    $chosen_methods    = WC()->session->get( 'chosen_shipping_methods' ); // The chosen shipping mehod
    $chosen_method     = explode(':', reset($chosen_methods) );
    $shipping_zone     = WC_Shipping_Zones::get_zone_by( 'instance_id', $chosen_method[1] );
    $current_zone_name = $shipping_zone->get_zone_name();

    if($current_payment_gateway === "cod" && $current_zone_name === "COD FCity"){
        $WC_Shipping_Zone = new WC_Shipping_Zone();
        $var = $WC_Shipping_Zone->set_zone_locations( "India - Maharashtra - Mumbai" );
    }

    return $gateways;
}
</code>```

Please help!

Note: I'm looking for a coding solution. If you want to suggest any plugin for this, then use the comment section, please.

答:
Ok, I don't find a way to change the shipping zone. So I added the extra fee in the cart depending on the Payment Gateway and Shipping Zone.

```<code>add_filter( 'woocommerce_before_calculate_totals', 'update_the_cart_with_extra_fee');
function update_the_cart_with_extra_fee(){
    global $woocommerce;
    $targeted_zones_names = array('SH1'); // Targeted zone names
    $current_payment_gateway = WC()->session->get('chosen_payment_method'); // Selected payment gateway

    // Current zone name
    $chosen_methods    = WC()->session->get( 'chosen_shipping_methods' ); // The chosen shipping mehod
    $chosen_method     = explode(':', reset($chosen_methods) );
    $shipping_zone     = WC_Shipping_Zones::get_zone_by( 'instance_id', $chosen_method[1] );
    $current_zone_name = $shipping_zone->get_zone_name();

    if($current_payment_gateway === "cod" && $current_zone_name === "SH1"){
        $extra_shipping_cost = 0;
        //Loop through the cart to find out the extra costs
        foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
            //Get the product info
            $_product = $values['data'];

            //Get the custom field value - make sure it's i.e. 10 not $10.00
            $custom_shipping_cost = 60;

            //Adding together the extra costs
            $extra_shipping_cost = $extra_shipping_cost + $custom_shipping_cost;

            $woocommerce->cart->add_fee( __('Cash on Delivery', 'woocommerce'), $extra_shipping_cost ); // Place this outside of foreach loop if you want to add fee for every product in the cart.
        }
    }

}
</code>```

I hope this will help someone.

Body:
Target: I want to add different shipping cost for the different payment gateways depending on the pin code user have.

Tried Using Shipping Zones:

I have 3 different shipping zones added in my woo-commerce dashboard. All the zones are created using the pin codes of the city and flat rate. However, if the pin code exists in multiple zones, then the top level zone gets the first priority and all other zones get ignored at the checkout page.

Now I want to change that zone depending on the Payment Gateway user chooses. For example user, 'A' has the pin code '123456' and this pin code exists in two Shipping Zones: 'SH1', 'SH2'. So, if the user chose 'Cash On Delivery' option, then I want to disable shipping zone 'SH1' for him while activating 'SH2'.

Here is the code I tried, but not works.

add_filter( 'woocommerce_available_payment_gateways', 'change_user_zone', 20, 1);
function change_user_zone(  $gateways ){

    $targeted_zones_names = array('COD FCity'); // Targeted zone names
    $current_payment_gateway = WC()->session->get('chosen_payment_method'); // Selected payment gateway

    // Current zone name
    $chosen_methods    = WC()->session->get( 'chosen_shipping_methods' ); // The chosen shipping mehod
    $chosen_method     = explode(':', reset($chosen_methods) );
    $shipping_zone     = WC_Shipping_Zones::get_zone_by( 'instance_id', $chosen_method[1] );
    $current_zone_name = $shipping_zone->get_zone_name();

    if($current_payment_gateway === "cod" && $current_zone_name === "COD FCity"){
        $WC_Shipping_Zone = new WC_Shipping_Zone();
        $var = $WC_Shipping_Zone->set_zone_locations( "India - Maharashtra - Mumbai" );
    }

    return $gateways;
}

Please help!

Note: I'm looking for a coding solution. If you want to suggest any plugin for this, then use the comment section, please.

Body:
Ok, I don't find a way to change the shipping zone. So I added the extra fee in the cart depending on the Payment Gateway and Shipping Zone.

add_filter( 'woocommerce_before_calculate_totals', 'update_the_cart_with_extra_fee');
function update_the_cart_with_extra_fee(){
    global $woocommerce;
    $targeted_zones_names = array('SH1'); // Targeted zone names
    $current_payment_gateway = WC()->session->get('chosen_payment_method'); // Selected payment gateway

    // Current zone name
    $chosen_methods    = WC()->session->get( 'chosen_shipping_methods' ); // The chosen shipping mehod
    $chosen_method     = explode(':', reset($chosen_methods) );
    $shipping_zone     = WC_Shipping_Zones::get_zone_by( 'instance_id', $chosen_method[1] );
    $current_zone_name = $shipping_zone->get_zone_name();

    if($current_payment_gateway === "cod" && $current_zone_name === "SH1"){
        $extra_shipping_cost = 0;
        //Loop through the cart to find out the extra costs
        foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
            //Get the product info
            $_product = $values['data'];

            //Get the custom field value - make sure it's i.e. 10 not $10.00
            $custom_shipping_cost = 60;

            //Adding together the extra costs
            $extra_shipping_cost = $extra_shipping_cost + $custom_shipping_cost;

            $woocommerce->cart->add_fee( __('Cash on Delivery', 'woocommerce'), $extra_shipping_cost ); // Place this outside of foreach loop if you want to add fee for every product in the cart.
        }
    }

}

I hope this will help someone.


问:
How can I limit a html input box so that it only accepts numeric input?
I have an html input box, but only numeric data is data. How can I enforce that?</p>

答:
You will need an events to validate if the entered text is a number or not. See sample code

JS

```<code>function isValidChar(char){

    var txt = char;
    var found = false;
    var validChars = "0123456789"; //List of valid characters

    for(j=0;j<txt.length;j++){ //Will look through the value of text
        var c = txt.charAt(j);
        found = false;
        for(x=0;x<validChars.length;x++){
            if(c==validChars.charAt(x)){
                found=true;
                break;
            }
        }
        if(!found){
            //If invalid character is found remove it and return the valid character(s).
            document.getElementById('txtFld').value = char.substring(0, char.length -1);
            break;
        }
    }
}
</code>```

HTML

```<code><input type="text" id="txtFld" onKeyup="isValidChar(this.value);" />
</code>```

See working code here jsfiddle

Though the code is a bit long you can minimize if you know how to use regular expression or a jquery.

Body:
You will need an events to validate if the entered text is a number or not. See sample code

JS

function isValidChar(char){

    var txt = char;
    var found = false;
    var validChars = "0123456789"; //List of valid characters

    for(j=0;j<txt.length;j++){ //Will look through the value of text
        var c = txt.charAt(j);
        found = false;
        for(x=0;x<validChars.length;x++){
            if(c==validChars.charAt(x)){
                found=true;
                break;
            }
        }
        if(!found){
            //If invalid character is found remove it and return the valid character(s).
            document.getElementById('txtFld').value = char.substring(0, char.length -1);
            break;
        }
    }
}

HTML

<input type="text" id="txtFld" onKeyup="isValidChar(this.value);" />

See working code here jsfiddle

Though the code is a bit long you can minimize if you know how to use regular expression or a jquery.


问:
How can Java prevent duplicated number creation with Random class?
I'm learning Java by reading the book "JAVA, How To Program", and I have reached chapter 7 which talks about array and arrays manipulations. In section 7.5 (case study: card shuffling and dealing simulation), it presents a program that creates a deck of cards, shuffles it and displays the shuffled cards without any duplicates.

In the program it uses the method shuffle to shuffle the cards after creating them. The method uses random object to create a random number between 0 and 51 to select a card from the deck and assign it to an array. The code:

```<code> public void shuffle() {
     // after shuffling, dealing should start at deck[ 0 ] again
     currentCard = 0; // reinitialize currentCard

     // for each Card, pick another random Card (0-51) and swap them
     for (int first = 0; first < deck.length; first++) {
         // select a random number between 0 and 51
         int second = randomNumbers.nextInt( NUMBER_OF_CARDS );

         // swap current Card with randomly selected Card
         Card temp = deck[ first ];
         deck[ first ] = deck[ second ];
         deck[ second ] = temp;
    }
}
</code>```

What if int second = randomNumbers.nextInt( Number_OF_CARDS );
generates a random number that is already selected? Wouldn't be there any duplicates in the deck? If this not the case, why duplicated numbers are not given by this line? What am I missing?

I have learnt that random numbers are generated "almost" equally between the range given, but there is still a chance for generating a number that is already generated before.

答:
It won't duplicate, because you're always swapping cards, and swapping can never duplicate. For instance, let's say my list starts out [a, b, c, d]. If I pick 1 as my first random number, then I swap elements 0 and 2, and end up with [c, b, a, d]. If I pick 2 again for my second number, I swap 1 and 2, and end up with [c, a, b, d].

But you are right that the algorithm is wrong! You can swap an already-swapped card, meaning that cards that get swapped early have a higher chance of getting swapped again, which introduces a bias. This CodingHorror blog post talks about it some, and there are many other discussions online if you search for "wrong shuffling algorithm" or such.

Instead, if you're trying to swap a card into position i, you should randomly pick a card from location x such that i <= x < deck.length. I forget offhand what the name of the book's (incorrect) algorithm is, but the variant I mentioned is called Fisher–Yates shuffle.

Body:
I'm learning Java by reading the book "JAVA, How To Program", and I have reached chapter 7 which talks about array and arrays manipulations. In section 7.5 (case study: card shuffling and dealing simulation), it presents a program that creates a deck of cards, shuffles it and displays the shuffled cards without any duplicates.

In the program it uses the method shuffle to shuffle the cards after creating them. The method uses random object to create a random number between 0 and 51 to select a card from the deck and assign it to an array. The code:

 public void shuffle() {
     // after shuffling, dealing should start at deck[ 0 ] again
     currentCard = 0; // reinitialize currentCard

     // for each Card, pick another random Card (0-51) and swap them
     for (int first = 0; first < deck.length; first++) {
         // select a random number between 0 and 51
         int second = randomNumbers.nextInt( NUMBER_OF_CARDS );

         // swap current Card with randomly selected Card
         Card temp = deck[ first ];
         deck[ first ] = deck[ second ];
         deck[ second ] = temp;
    }
}

What if int second = randomNumbers.nextInt( Number_OF_CARDS );
generates a random number that is already selected? Wouldn't be there any duplicates in the deck? If this not the case, why duplicated numbers are not given by this line? What am I missing?

I have learnt that random numbers are generated "almost" equally between the range given, but there is still a chance for generating a number that is already generated before.


问:
How to find a duplicate element in an unordered array using constant space
I am revising exam questions and I have come accross this one that I cannot solve (10.a).

Since I can't modify the array I know I cannot use Bubble Sort for instance, but the bit that is throwing me is the "not dependent on n", the only idea I can come up with would be to select the array[i] element and compare it to array[i+j] which I understand is not allowed since it would dependent on n.

We are several in our course scratching out heads at how should we approach this one, anybody could give us an idea on how to solve it?

For the second part we are OK since we have done a few search algorithm that could solve the question.

答:
may use only a constant amount of additional space

This means that your algorithm is only allowed to use a fixed number of memory cells. However, it does not mean that you're forbidden to access memory holding the input array.

Note that the question is talking about constant space, not constant time.

A solution that compares every array[i] to array[i+j] is perfectly acceptable, since it only needs 1 additional memory cell (holding the result).


问:
Why am i getting an error hip: bitstream problem, resyncing skipping while playing mp3 songs?
I am getting an error of bitsream problem. I am already skipping reading of id3tag by 512 bytes, but still I am not able to play all songs while some songs are getting played</p>

```<code>define MP3_SKIP_SIZE  512
fseek(playerDetails->mp3Fp,MP3_SKIP_SIZE,SEEK_SET);
</code>```

答:
Size of ID3 tags is variable, it is not neccessarily 512 bytes.

You can use id3lib to find out size of ID3 tags:

#include <id3/tag.h>

// Get size of ID3 tags

size_t getID3TagSize(const char* filename)
{
    ID3_Tag myTag(filename);

    return myTag.Size();
}

#include <lame.h>

void decodeMp3(const char* fileName)
{
    size_t mp3TagSize = getID3TagSize(fileName);

    f.open(fileName, std::ios::binary);

    f.seekg(mp3TagSize); //Skip ID3 tags

    std::array<unsigned char, 1024*1024> buffer;

    f.read(reinterpret_cast<char*>(&buffer[0]), buffer.size());

    auto count = f.gcount();

    hip_t lameInput = hip_decode_init();

    mp3data_struct mp3data{ 0 };

    std::array<short, 1024 * 1024 * 8> pcm_l;
    std::array<short, 1024 * 1024 * 8> pcm_r;

    int decodeResult = hip_decode_headers(lameInput, &buffer[0], count, &pcm_l[0], &pcm_r[0], &mp3data);

    //... Continue decoding ...

}

```

Body:
I am getting an error of bitsream problem. I am already skipping reading of id3tag by 512 bytes, but still I am not able to play all songs while some songs are getting played

define MP3_SKIP_SIZE  512
fseek(playerDetails->mp3Fp,MP3_SKIP_SIZE,SEEK_SET);


问:
Jade - Trying display collection data from mongodb
i want to display data from mongodb collection

i am using pug for and want to display my data collection in mongodb

but i have no idea, about this error

i have tried this

it's my .pug file

```<code>extends layout

block content
    if registrations.length
        table
            tr
                th Name
                th Email
            each registration in registrations
                tr
                    td=registration.name
                    td=registration.email
    else
        p No registrations yet
</code>```

it's my index.js file

```<code>
const Registration = mongoose.model('Registration');
router.get('/registrations', (req, res) => {
    Registration.find()
        .then((registrations) => {
            res.render('index', { title: 'Listing registrations' });
        })
        .catch(() => { res.send('Something went wrong'); });
});
</code>```

it's the error message

```<code>TypeError: E:\web_apps_project\demo-node-app\views\index.pug:4
    2|

    3| block content

  > 4|     if registrations.length

    5|         table

    6|             tr

    7|                 th Name

Cannot read property 'length' of undefined
    at eval (eval at wrap (E:\web_apps_project\demo-node-app\node_modules\pug-runtime\wrap.js:6:10), <anonymous>:21:19)
    at template (eval at wrap (E:\web_apps_project\demo-node-app\node_modules\pug-runtime\wrap.js:6:10), <anonymous>:79:50)
    at Object.exports.renderFile (E:\web_apps_project\demo-node-app\node_modules\pug\lib\index.js:427:38)
    at Object.exports.renderFile (E:\web_apps_project\demo-node-app\node_modules\pug\lib\index.js:417:21)
    at View.exports.__express [as engine] (E:\web_apps_project\demo-node-app\node_modules\pug\lib\index.js:464:11)
    at View.render (E:\web_apps_project\demo-node-app\node_modules\express\lib\view.js:135:8)
    at tryRender (E:\web_apps_project\demo-node-app\node_modules\express\lib\application.js:640:10)
    at Function.render (E:\web_apps_project\demo-node-app\node_modules\express\lib\application.js:592:3)
    at ServerResponse.render (E:\web_apps_project\demo-node-app\node_modules\express\lib\response.js:1012:7)
    at Registration.find.then (E:\web_apps_project\demo-node-app\routes\index.js:36:17)
    at process._tickCallback (internal/process/next_tick.js:68:7)
</code>```

答:
You need to pass the registrations returned from the database query to the template as follows:</p>

```<code>router.get('/registrations', (req, res) => {
    Registration.find()
        .then((registrations) => {
            res.render('index', { title: 'Listing registrations', 'registrations': registrations });
        })
        .catch(() => { res.send('Something went wrong'); });
});
</code>```

Body:
i want to display data from mongodb collection

i am using pug for and want to display my data collection in mongodb

but i have no idea, about this error

i have tried this

it's my .pug file

extends layout

block content
    if registrations.length
        table
            tr
                th Name
                th Email
            each registration in registrations
                tr
                    td=registration.name
                    td=registration.email
    else
        p No registrations yet

it's my index.js file

const Registration = mongoose.model('Registration');
router.get('/registrations', (req, res) => {
    Registration.find()
        .then((registrations) => {
            res.render('index', { title: 'Listing registrations' });
        })
        .catch(() => { res.send('Something went wrong'); });
});

it's the error message

TypeError: E:\web_apps_project\demo-node-app\views\index.pug:4
    2|

    3| block content

  > 4|     if registrations.length

    5|         table

    6|             tr

    7|                 th Name

Cannot read property 'length' of undefined
    at eval (eval at wrap (E:\web_apps_project\demo-node-app\node_modules\pug-runtime\wrap.js:6:10), <anonymous>:21:19)
    at template (eval at wrap (E:\web_apps_project\demo-node-app\node_modules\pug-runtime\wrap.js:6:10), <anonymous>:79:50)
    at Object.exports.renderFile (E:\web_apps_project\demo-node-app\node_modules\pug\lib\index.js:427:38)
    at Object.exports.renderFile (E:\web_apps_project\demo-node-app\node_modules\pug\lib\index.js:417:21)
    at View.exports.__express [as engine] (E:\web_apps_project\demo-node-app\node_modules\pug\lib\index.js:464:11)
    at View.render (E:\web_apps_project\demo-node-app\node_modules\express\lib\view.js:135:8)
    at tryRender (E:\web_apps_project\demo-node-app\node_modules\express\lib\application.js:640:10)
    at Function.render (E:\web_apps_project\demo-node-app\node_modules\express\lib\application.js:592:3)
    at ServerResponse.render (E:\web_apps_project\demo-node-app\node_modules\express\lib\response.js:1012:7)
    at Registration.find.then (E:\web_apps_project\demo-node-app\routes\index.js:36:17)
    at process._tickCallback (internal/process/next_tick.js:68:7)

Body:
You need to pass the registrations returned from the database query to the template as follows:

router.get('/registrations', (req, res) => {
    Registration.find()
        .then((registrations) => {
            res.render('index', { title: 'Listing registrations', 'registrations': registrations });
        })
        .catch(() => { res.send('Something went wrong'); });
});


问:
Cannot set the window icon in android
How can I set a window icon for all the activities. I have gone through the window features and relative methods to set the features.

Here is the code I have used to set the icon:

```<code>requestWindowFeature(Window.FEATURE_LEFT_ICON);
setContentView(R.layout.main);
setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.icon);
</code>```

I have called this code in the 'onCreate' method of an activity. Icon is set for the main activity. But whenever I go to other activities, no icon is set in the window. I cannot see any errors in the logcat. Please help me.

答:
It was a cache problem :)

I have Uninstalled the application from the emulator and deleted the following files from the 'bin' folder:

classes.dex

ApplicationName.apk

resources.ap_

Deleted the R.java file.
It worked perfectly after reinstalling the application.

Title: Cannot set the window icon in android

Body:
How can I set a window icon for all the activities. I have gone through the window features and relative methods to set the features.

Here is the code I have used to set the icon:

requestWindowFeature(Window.FEATURE_LEFT_ICON);
setContentView(R.layout.main);
setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.icon);

I have called this code in the 'onCreate' method of an activity. Icon is set for the main activity. But whenever I go to other activities, no icon is set in the window. I cannot see any errors in the logcat. Please help me.


问:
Can't get result outside the query function in express nodejs
I am trying to get the value of variable w_name outside query even I have defined w_name before query but cannot getting it after query. Please check the code and help:

```<code>connection.query('SELECT * FROM workstations WHERE id=?',[results[0].w_id],function(err,res,field){
                        w_name = res[0].name;
                });
                console.log(w_name);
</code>```

console.log showing undefined but if I am putting console.log inside the query after w_name it is showing proper result. What's wrong in it?

答:
connection.query(...params) is asynchronous function, which requires some time to read and get resulting data for query passed to it.
Defining console.log(w_name) prints undefined because result is not yet assigned to w_name variable. Whereas defining it inside callback function assigns value to w_name.

Check this article for understanding asynchronous javascript.

```<code>           connection.query('SELECT * FROM workstations WHERE id=?',
                    [results[0].w_id],function(err,res,field){

                    w_name = res[0].name;
                      console.log(w_name);
            });
</code>```

Body:
I am trying to get the value of variable w_name outside query even I have defined w_name before query but cannot getting it after query. Please check the code and help:

connection.query('SELECT * FROM workstations WHERE id=?',[results[0].w_id],function(err,res,field){
                        w_name = res[0].name;
                });
                console.log(w_name);

console.log showing undefined but if I am putting console.log inside the query after w_name it is showing proper result. What's wrong in it?

Body:
connection.query(...params) is asynchronous function, which requires some time to read and get resulting data for query passed to it.
Defining console.log(w_name) prints undefined because result is not yet assigned to w_name variable. Whereas defining it inside callback function assigns value to w_name.

Check this article for understanding asynchronous javascript.

           connection.query('SELECT * FROM workstations WHERE id=?',
                    [results[0].w_id],function(err,res,field){

                    w_name = res[0].name;
                      console.log(w_name);
            });


问:
Calculation island error with perlin noise
I'm developing a small project, which is a grid of 100 x 100 hexagons.
In the script below, I paint my hexagons with the perlin noise, but the format I want to island does not go away.
I'll leave my code and 2 examples as my map stays and how I wish it to stay.

My island

My Island

As i need

Im Need

```<code>int getColor(float x, float z)
{
    xTO = (int)x / terrainWidth - 30;
    zTO = (int)z / terrainHeight - 30;

    float v = Mathf.PerlinNoise((xTO + x + seed) * freq, (zTO + z) * freq);
    //  v += 0.001f;

    float form = formWorld(x, z);

    if (v < 0.25f)
    {
        //water
        return 0;
    }
    else if (v < 0.5f)
    {
        //sand
        return 1;
    }

    else if (v < 0.75f)
    {
        //grass
        return 2;
    }
    else
    {
        //Trees / Forest
        MakeNewTree(new Vector3(xx, 0, z * 7.5f));
        return 2;
    }
}
</code>```

答:
If you want your image to look more like the second one, the best option is going to be adding a circular gradient which offsets your Perlin Noise.

The easiest way to do this is to measure the distance from the center and combine that with the perlin noise.

Here's some untested code.

```<code>    int getColor(float x, float z)
    {
        xTO = (int)x / terrainWidth - 30;
        zTO = (int)z / terrainHeight - 30;

        float v = Mathf.PerlinNoise((xTO + x + seed) * freq, (zTO + z) * freq);
        //  v += 0.001f;
        v -= CircleOffset(x,z)/2; //Change the two to make the island bigger.

        float form = formWorld(x, z);

        if (v < 0.25f)
        {
            //water
            return 0;
        }
        else if (v < 0.5f)
        {
            //sand
            return 1;
        }

        else if (v < 0.75f)
        {
            //grass
            return 2;
        }
        else
        {
            //Trees / Forest
            MakeNewTree(new Vector3(xx, 0, z * 7.5f));
            return 2;
        }
    }

    float CircleOffset(float x, float y)
    {
        Vector2 center = new Vector2(terrainWidth/2,terrainHeight/2);
        float distance = Mathf.Sqrt((center.x - x)*(center.x - x) + (center.y - y) * (center.y - y));
        return distance/terrainWidth;
    }
</code>```

Hope this helps!

Body:
I'm developing a small project, which is a grid of 100 x 100 hexagons.
In the script below, I paint my hexagons with the perlin noise, but the format I want to island does not go away.
I'll leave my code and 2 examples as my map stays and how I wish it to stay.

My island

My Island

As i need

Im Need

int getColor(float x, float z)
{
    xTO = (int)x / terrainWidth - 30;
    zTO = (int)z / terrainHeight - 30;

    float v = Mathf.PerlinNoise((xTO + x + seed) * freq, (zTO + z) * freq);
    //  v += 0.001f;

    float form = formWorld(x, z);

    if (v < 0.25f)
    {
        //water
        return 0;
    }
    else if (v < 0.5f)
    {
        //sand
        return 1;
    }

    else if (v < 0.75f)
    {
        //grass
        return 2;
    }
    else
    {
        //Trees / Forest
        MakeNewTree(new Vector3(xx, 0, z * 7.5f));
        return 2;
    }
}

Body:
If you want your image to look more like the second one, the best option is going to be adding a circular gradient which offsets your Perlin Noise.

The easiest way to do this is to measure the distance from the center and combine that with the perlin noise.

Here's some untested code.

    int getColor(float x, float z)
    {
        xTO = (int)x / terrainWidth - 30;
        zTO = (int)z / terrainHeight - 30;

        float v = Mathf.PerlinNoise((xTO + x + seed) * freq, (zTO + z) * freq);
        //  v += 0.001f;
        v -= CircleOffset(x,z)/2; //Change the two to make the island bigger.

        float form = formWorld(x, z);

        if (v < 0.25f)
        {
            //water
            return 0;
        }
        else if (v < 0.5f)
        {
            //sand
            return 1;
        }

        else if (v < 0.75f)
        {
            //grass
            return 2;
        }
        else
        {
            //Trees / Forest
            MakeNewTree(new Vector3(xx, 0, z * 7.5f));
            return 2;
        }
    }

    float CircleOffset(float x, float y)
    {
        Vector2 center = new Vector2(terrainWidth/2,terrainHeight/2);
        float distance = Mathf.Sqrt((center.x - x)*(center.x - x) + (center.y - y) * (center.y - y));
        return distance/terrainWidth;
    }

Hope this helps!


问:
ASP.Net MVC 2 Application Login page as startuppage
Dear All,
I want to disable anonymous access to my MVC 2 application for that I add below code in web.config file <deny users="?" />
     <authentication mode="Forms">
      <forms loginUrl="~/Account/LogOn" timeout="2880" />
    </authentication>
After that application start with login page but it is not taking masterpage and css styles

This is Login page code

`<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

    Log On

Log On

        Please enter your username and password. <%: Html.ActionLink("Register", "Register") %> if you don't have an account.

```<code><% using (Html.BeginForm()) { %>
    <%: Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.") %>
    <div>
        <fieldset>
            <legend>Account Information</legend>

            <div class="editor-label">
                <%: Html.LabelFor(m => m.UserName) %>
            </div>
            <div class="editor-field">
                <%: Html.TextBoxFor(m => m.UserName) %>
                <%: Html.ValidationMessageFor(m => m.UserName) %>
            </div>

            <div class="editor-label">
                <%: Html.LabelFor(m => m.Password) %>
            </div>
            <div class="editor-field">
                <%: Html.PasswordFor(m => m.Password) %>
                <%: Html.ValidationMessageFor(m => m.Password) %>
            </div>

            <div class="editor-label">
                <%: Html.CheckBoxFor(m => m.RememberMe) %>
                <%: Html.LabelFor(m => m.RememberMe) %>
            </div>

            <p>
                <input type="submit" value="Log On" />
            </p>
        </fieldset>
    </div>
<% } %>
</code>```

`

can someone direct me what I am missing?

答:
Don't use <deny users="?" /> in ASP.NET MVC. Use the [Authorize] attribute to decorate controllers/action that need to be protected. So for example if you wanted to protect all controllers you could have a base controller which will be decorated with this attribute:

```<code>[Authorize]
public abstract class BaseController: Controller
{
    protected BaseController() {}
}
</code>```

and then have other controllers derive from it. Obviously the LoginController shouldn't derive from this base controller as it need to show the login form without requiring authentication.

Body:
Dear All,
I want to disable anonymous access to my MVC 2 application for that I add below code in web.config file <deny users="?" />
     <authentication mode="Forms">
      <forms loginUrl="~/Account/LogOn" timeout="2880" />
    </authentication>
After that application start with login page but it is not taking masterpage and css styles

This is Login page code

`<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

    Log On

Log On

        Please enter your username and password. <%: Html.ActionLink("Register", "Register") %> if you don't have an account.

<% using (Html.BeginForm()) { %>
    <%: Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.") %>

        <fieldset>
            <legend>Account Information</legend>

                <%: Html.LabelFor(m => m.UserName) %>

                <%: Html.TextBoxFor(m => m.UserName) %>
                <%: Html.ValidationMessageFor(m => m.UserName) %>

                <%: Html.LabelFor(m => m.Password) %>

                <%: Html.PasswordFor(m => m.Password) %>
                <%: Html.ValidationMessageFor(m => m.Password) %>

                <%: Html.CheckBoxFor(m => m.RememberMe) %>
                <%: Html.LabelFor(m => m.RememberMe) %>

                <input type="submit" value="Log On" />

        </fieldset>

<% } %>

`

can someone direct me what I am missing?

Body:
Don't use <deny users="?" /> in ASP.NET MVC. Use the [Authorize] attribute to decorate controllers/action that need to be protected. So for example if you wanted to protect all controllers you could have a base controller which will be decorated with this attribute:

[Authorize]
public abstract class BaseController: Controller
{
    protected BaseController() {}
}

and then have other controllers derive from it. Obviously the LoginController shouldn't derive from this base controller as it need to show the login form without requiring authentication.