问:
If a parameter of event handler contains certain characters, JavaScript does not execute properly
php:

```<code>$str1 = "AAA\r\nBBBB\\CCC";
echo"<textarea id='aa1' onfocus='erase(\"".$str1."\", \"aa1\");'></textarea>";
$str2 = "AAABBBB\\CCC";
echo"<textarea id='aa2' onfocus='erase(\"".$str2."\", \"aa2\");'></textarea>";
$str3 = "AAABBBB\CCC";
echo"<textarea id='aa3' onfocus='erase(\"".$str3."\", \"aa3\");'></textarea>";
$str4 = "AAABBBBCCC";
echo"<textarea id='aa4' onfocus='erase(\"".$str4."\", \"aa4\");'></textarea>";
</code>```

javascript:

```<code>function erase(str, id)
{
    alert("good");
    var field = document.getElementById(id);
    if(field.value == str)
    {
        field.value = '';
    }
}
</code>```

If I click on textarea id='aa1', nothing happens.

If I click on textarea id='aa2' or textarea id='aa3', 'good' is printed but nothing happens to field.value.

If I click on textarea id='aa4', 'good' is printed and field.value is ''.

I want a string like AAA\r\nBBBB\\CCC to work like textarea id='aa4.

How can I do that?

I read the post below but it does not seem to help my situation:

Javascript parameter

Javascript Line Break Textarea

update:

I've replaced $str1 with json_encode($str1), So alert(); works fine now. (Thanks to Jordan Running.)

But the field.value part still does not work.

code refactoring is too hard in my situation... Is there any way to handle the field.value problem without code refactoring?

If quotes corrupt my HTML, I can putting $str1 in htmlspecialchars() and displaying it in <textarea>.

答:
Generally speaking it's a bad idea to use string concatenation to build JavaScript. Your PHP code produces the following HTML:

<textarea id='aa1' onfocus='erase("AAA
BBBB\CCC", "aa1");'></textarea>
```

<p>That's valid HTML, but the code in your <code>onfocus</code> attribute is <em>not</em> valid JavaScript. In JavaScript, you can't have a line break in the middle of a string literal. You can have a line break in a template literal (i.e. <code>`one of these`</code>), but that's not the right solution here.</p>

<h1>A quick but short-sighted fix</h1>

<p>When you need to "inject" some data into a block of JavaScript, you should always use <code>json_encode</code>:</p>

<pre class="lang-php prettyprint-override"><code>$str1 = "AAA\r\nBBBB\\CCC";
echo "<textarea id='aa1' onfocus='erase(" . json_encode($str1) . ", \"aa1\");'></textarea>";
</code>```

Make careful note of the quotation marks above. Because json_encode wraps strings in quotation marks, you don't need additional quotes around . json_encode($str1) ..

This will produce the following HTML:

<textarea id='aa1' onfocus='erase("AAA\r\nBBBB\\CCC", "aa1");'></textarea>
```

<p>...whose <code>onfocus</code> handler works correctly, as you can see in this snippet:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function erase(...args) { console.log('erase called with', args); }</code>```

<textarea id='aa1' onfocus='erase("AAA\r\nBBBB\\CCC", "aa1");'></textarea>```
</div>
</div>
</p>

<h1>A better way</h1>

<p>The above is still fragile. What if your data has a <code>'</code> in it? That'll break your HTML. The correct solution is to move your data out of the HTML entirely. Consider if you refactored your code to look something like this:</p>

```<textarea id="aa1"></textarea>
<textarea id="aa2"></textarea>
<textarea id="aa3"></textarea>
<textarea id="aa4"></textarea>
<?php
  $erase_map = [
    'aa1' => "AAA\r\nBBBB\\CCC",
    'aa2' => "AAABBBB\\CCC",
    'aa3' => "AAABBBB\CCC",
    'aa4' => "AAABBBBCCC",
  ];
?>

```

<p>In the above code, all of the data is in one place—a single associative array—instead of scattered around your HTML. It generates HTML code with a <code><script></code> tag into which the data is injected as a JSON object and assigned to a JavaScript variable:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><textarea id="aa1"></textarea>
<textarea id="aa2"></textarea>
<textarea id="aa3"></textarea>
<textarea id="aa4"></textarea>
<script>
  const ERASE_MAP = {"aa1":"AAA\r\nBBBB\\CCC","aa2":"AAABBBB\\CCC","aa3":"AAABBBB\\CCC","aa4":"AAABBBBCCC"};

  function erase(event) {
    if (event.target.value == ERASE_MAP[event.target.id]) {
      event.target.value = '';
    }
  }
  document.querySelectorAll('textarea').forEach(textarea => textarea.addEventListener('focus', erase));
</script></code>```

Body:
php:

$str1 = "AAA\r\nBBBB\\CCC";
echo"<textarea id='aa1' onfocus='erase(\"".$str1."\", \"aa1\");'></textarea>";
$str2 = "AAABBBB\\CCC";
echo"<textarea id='aa2' onfocus='erase(\"".$str2."\", \"aa2\");'></textarea>";
$str3 = "AAABBBB\CCC";
echo"<textarea id='aa3' onfocus='erase(\"".$str3."\", \"aa3\");'></textarea>";
$str4 = "AAABBBBCCC";
echo"<textarea id='aa4' onfocus='erase(\"".$str4."\", \"aa4\");'></textarea>";

javascript:

function erase(str, id)
{
    alert("good");
    var field = document.getElementById(id);
    if(field.value == str)
    {
        field.value = '';
    }
}

If I click on textarea id='aa1', nothing happens.

If I click on textarea id='aa2' or textarea id='aa3', 'good' is printed but nothing happens to field.value.

If I click on textarea id='aa4', 'good' is printed and field.value is ''.

I want a string like AAA\r\nBBBB\\CCC to work like textarea id='aa4.

How can I do that?

I read the post below but it does not seem to help my situation:

Javascript parameter

Javascript Line Break Textarea

update:

I've replaced $str1 with json_encode($str1), So alert(); works fine now. (Thanks to Jordan Running.)

But the field.value part still does not work.

code refactoring is too hard in my situation... Is there any way to handle the field.value problem without code refactoring?

If quotes corrupt my HTML, I can putting $str1 in htmlspecialchars() and displaying it in <textarea>.

Body:
Generally speaking it's a bad idea to use string concatenation to build JavaScript. Your PHP code produces the following HTML:

<textarea id='aa1' onfocus='erase("AAA
BBBB\CCC", "aa1");'></textarea>

That's valid HTML, but the code in your onfocus attribute is not valid JavaScript. In JavaScript, you can't have a line break in the middle of a string literal. You can have a line break in a template literal (i.e. `one of these`), but that's not the right solution here.

A quick but short-sighted fix

When you need to "inject" some data into a block of JavaScript, you should always use json_encode:

$str1 = "AAA\r\nBBBB\\CCC";
echo "<textarea id='aa1' onfocus='erase(" . json_encode($str1) . ", \"aa1\");'></textarea>";

Make careful note of the quotation marks above. Because json_encode wraps strings in quotation marks, you don't need additional quotes around . json_encode($str1) ..

This will produce the following HTML:

<textarea id='aa1' onfocus='erase("AAA\r\nBBBB\\CCC", "aa1");'></textarea>

...whose onfocus handler works correctly, as you can see in this snippet:

function erase(...args) { console.log('erase called with', args); }

<textarea id='aa1' onfocus='erase("AAA\r\nBBBB\\CCC", "aa1");'></textarea>

A better way

The above is still fragile. What if your data has a ' in it? That'll break your HTML. The correct solution is to move your data out of the HTML entirely. Consider if you refactored your code to look something like this:

<textarea id="aa1"></textarea>
<textarea id="aa2"></textarea>
<textarea id="aa3"></textarea>
<textarea id="aa4"></textarea>
<?php
  $erase_map = [
    'aa1' => "AAA\r\nBBBB\\CCC",
    'aa2' => "AAABBBB\\CCC",
    'aa3' => "AAABBBB\CCC",
    'aa4' => "AAABBBBCCC",
  ];
?>
<script>
  const ERASE_MAP = <?php echo json_encode($erase_map); ?>;

  function erase(event) {
    if (event.target.value == ERASE_MAP[event.target.id]) {
      event.target.value = '';
    }
  }
  document.querySelectorAll('textarea').forEach(textarea => textarea.addEventListener('focus', erase));
</script>

In the above code, all of the data is in one place—a single associative array—instead of scattered around your HTML. It generates HTML code with a <script> tag into which the data is injected as a JSON object and assigned to a JavaScript variable:

<textarea id="aa1"></textarea>
<textarea id="aa2"></textarea>
<textarea id="aa3"></textarea>
<textarea id="aa4"></textarea>
<script>
  const ERASE_MAP = {"aa1":"AAA\r\nBBBB\\CCC","aa2":"AAABBBB\\CCC","aa3":"AAABBBB\\CCC","aa4":"AAABBBBCCC"};

  function erase(event) {
    if (event.target.value == ERASE_MAP[event.target.id]) {
      event.target.value = '';
    }
  }
  document.querySelectorAll('textarea').forEach(textarea => textarea.addEventListener('focus', erase));
</script>


来源: stackexchange

问:
Why cannot I return values from two functions in Java?
Error description here

I can return either getMonth() or getYear() from the following code.

When both are called, an error is displayed.

I have tried giving the value of m and y separately in the calculate date function and that works perfectly !!
Any suggestions?

I am a beginner, apologies if there is a trivial mistake, though there shouldn't be according to me.

```<code>import java.util.Scanner;

public class Second_Java {

public static int getMonth() {

    int a;
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the input for the required month: ");
    a = sc.nextInt(); // stored in 'a' locally

    while (a < 1 || a > 12) {

        a = -1;
        System.out.println(a);

    }
    sc.close();
    return a;
}

public static int getYear() {

    int b;
    Scanner input = new Scanner(System.in);
    System.out.println("Enter the input for the required year: ");
    b = input.nextInt(); // stored in 'a' locally

    while (b < 1) {

        b = -2;
        System.out.println(b);

    }
    input.close();
    return b;
}

public static void calculateDays(int m, int y) {

    switch (m) {
    case 4:
    case 6:
    case 9:
    case 11:
        m = 30;
        System.out.println(m);
        break;
    case 2:
        if (y % 400 == 0 || (y % 4 == 0 && y % 100 != 0)) {
            m = 29;
            System.out.println(m);
        } else {
            m = 28;
            System.out.println(m);
        }
        break;
    default: {
        m = 31;
        System.out.println(m);
    }

    }

}

public static void main(String[] args) {

    int m = getMonth();
    int y = getYear();
    calculateDays(m, y);
}
</code>```

}

答:
Closing the Scanner also closes the input stream it's scanning -- in this case System.in. Hence, when you subsequently call getYear(), it finds the input stream System.in already closed.

One way to avoid this is to use the same Scanner in both methods, by passing it as an argument to the methods.

From the Java API docs for Scanner.close():

public void close()

Closes this scanner.

If this scanner has not yet been closed then if its underlying readable also implements the Closeable interface then the readable's close method will be invoked. If this scanner is already closed then invoking this method will have no effect.

By the way, the purpose of the loops in getMonth() and getYear() are unclear. If you want to continue scanning until a valid value is entered, then you want to include a call to Scanner.nextInt() inside the loops. And consider using a do-while statement, since you know you want to read at least one value.

ContentLicense: CC BY-SA 3.0

Body:
Error description here

I can return either getMonth() or getYear() from the following code.

When both are called, an error is displayed.

I have tried giving the value of m and y separately in the calculate date function and that works perfectly !!
Any suggestions?

I am a beginner, apologies if there is a trivial mistake, though there shouldn't be according to me.

import java.util.Scanner;

public class Second_Java {

public static int getMonth() {

    int a;
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the input for the required month: ");
    a = sc.nextInt(); // stored in 'a' locally

    while (a < 1 || a > 12) {

        a = -1;
        System.out.println(a);

    }
    sc.close();
    return a;
}

public static int getYear() {

    int b;
    Scanner input = new Scanner(System.in);
    System.out.println("Enter the input for the required year: ");
    b = input.nextInt(); // stored in 'a' locally

    while (b < 1) {

        b = -2;
        System.out.println(b);

    }
    input.close();
    return b;
}

public static void calculateDays(int m, int y) {

    switch (m) {
    case 4:
    case 6:
    case 9:
    case 11:
        m = 30;
        System.out.println(m);
        break;
    case 2:
        if (y % 400 == 0 || (y % 4 == 0 && y % 100 != 0)) {
            m = 29;
            System.out.println(m);
        } else {
            m = 28;
            System.out.println(m);
        }
        break;
    default: {
        m = 31;
        System.out.println(m);
    }

    }

}

public static void main(String[] args) {

    int m = getMonth();
    int y = getYear();
    calculateDays(m, y);
}

}


问:
List of all scheduled tasks using Python in AWS server
I have an AWS server in which i have a list of scheduled tasks. When i am executing below python script saved in a file named script.py through command prompt, i am not getting name of many tasks in the console.

script

```<code>import win32com.client
def Task_Names():
    path = find_path()
    columns1 = ['Workflow Name','Last Run Time','Status']
    dat = pd.DataFrame(columns1)
    TASK_STATE = {0: 'Unknown',
                  1: 'Disabled',
                  2: 'Queued',
                  3: 'Ready',
                  4: 'Running'}
    scheduler = win32com.client.Dispatch('Schedule.Service')
    scheduler.Connect()
    folders = [scheduler.GetFolder('\\')]
    while folders:
        folder = folders.pop(0)
        folders += list(folder.GetFolders(0))

        for task in folder.GetTasks(0):
            if task.LastTaskResult == -2147023829:
                result = 'Failed'
            elif task.LastTaskResult == -2147024894:
                result = 'The system cannot find the file specified'
            elif task.LastTaskResult == 267009:
                result = 'The task is currently running'
            elif task.LastTaskResult == 0:
                result = 'Completed'
            #status.append(valu)
            print(task.Name,task.LastRunTime,result)

if __name__ == '__main__':
    Task_Names()
</code>```

I saved the file in H:\ScriptRepo, so i am navigating to the folder by using cd command cd /d H:\ScriptRepo in the command prompt. Once i reach there, i am typing python script.py

The problem is i am not able to get name of all the scheduled tasks. When i execute the same script in my local PC, i am able to get the name of all scheduled tasks which i see in task scheduler library window. What am i missing? And Why does this script behave differently in AWS and how do i solve it?

答:
I found the answer myself. Its strange, when i execute the script only list i am getting are the ones i added in the scheduler. Similarly if i ask a different user to execute the script using his credentials it is printing only those tasks which he/she added in the task scheduler. Point to be considered is all the users have administrator privileges.

To solve this i logged into the server using credentials of administrator and now it is printing all workflow details i wanted.

Body:
I have an AWS server in which i have a list of scheduled tasks. When i am executing below python script saved in a file named script.py through command prompt, i am not getting name of many tasks in the console.

script

import win32com.client
def Task_Names():
    path = find_path()
    columns1 = ['Workflow Name','Last Run Time','Status']
    dat = pd.DataFrame(columns1)
    TASK_STATE = {0: 'Unknown',
                  1: 'Disabled',
                  2: 'Queued',
                  3: 'Ready',
                  4: 'Running'}
    scheduler = win32com.client.Dispatch('Schedule.Service')
    scheduler.Connect()
    folders = [scheduler.GetFolder('\\')]
    while folders:
        folder = folders.pop(0)
        folders += list(folder.GetFolders(0))

        for task in folder.GetTasks(0):
            if task.LastTaskResult == -2147023829:
                result = 'Failed'
            elif task.LastTaskResult == -2147024894:
                result = 'The system cannot find the file specified'
            elif task.LastTaskResult == 267009:
                result = 'The task is currently running'
            elif task.LastTaskResult == 0:
                result = 'Completed'
            #status.append(valu)
            print(task.Name,task.LastRunTime,result)

if __name__ == '__main__':
    Task_Names()

I saved the file in H:\ScriptRepo, so i am navigating to the folder by using cd command cd /d H:\ScriptRepo in the command prompt. Once i reach there, i am typing python script.py

The problem is i am not able to get name of all the scheduled tasks. When i execute the same script in my local PC, i am able to get the name of all scheduled tasks which i see in task scheduler library window. What am i missing? And Why does this script behave differently in AWS and how do i solve it?


答:
Loop and build your result, unsetting resumo_mes after you use it.  Then get the remaining values:

```<code>foreach($data as $key => $values) {
    $series[$key]['type'] = 'column';
    $series[$key]['name'] = $values['resumo_mes'];
    unset($values['resumo_mes']);
    $series[$key]['data'] = array_map('intval', array_values($values));
}
</code>```

You could also filter the values with is_numeric or is_int depending on the type. is_numeric works for your sample data as the date is not "numeric":

```<code>foreach($data as $values) {
    $series[] = array('type' => 'column',
                      'name' => $values['resumo_mes'],
                      'data' => array_map('intval',
                                          array_values(
                                          array_filter($values,
                                                       'is_numeric'))));
}
</code>```

Added array_map with intval.

Title: Complicated multidimensional array to use in highchart series

Body:
I need some help creating/modifying a multidimensional array. I have this array created from yii2 ArrayDataProvider:

Array(
[0] => Array
    (
        [resumo_mes] => 2017-06-01
        [total_total] => 15826
        [total_chegadas] => 9560
        [total_partidas] => 6266
        [total_36h] => 9633
        [chegadas_36h] => 6076
        [partidas_36h] => 3557
        [total_90m_36h] => 5510
        [chegadas_90m_36h] => 3001
        [partidas_90m_36h] => 2509
        [total_90m] => 683
        [chegadas_90m] => 483
        [partidas_90m] => 200
    )

[1] => Array
    (
        [resumo_mes] => 2017-05-01
        [total_total] => 16170
        [total_chegadas] => 9625
        [total_partidas] => 6545
        [total_36h] => 9962
        [chegadas_36h] => 6057
        [partidas_36h] => 3905
        [total_90m_36h] => 5542
        [chegadas_90m_36h] => 3139
        [partidas_90m_36h] => 2403
        [total_90m] => 666
        [chegadas_90m] => 429
        [partidas_90m] => 237
    )
)

I'm trying to achieve this:

Array(
[0] => Array
    (
        [type] => column
        [name] => 2017-06-01
        [data] => Array
            (
                [0] => 15826
                [1] => 9560
                [2] => 6266
                [3] => 9633
                [4] => 6076
                [5] => 3557
                [6] => 5510
                [7] => 3001
                [8] => 2509
                [9] => 683
                [10] => 483
                [11] => 200
            )

    )

[1] => Array
    (
        [type] => column
        [name] => 2017-05-01
        [data] => Array
            (
                [0] => 16170
                [1] => 9625
                [2] => 6545
                [3] => 9962
                [4] => 6057
                [5] => 3905
                [6] => 5542
                [7] => 3139
                [8] => 2403
                [9] => 666
                [10] => 429
                [11] => 237
            )

    )
)

But I'm stuck getting the values, with this code:

$data = $dataProvider->getModels();
foreach ($data as $d) {
    $mes[] = $d['resumo_mes'];
    $total[] = intval($d['total_total']);
};

foreach ($mes as $m) {
    $series[] = array(
            'type' =>'column', 'name' =>$m,
            'data' => $total
        );
};

I was able to achieve this:

Array(
[0] => Array
    (
        [type] => column
        [name] => 2017-06-01
        [data] => Array
            (
                [0] => 15826
                [1] => 16170
            )

    )

[1] => Array
    (
        [type] => column
        [name] => 2017-05-01
        [data] => Array
            (
                [0] => 15826
                [1] => 16170
            )

    )

)

As you can see the values are from total_total of both inner arrays.  How do I manage to split them like the example given above?

Body:
Loop and build your result, unsetting resumo_mes after you use it.  Then get the remaining values:

foreach($data as $key => $values) {
    $series[$key]['type'] = 'column';
    $series[$key]['name'] = $values['resumo_mes'];
    unset($values['resumo_mes']);
    $series[$key]['data'] = array_map('intval', array_values($values));
}

You could also filter the values with is_numeric or is_int depending on the type. is_numeric works for your sample data as the date is not "numeric":

foreach($data as $values) {
    $series[] = array('type' => 'column',
                      'name' => $values['resumo_mes'],
                      'data' => array_map('intval',
                                          array_values(
                                          array_filter($values,
                                                       'is_numeric'))));
}

Added array_map with intval.


问:
Changing the Value of an Attribute using javascript
Getting my script down to the bare bones, I have followed the example of the w3schools.com ( https://www.w3schools.com/js/js_htmldom_html.asp ) for: document.getElementById(id).attribute = new value. Their example:

```<code><!DOCTYPE html>
<html>
<body>

    <img id="myImage" src="smiley.gif">

<script>
    document.getElementById("myImage").src = "landscape.jpg";
</script>

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

Here is mine. I get no error messages on the Chrome console.

```<code><body>

    <img id = "indexPhoto" src =
        "newthaiimages/indexPhotos/indexPhoto_320.jpg"
         width="320" height="474" alt="hero sepia toned photo of Thai
         temple next to a river"/>

<script>

    document.getElementById("indexPhoto").scr =
        "newthaiimages/indexPhotos/indexPhoto_450.jpg";

</script>

</body>
</code>```

You can see the result at http://newthaimassage.com/index3.php . Here is the script not stripped down.

```<code><script>

    window.onload = function() {

       var w = window

   var x = w.innerWidth

switch(w.innerWidth){

    case x <= 320:

    break;

    case x <= 768:

        document.getElementById("indexPhoto").scr ="indexPhoto_450.jpg";

    break;

    case x <= 1024:

        document.getElementById("indexPhoto").scr ="indexPhoto_835.jpg";

    break;

    case x <= 1420:

        document.getElementById("indexPhoto").scr ="indexPhoto_1000.jpg";

    break;

    default:

        document.getElementById("indexPhoto").scr ="indexPhoto_1200.jpg";

}}

</script>
</code>```

Currently I am using CSS media queries to show images by window size, but using background images I can not use CSS animation, which is my ultimate goal here. Any help on this would be greatly appreciated.

答: You have a typo, change scr to src.

Body:
Getting my script down to the bare bones, I have followed the example of the w3schools.com ( https://www.w3schools.com/js/js_htmldom_html.asp ) for: document.getElementById(id).attribute = new value. Their example:

<!DOCTYPE html>

Here is mine. I get no error messages on the Chrome console.

You can see the result at http://newthaimassage.com/index3.php . Here is the script not stripped down.

Currently I am using CSS media queries to show images by window size, but using background images I can not use CSS animation, which is my ultimate goal here. Any help on this would be greatly appreciated.

Body: You have a typo, change scr to src.


问:
XSD code generation (C#) with xsd:includes
I have a problem with code generation using xsd.exe (the one provided with the .NET SDK) and also with Xsd2Code (http://xsd2code.codeplex.com/).

I have the following setup of XSD files:

Common.xsd

Summary.xsd

Detail.xsd

Common defines some types that are used in both Summary and Detail and are therefore both Summary and Detail include the line <xs:include schemaLocation="Common.xsd" />.

Now the problem with all XSD code generation tools I tried is that they only take a XSD file with a top level type (so Summary/Detail) and create classes in ONE namespace.

The problem with this is that if I use these tools I get 2 exact copies of every type in Common.xsd (Namespace.Summary.CommonType and Namespace.Detail.CommonType). When I want to use them in code I always have to convert between them (basically just copy all the values) with is quite a nuisance and leads to quite a lot of overhead and confusion.

Is there any XSD code generation tool that handles includes better (ie. puts included types into an own namespace and only generates them once)?

答:
The following method in Xsd2Code always returns true:

```<code>Xsd2Code.Library.Extensions.CodeExtension.ContainsTypeName(XmlSchema schema, CodeTypeDeclaration type)
</code>```

This prevents the exclusion of included xml schema items.

Body:
The following method in Xsd2Code always returns true:

Xsd2Code.Library.Extensions.CodeExtension.ContainsTypeName(XmlSchema schema, CodeTypeDeclaration type)

This prevents the exclusion of included xml schema items.


问:
Custom Deserializer in Json
I want to implement a custom Json mapping to the POJO below at class level.

```<code>@JsonDeserialize(using = DeviceDeserializer.class)
 public class Pojo {
   private String device;
   private String port;
   private String reservbleBw;
   *default constructor, getter and setters*
 }
</code>```

Below is my Json File

```<code>[
  {
   "Device":"ABCD",
   "ifces":[
     {
      "port":"ABCD:1/2/0",
      "reservableBW":"1000",
      "capabilites":[ "MPLS" ]
    },
    {
      "port":"ABCD:1/2/1",
      "reservableBW":"100",
      "capabilites":[ "ETHERNET" ]
    }
  ]
 }
]
</code>```

Now i only need to map the ports and reservableBw when 'capabilities' is 'ETHERNET'. I looked at few examples of custom deserializer but i do not know how to pass the value for JsonParser and DeserializationContext. I have problem understanding the below line.

```<code>  public Pojo deserialize(JsonParser jParser, DeserializationContext ctxt) throws IOException, JsonProcessingException
{
 // custom deserializer implementation
}
</code>```

答:
There are two methods to solve your issue:

Method 1: use a middle object to mapper: I have created a demo for your issue see this.

Create a middle object to mapper the original JSON

```<code>public class SfPojoDto {
    private String device;
    private List<Ifce> ifces;
}

public class Ifce {
    private String port;
    private String reservableBW;
    private String[] capabilites;
}
</code>```

Then use custom deserializer to mapper it firstly and convert to your target object.

```<code>public class DeviceDeserializer extends JsonDeserializer<SfPojo> {
    @Override
    public SfPojo deserialize(JsonParser p, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {
        // while (p.nextToken()!=null) {
        //     if (p.getCurrentToken()==)
        // }
        String temp = p.readValueAsTree().toString();
        ObjectMapper mapper = new ObjectMapper();
        SfPojoDto sfPojoDto = mapper.readValue(temp, SfPojoDto.class);
        SfPojo sfPojo = new SfPojo();
        sfPojo.setDevice(sfPojoDto.getDevice());
        List<Ifce> ifceList = sfPojoDto.getIfces();
        for (Ifce ifce : ifceList) {
            List<String> capabilities = Arrays.asList(ifce.getCapabilites());
            if (capabilities.contains("ETHERNET")) {
                sfPojo.setPort(ifce.getPort());
                sfPojo.setReservbleBw(ifce.getReservableBW());
                return sfPojo;
            }
        }
        return sfPojo;
    }
}
</code>```

Method 2: you can use the JsonParser to operate the JSON string, but this method is more complicated, you can ref this article:

Title: Custom Deserializer in Json

Body:
I want to implement a custom Json mapping to the POJO below at class level.

@JsonDeserialize(using = DeviceDeserializer.class)
 public class Pojo {
   private String device;
   private String port;
   private String reservbleBw;
   *default constructor, getter and setters*
 }

Below is my Json File

[
  {
   "Device":"ABCD",
   "ifces":[
     {
      "port":"ABCD:1/2/0",
      "reservableBW":"1000",
      "capabilites":[ "MPLS" ]
    },
    {
      "port":"ABCD:1/2/1",
      "reservableBW":"100",
      "capabilites":[ "ETHERNET" ]
    }
  ]
 }
]

Now i only need to map the ports and reservableBw when 'capabilities' is 'ETHERNET'. I looked at few examples of custom deserializer but i do not know how to pass the value for JsonParser and DeserializationContext. I have problem understanding the below line.

  public Pojo deserialize(JsonParser jParser, DeserializationContext ctxt) throws IOException, JsonProcessingException
{
 // custom deserializer implementation
}

Body:
There are two methods to solve your issue:

Method 1: use a middle object to mapper: I have created a demo for your issue see this.

Create a middle object to mapper the original JSON

public class SfPojoDto {
    private String device;
    private List<Ifce> ifces;
}

public class Ifce {
    private String port;
    private String reservableBW;
    private String[] capabilites;
}

Then use custom deserializer to mapper it firstly and convert to your target object.

public class DeviceDeserializer extends JsonDeserializer<SfPojo> {
    @Override
    public SfPojo deserialize(JsonParser p, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {
        // while (p.nextToken()!=null) {
        //     if (p.getCurrentToken()==)
        // }
        String temp = p.readValueAsTree().toString();
        ObjectMapper mapper = new ObjectMapper();
        SfPojoDto sfPojoDto = mapper.readValue(temp, SfPojoDto.class);
        SfPojo sfPojo = new SfPojo();
        sfPojo.setDevice(sfPojoDto.getDevice());
        List<Ifce> ifceList = sfPojoDto.getIfces();
        for (Ifce ifce : ifceList) {
            List<String> capabilities = Arrays.asList(ifce.getCapabilites());
            if (capabilities.contains("ETHERNET")) {
                sfPojo.setPort(ifce.getPort());
                sfPojo.setReservbleBw(ifce.getReservableBW());
                return sfPojo;
            }
        }
        return sfPojo;
    }
}

Method 2: you can use the JsonParser to operate the JSON string, but this method is more complicated, you can ref this article:


问:
Could someone help me with python network pragram?
Write down the chatting program code base with SSL/TLS and MultiThreading.

there's a 3 things to follow.

1.when client connected client's ID and IP or Network interface information, network information.

2.when client send message you have to follow this form([Client ID@connect IP] Message ) everytime.

3.you have to show and explain flowchart with client and server program.

it's my final exam of network programing. but it's too hard for me. i couldn't write down the code. so i have to submit the paper with nothing. i don't know how to do. someone can explain how to code the program?

my code is

server.py

```<code>import socket
import thread

print '---python chatting program---'

host = ''
port = 27332

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.bind((host, port))

s.listen(1)

users = []

def service(conn):

    try:

        name = conn.recv(1024)

        str = '*' + name + ' is entered.*'

        while conn:

            print str

            for each in users:

                each.send(str)

            str = name + ' : ' + conn.recv(1024)

    except:

        users.remove(conn)

        str = '*' + name + ' is out.*'

        print str

        if users:

            for each in users: each.send(str)

# thread.start_new_thread(service, ())

while 1:

    conn, addr = s.accept()

    global users

    users.append(conn)

    thread.start_new_thread(service, (conn, ))

    pass
</code>```

client.py

```<code>import socket
import thread

def handle(socket):

    while 1:

        data = socket.recv(1024)

        if not data:

            continue

        print data

    print 'handler is end.'

host = '127.0.0.1'
port = 27332

print 'enter your name.'

name = raw_input()

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.connect((host, port))

s.send(name)

thread.start_new_thread(handle, (s, ))

while 1:

    msg = raw_input()

    if not msg:

        continue

    s.send(msg)

s.close()

print '---chatting program is end---'
</code>```

答:
The official Python documentation provides an example of how to use Python's native socket package to implement a simple echo server and client. The example itself contains essentially no real functionality (since the goal here is to demo the use of socket): the server echoes back everything it receives from the client. However, you can use this code as a basis, adding the functionality as required. If you use Python 3, you'll find the documentation here, for Python 2 see here.

Now for the SSL/TLS part. Python has a native module ssl which is a TLS/SSL wrapper for socket objects; to cite the official Python documentation: the module "provides access to Transport Layer Security (often known as “Secure Sockets Layer”) encryption and peer authentication facilities for network sockets". If you use Python 3, you can find the documentation for the ssl module here, for Python 2 see here.

The ssl module provides the class ssl.SSLSocket, which is derived from the socket.socket type, and provides a socket-like wrapper that also encrypts and decrypts the data going over the socket with SSL. The official documentation also contains example code (snippets) you can use to implement your exercise (see e.g. here for how to do SSL/TLS using ssl module in Python 3).

Body:
Write down the chatting program code base with SSL/TLS and MultiThreading.

there's a 3 things to follow.

1.when client connected client's ID and IP or Network interface information, network information.

2.when client send message you have to follow this form([Client ID@connect IP] Message ) everytime.

3.you have to show and explain flowchart with client and server program.

it's my final exam of network programing. but it's too hard for me. i couldn't write down the code. so i have to submit the paper with nothing. i don't know how to do. someone can explain how to code the program?

my code is

server.py

import socket
import thread

print '---python chatting program---'

host = ''
port = 27332

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.bind((host, port))

s.listen(1)

users = []

def service(conn):

    try:

        name = conn.recv(1024)

        str = '*' + name + ' is entered.*'

        while conn:

            print str

            for each in users:

                each.send(str)

            str = name + ' : ' + conn.recv(1024)

    except:

        users.remove(conn)

        str = '*' + name + ' is out.*'

        print str

        if users:

            for each in users: each.send(str)

# thread.start_new_thread(service, ())

while 1:

    conn, addr = s.accept()

    global users

    users.append(conn)

    thread.start_new_thread(service, (conn, ))

    pass

client.py

import socket
import thread

def handle(socket):

    while 1:

        data = socket.recv(1024)

        if not data:

            continue

        print data

    print 'handler is end.'

host = '127.0.0.1'
port = 27332

print 'enter your name.'

name = raw_input()

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.connect((host, port))

s.send(name)

thread.start_new_thread(handle, (s, ))

while 1:

    msg = raw_input()

    if not msg:

        continue

    s.send(msg)

s.close()

print '---chatting program is end---'


问:
angular2- Observable getting data from list out of order
```<code>    for (let i = 0; i < this.data.VirtualHosts.length; i++) {
                // get the vh
                this.apiService.findVH(this.data.VirtualHosts[i])
                    // then add each vhost to data by concat and then convert to json
                    .subscribe((data) => {
                        this.data = data.docs[0]
                        this.jsonData = this.jsonData.concat(this.data)
                        //console.log("AFTER: " + this.jsonData[i]._id)
                        //console.log("Response for getVH: " + JSON.stringify(this.jsonData))

                    })
            }
</code>```

Here, I loop through a list of ID's of VirtualHosts and do a get call (findVH) on every single one of them. However, the get call seems to be calling each index out of order. How would I make it so that the get call returns a list of data in the order that it was given in the this.data.VirtualHosts list?

答:
I wouldn't recommend to use an observable inside a loop unless you really have to.. consider get all of your data within one api call / observable. If you are not unsubscribing from each one of the observables you will end up with a memory leak (unless you are using angular http).

Anyway, try wrap your code with a timeout to add it to the event queue:

```<code>for (let i = 0; i < this.data.VirtualHosts.length; i++) {
setTimeout(() => {
                // get the vh
                this.apiService.findVH(this.data.VirtualHosts[i])
                    // then add each vhost to data by concat and then convert to json
                    .subscribe((data) => {
                        this.data = data.docs[0]
                        this.jsonData = this.jsonData.concat(this.data)
                        //console.log("AFTER: " + this.jsonData[i]._id)
                        //console.log("Response for getVH: " + JSON.stringify(this.jsonData))

                    })
}, 0);
            }
</code>```

Currently the for loop ends before your service method is being exeucuted.

Body:
    for (let i = 0; i < this.data.VirtualHosts.length; i++) {
                // get the vh
                this.apiService.findVH(this.data.VirtualHosts[i])
                    // then add each vhost to data by concat and then convert to json
                    .subscribe((data) => {
                        this.data = data.docs[0]
                        this.jsonData = this.jsonData.concat(this.data)
                        //console.log("AFTER: " + this.jsonData[i]._id)
                        //console.log("Response for getVH: " + JSON.stringify(this.jsonData))

                    })
            }

Here, I loop through a list of ID's of VirtualHosts and do a get call (findVH) on every single one of them. However, the get call seems to be calling each index out of order. How would I make it so that the get call returns a list of data in the order that it was given in the this.data.VirtualHosts list?

Body:
I wouldn't recommend to use an observable inside a loop unless you really have to.. consider get all of your data within one api call / observable. If you are not unsubscribing from each one of the observables you will end up with a memory leak (unless you are using angular http).

Anyway, try wrap your code with a timeout to add it to the event queue:

for (let i = 0; i < this.data.VirtualHosts.length; i++) {
setTimeout(() => {
                // get the vh
                this.apiService.findVH(this.data.VirtualHosts[i])
                    // then add each vhost to data by concat and then convert to json
                    .subscribe((data) => {
                        this.data = data.docs[0]
                        this.jsonData = this.jsonData.concat(this.data)
                        //console.log("AFTER: " + this.jsonData[i]._id)
                        //console.log("Response for getVH: " + JSON.stringify(this.jsonData))

                    })
}, 0);
            }

Currently the for loop ends before your service method is being exeucuted.


问:
Array.indexOf(value) - not giving proper index number in GAS
In GAS,

```<code>Code.gs
function myFunction() {
  var sheet2 = SpreadsheetApp.getActivesheet();
  var firstset = sheet2.getRange('B1:B10').getValues();
  Logger.log(firstset)
  var found = firstset.indexOf('[re]')
  Logger.log(found)
}
</code>```

In Google Spreadsheet Range B1:B10,

```<code>B1  we
B2  we
B3  re
B4  ef
B5  ge
B6  er
B7  fe
B8  th
B9  rg
B10 pq
</code>```

The answer to the code should result 2, however, Log is showing -1 (not matched). Any help

Screenshot of Logger.log

答:
Here is what works for me.

This is a revised method, the original was not giving me the proper results.

```<code>Array.prototype.findIndex = function(search)
{
  if(search == "") return -1;
  for(var t = 0; t < this.length; t++)
  {
    if(this[t].search(search) >=0)
    {break}
  }
  return t-1;
}
</code>```

USAGE

```<code>var fruits = ["Banana", "Orange", "Apple", "Mango"];
var index = fruits.findIndex("Apple");
//"Apple" is located at position 2 in the array.
Logger.log("Index of 'Apple' is:  " + index);
</code>```

NOTE

When using this method to get the index of a sheets column by name, increment the index by 1 to use sheet.getRange(rowIndex, columnIndex).

```<code>var range = sheet.getRange(row, (index+1));
</code>```

Body:
In GAS,

Code.gs
function myFunction() {
  var sheet2 = SpreadsheetApp.getActivesheet();
  var firstset = sheet2.getRange('B1:B10').getValues();
  Logger.log(firstset)
  var found = firstset.indexOf('[re]')
  Logger.log(found)
}

In Google Spreadsheet Range B1:B10,

B1  we
B2  we
B3  re
B4  ef
B5  ge
B6  er
B7  fe
B8  th
B9  rg
B10 pq

The answer to the code should result 2, however, Log is showing -1 (not matched). Any help

Screenshot of Logger.log

Body:
Here is what works for me.

This is a revised method, the original was not giving me the proper results.

Array.prototype.findIndex = function(search)
{
  if(search == "") return -1;
  for(var t = 0; t < this.length; t++)
  {
    if(this[t].search(search) >=0)
    {break}
  }
  return t-1;
}

USAGE

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var index = fruits.findIndex("Apple");
//"Apple" is located at position 2 in the array.
Logger.log("Index of 'Apple' is:  " + index);

NOTE

When using this method to get the index of a sheets column by name, increment the index by 1 to use sheet.getRange(rowIndex, columnIndex).

var range = sheet.getRange(row, (index+1));


问:
jquery selector doesn't give all elements
In the next web page I want to select all
 elements with Jquery.
I want to select all the products that are inside

https://www.walmart.com/browse/home-improvement/air-quality/1072864_133032_1231459

I have tried:

```<code>$(".search-product-result ul li")
$("ul.search-result-gridview-items li")
</code>```

Also I have tried:

```<code>$("li")
$("ul li")
$("section li")
</code>```

to select all
 and none works.
All of them give one
 and not all.

Why this happens?

答:
If that is the actual HTML code that you've got in your site, the problem most likely is with the class declaration on the
.

You have it noted as
 when it should be
.

You're missing the opening double quotes before the class name.

Body:
In the next web page I want to select all
 elements with Jquery.
I want to select all the products that are inside

https://www.walmart.com/browse/home-improvement/air-quality/1072864_133032_1231459

I have tried:

$(".search-product-result ul li")
$("ul.search-result-gridview-items li")

Also I have tried:

$("li")
$("ul li")
$("section li")

to select all
 and none works.
All of them give one
 and not all.

Why this happens?

Body:
If that is the actual HTML code that you've got in your site, the problem most likely is with the class declaration on the <ul>.

You have it noted as <ul class=search-result-gridview-items"> when it should be <ul class="search-result-gridview-items">.

You're missing the opening double quotes before the class name.


问:
Kendoui Grid Custom Aggregate Group Header
I have a purchase grid with expiration date and I need to sum only the valid values, that is, those that have not expired. The image shows what is displayed today (in red) and how it should look (in blue). Today is 2017-07-07.

答:
As far I know there is no stadard kendo way to build conditional sum aggregate.
However - you can use footer template to obtain similiar functionality.

Example:

Column definition part:

```<code>columns: [
          "ColumnTitle",
          { field: "Field", title: "Title", footerTemplate: conditionalSum },
        ]
</code>```

Function:

```<code>function conditionalSum() {
        var data = yourGrid.dataSource.data();
        var sum = 0;
        for (var idx = 0; idx < data.length; idx++) {
          //do your calculations
        }

        return kendo.toString(sum);
      }
</code>```

Body:
As far I know there is no stadard kendo way to build conditional sum aggregate.
However - you can use footer template to obtain similiar functionality.

Example:

Column definition part:

columns: [
          "ColumnTitle",
          { field: "Field", title: "Title", footerTemplate: conditionalSum },
        ]

Function:

function conditionalSum() {
        var data = yourGrid.dataSource.data();
        var sum = 0;
        for (var idx = 0; idx < data.length; idx++) {
          //do your calculations
        }

        return kendo.toString(sum);
      }


问:
Selecting the option passed from the controller
I'm having trouble with the selection of the right value in a 'select' when the options are String. I can't find the solution in the forums.

I pass 'kind' in the controller and I can see that the values are fine but only the Integer fields are selected properly in the 'select'. The ones with String always show the first value and not the one pass in 'kind'.

I added the code I thought it could help
Can anyone help?

My HTML code. The form contains many 'select' but I left two, the first one works but the second one always show the first option:

```<code> <form  role="form" th:action="@{/kind/update}"  th:object="${kind}" method="post">
    <div class="form-group col-md-4">
        <label for="replicates">No. of Replicates</label>
        <select id="replicates" class="form-control" style="width: 70%;" th:field="${kind.replicates}">
            <option th:each="rep: ${replicatesnumber}" th:value="${rep}" th:text="${rep}"> </option>
       </select>
   </div>
   <div class="form-group col-md-3">
       <label for="substrate">Substrate</label>
       <select id="substrate" class="form-control" th:field="${kind.substrate}">
           <option th:each="substrate: ${substrates}" th:value="${substrate}" th:text="${substrate}"> </option>
       </select>
   </div>
   <div class="box-footer">
    <button type="submit" class="btn btn-primary">Save</button>
    <a class="btn btn-primary" th:href="@{/division/edit/}+${kind.division.id}" role="button">Cancel</a>
    </div>
</form>
</code>```

The controller look like this:

```<code>@Controller
@RequestMapping("/kind")
public class KindController {

    @Autowired
    private KindService kindService;

    @ModelAttribute("replicatesnumber")
    public int[] getReplicates() {
        int[] reps = new int[3];
        reps[0] = 2;
        reps[1] = 4;
        reps[2] = 8;
        return reps;
    }

    @ModelAttribute("substrates")
    public List<String> getSubstrates() {
        return Arrays.asList("BP", "PP", "TP", "OGM", "Sand");
    }

   @GetMapping(value= "/edit/{kindId}")
   public String viewDivision(@PathVariable Integer kindId, Model model){
       Kind kind= kindService.findById(kindId);
       model.addAttribute("kind",kind);
       return  "kind_edit";
   }
</code>```

and the entity:

```<code>@Entity
@Table(name = "kind", schema = "ostscourses")
public class Kind implements java.io.Serializable {

private Integer id;
private Division division;
private String name;
private Integer germinationDays;
private Integer firstCount;
private Integer replicates;
private Boolean dark;
private Integer chill;
private String temperature;
private String substrate;
private Integer noSeeds;
private List<Sample> samples;

public Kind() {
}

public Kind(Integer id, Division division) {
    this.id = id;
    this.division = division;
}

public Kind(Integer id, Division division, String name, Integer germinationDays, Integer firstCount, Integer replicates, Boolean dark, Integer chill, String temperature, String substrate, Integer noSeeds, List<Sample> samples) {
    this.id = id;
    this.division = division;
    this.name = name;
    this.germinationDays = germinationDays;
    this.firstCount = firstCount;
    this.replicates = replicates;
    this.dark = dark;
    this.chill = chill;
    this.temperature = temperature;
    this.substrate = substrate;
    this.noSeeds = noSeeds;
    this.samples = samples;
}

@Id
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
    return this.id;
}

public void setId(Integer id) {
    this.id = id;
}

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "division_id", nullable = false)
@JsonIgnore
public Division getDivision() {
    return this.division;
}

public void setDivision(Division division) {
    this.division = division;
}

@Column(name = "name", length = 25)
public String getName() {
    return this.name;
}

public void setName(String name) {
    this.name = name;
}

@Column(name = "germination_days")
public Integer getGerminationDays() {
    return this.germinationDays;
}

public void setGerminationDays(Integer germinationDays) {
    this.germinationDays = germinationDays;
}

@Column(name = "first_count")
public Integer getFirstCount() {
    return this.firstCount;
}

public void setFirstCount(Integer firstCount) {
    this.firstCount = firstCount;
}

@Column(name = "replicates")
public Integer getReplicates() {
    return this.replicates;
}

public void setReplicates(Integer replicates) {
    this.replicates = replicates;
}

@Column(name = "dark")
public Boolean getDark() {
    return this.dark;
}

public void setDark(Boolean dark) {
    this.dark = dark;
}

@Column(name = "chill")
public Integer getChill() {
    return this.chill;
}

public void setChill(Integer chill) {
    this.chill = chill;
}

@Column(name = "temperature", length = 10)
public String getTemperature() {
    return this.temperature;
}

public void setTemperature(String temperature) {
    this.temperature = temperature;
}

@Column(name = "substrate", length = 5)
public String getSubstrate() {
    return this.substrate;
}

public void setSubstrate(String substrate) {
    this.substrate = substrate;
}

@Column(name = "no_seeds")
public Integer getNoSeeds() {
    return this.noSeeds;
}

public void setNoSeeds(Integer noSeeds) {
    this.noSeeds = noSeeds;
}

@OneToMany(fetch = FetchType.LAZY, mappedBy = "kind")
@JsonIgnore
public List<Sample> getSamples() {
    return this.samples;
}

public void setSamples(List<Sample> samples) {
    this.samples = samples;
}

@Override
public int hashCode() {
    int hash = 3;
    hash = 47 * hash + Objects.hashCode(this.id);
    return hash;
}

@Override
public boolean equals(Object obj) {
    if (this == obj) {
        return true;
    }
    if (obj == null) {
        return false;
    }
    if (getClass() != obj.getClass()) {
        return false;
    }
    final Kind other = (Kind) obj;
    if (!Objects.equals(this.id, other.id)) {
        return false;
    }
    return true;
}

@Override
public String toString() {
    return "Kind{" + "id=" + id + ", name=" + name + ", germinationDays=" + germinationDays + ", firstCount=" + firstCount + ", replicates=" + replicates + ", dark=" + dark + ", chill=" + chill + ", temperature=" + temperature + ", substrate=" + substrate + ", noSeeds=" + noSeeds + '}';
}
</code>```

}

答:
Well, I just found a solution creating enum with the values I need in the select

```<code>public enum SubstrateType{
    BP,
    PP,
    TP,
    OGM,
    Sand;
}
</code>```

In my controller:

```<code>@ModelAttribute("substrates")
public SubstrateType[] getSubstrates() {
    return SubstrateType.values();
}
</code>```

I know it should work without enum as I have seen this before. Anyway I think is a good practice having enum.

Body:
I'm having trouble with the selection of the right value in a 'select' when the options are String. I can't find the solution in the forums.

I pass 'kind' in the controller and I can see that the values are fine but only the Integer fields are selected properly in the 'select'. The ones with String always show the first value and not the one pass in 'kind'.

I added the code I thought it could help
Can anyone help?

My HTML code. The form contains many 'select' but I left two, the first one works but the second one always show the first option:

 <form  role="form" th:action="@{/kind/update}"  th:object="${kind}" method="post">

        No. of Replicates
        <select id="replicates" class="form-control" style="width: 70%;" th:field="${kind.replicates}">
            <option th:each="rep: ${replicatesnumber}" th:value="${rep}" th:text="${rep}"> </option>
       </select>

       Substrate
       <select id="substrate" class="form-control" th:field="${kind.substrate}">
           <option th:each="substrate: ${substrates}" th:value="${substrate}" th:text="${substrate}"> </option>
       </select>

    <button type="submit" class="btn btn-primary">Save</button>
    Cancel

</form>

The controller look like this:

@Controller
@RequestMapping("/kind")
public class KindController {

    @Autowired
    private KindService kindService;

    @ModelAttribute("replicatesnumber")
    public int[] getReplicates() {
        int[] reps = new int[3];
        reps[0] = 2;
        reps[1] = 4;
        reps[2] = 8;
        return reps;
    }

    @ModelAttribute("substrates")
    public List<String> getSubstrates() {
        return Arrays.asList("BP", "PP", "TP", "OGM", "Sand");
    }

   @GetMapping(value= "/edit/{kindId}")
   public String viewDivision(@PathVariable Integer kindId, Model model){
       Kind kind= kindService.findById(kindId);
       model.addAttribute("kind",kind);
       return  "kind_edit";
   }

and the entity:

@Entity
@Table(name = "kind", schema = "ostscourses")
public class Kind implements java.io.Serializable {

private Integer id;
private Division division;
private String name;
private Integer germinationDays;
private Integer firstCount;
private Integer replicates;
private Boolean dark;
private Integer chill;
private String temperature;
private String substrate;
private Integer noSeeds;
private List<Sample> samples;

public Kind() {
}

public Kind(Integer id, Division division) {
    this.id = id;
    this.division = division;
}

public Kind(Integer id, Division division, String name, Integer germinationDays, Integer firstCount, Integer replicates, Boolean dark, Integer chill, String temperature, String substrate, Integer noSeeds, List<Sample> samples) {
    this.id = id;
    this.division = division;
    this.name = name;
    this.germinationDays = germinationDays;
    this.firstCount = firstCount;
    this.replicates = replicates;
    this.dark = dark;
    this.chill = chill;
    this.temperature = temperature;
    this.substrate = substrate;
    this.noSeeds = noSeeds;
    this.samples = samples;
}

@Id
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
    return this.id;
}

public void setId(Integer id) {
    this.id = id;
}

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "division_id", nullable = false)
@JsonIgnore
public Division getDivision() {
    return this.division;
}

public void setDivision(Division division) {
    this.division = division;
}

@Column(name = "name", length = 25)
public String getName() {
    return this.name;
}

public void setName(String name) {
    this.name = name;
}

@Column(name = "germination_days")
public Integer getGerminationDays() {
    return this.germinationDays;
}

public void setGerminationDays(Integer germinationDays) {
    this.germinationDays = germinationDays;
}

@Column(name = "first_count")
public Integer getFirstCount() {
    return this.firstCount;
}

public void setFirstCount(Integer firstCount) {
    this.firstCount = firstCount;
}

@Column(name = "replicates")
public Integer getReplicates() {
    return this.replicates;
}

public void setReplicates(Integer replicates) {
    this.replicates = replicates;
}

@Column(name = "dark")
public Boolean getDark() {
    return this.dark;
}

public void setDark(Boolean dark) {
    this.dark = dark;
}

@Column(name = "chill")
public Integer getChill() {
    return this.chill;
}

public void setChill(Integer chill) {
    this.chill = chill;
}

@Column(name = "temperature", length = 10)
public String getTemperature() {
    return this.temperature;
}

public void setTemperature(String temperature) {
    this.temperature = temperature;
}

@Column(name = "substrate", length = 5)
public String getSubstrate() {
    return this.substrate;
}

public void setSubstrate(String substrate) {
    this.substrate = substrate;
}

@Column(name = "no_seeds")
public Integer getNoSeeds() {
    return this.noSeeds;
}

public void setNoSeeds(Integer noSeeds) {
    this.noSeeds = noSeeds;
}

@OneToMany(fetch = FetchType.LAZY, mappedBy = "kind")
@JsonIgnore
public List<Sample> getSamples() {
    return this.samples;
}

public void setSamples(List<Sample> samples) {
    this.samples = samples;
}

@Override
public int hashCode() {
    int hash = 3;
    hash = 47 * hash + Objects.hashCode(this.id);
    return hash;
}

@Override
public boolean equals(Object obj) {
    if (this == obj) {
        return true;
    }
    if (obj == null) {
        return false;
    }
    if (getClass() != obj.getClass()) {
        return false;
    }
    final Kind other = (Kind) obj;
    if (!Objects.equals(this.id, other.id)) {
        return false;
    }
    return true;
}

@Override
public String toString() {
    return "Kind{" + "id=" + id + ", name=" + name + ", germinationDays=" + germinationDays + ", firstCount=" + firstCount + ", replicates=" + replicates + ", dark=" + dark + ", chill=" + chill + ", temperature=" + temperature + ", substrate=" + substrate + ", noSeeds=" + noSeeds + '}';
}

}

Body:
Well, I just found a solution creating enum with the values I need in the select

public enum SubstrateType{
    BP,
    PP,
    TP,
    OGM,
    Sand;
}

In my controller:

@ModelAttribute("substrates")
public SubstrateType[] getSubstrates() {
    return SubstrateType.values();
}

I know it should work without enum as I have seen this before. Anyway I think is a good practice having enum.


问:
Intl.DateTimeFormat produces wrong format
In current Chrome, Firefox and Safari Intl.DateTimeFormat for the locale it-CH (italian part of Switzerland) is wrong:

```<code>new window.Intl.DateTimeFormat('it-CH').format(new Date()) // -> "6/7/2017"
new window.Intl.DateTimeFormat('fr-CH').format(new Date()) // -> "06.07.2017"
new window.Intl.DateTimeFormat('de-CH').format(new Date()) // -> "06.07.2017"
</code>```

The output of the first line is wrong. In all parts of Switzerland the format should be "dd.mm.yyyy"

Interestingly IE11 & Edge produce the correct output for the above snippet.

What is the best way to fix/patch/override the faulty implementation of window.Intl in given browsers?

答:
Not sure about best but the easiest should be something like this:

```<code>var nativeDateTimeFormat = window.Intl.DateTimeFormat;
window.Intl.DateTimeFormat = function(locale) {
  var native = nativeDateTimeFormat(locale);
  if (locale === 'it-CH') {
    native.format = function() {
      return nativeDateTimeFormat('fr-CH').format();
    }
  }
  return native;
}
</code>```

This solution uses the fact that fr-CH has the correct format that it-CH should have.

Body:
In current Chrome, Firefox and Safari Intl.DateTimeFormat for the locale it-CH (italian part of Switzerland) is wrong:

new window.Intl.DateTimeFormat('it-CH').format(new Date()) // -> "6/7/2017"
new window.Intl.DateTimeFormat('fr-CH').format(new Date()) // -> "06.07.2017"
new window.Intl.DateTimeFormat('de-CH').format(new Date()) // -> "06.07.2017"

The output of the first line is wrong. In all parts of Switzerland the format should be "dd.mm.yyyy"

Interestingly IE11 & Edge produce the correct output for the above snippet.

What is the best way to fix/patch/override the faulty implementation of window.Intl in given browsers?

Body:
Not sure about best but the easiest should be something like this:

var nativeDateTimeFormat = window.Intl.DateTimeFormat;
window.Intl.DateTimeFormat = function(locale) {
  var native = nativeDateTimeFormat(locale);
  if (locale === 'it-CH') {
    native.format = function() {
      return nativeDateTimeFormat('fr-CH').format();
    }
  }
  return native;
}

This solution uses the fact that fr-CH has the correct format that it-CH should have.


问:
ADAL v3: How to authenticate using UserPasswordCredential?
ADAL v3 has the UserPasswordCredential class, but I cannot find a working implementation. There's no AcquireToken overload which accepts a UserPasswordCredential or UserCredential type. What is the correct way of performing the username&password flow in ADAL v3? This particular piece of code is using full .Net 4.5.</p>

答:
To elaborate on the second part of the accepted answer, here is an implementation to make the POST request:

```<code>    From SettingHelper: public static string GetAuthorityEndpoint(string azuretenantId) => $"https://login.microsoftonline.com/{azuretenantId}/";

    private static async Task<OAuthResult> AuthenticateAsync(string resource = "https://yourAzureADProtectedResource.url/")
    {
        var oauthEndpoint = new Uri(new Uri(SettingsHelper.GetAuthorityEndpoint("your AAD Tenent ID")), "oauth2/token");

        using (var client = new HttpClient())
        {
            var result = await client.PostAsync(oauthEndpoint, new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("resource", resource),
                new KeyValuePair<string, string>("client_id", "your AAD App Id"),
                new KeyValuePair<string, string>("grant_type", "password"),
                new KeyValuePair<string, string>("username", "your.user@yourtenent.url"),
                new KeyValuePair<string, string>("password", "your password"),
                new KeyValuePair<string, string>("scope", "openid"),
                new KeyValuePair<string, string>("client_secret", "an access key for your AAD App"),
            }));

            var content = await result.Content.ReadAsStringAsync();
            var authResult = JsonConvert.DeserializeObject<OAuthResult>(content);
            return authResult;
        }
    }

    class OAuthResult
    {
        public string Token_Type { get; set; }
        public string Scope { get; set; }
        public int Expires_In { get; set; }
        public int Ext_Expires_In { get; set; }
        public int Expires_On { get; set; }
        public int Not_Before { get; set; }
        public Uri Resource { get; set; }
        public string Access_Token { get; set; }
    }
</code>```

You can then go on to use the Auth result like this:

```<code>    private async Task<HttpClient> GetHttpClientWithAzureADAuthentication()
    {
        OAuthResult authResult;
        try
        {
            authResult = await AuthenticateAsync();
            var httpClient = GetHttpClient();
            httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {authResult.Access_Token}");

            return httpClient;
        }
        catch (Exception e)
        {
            Debug.WriteLine(e);
            throw;
        }
    }
</code>```

Body:
To elaborate on the second part of the accepted answer, here is an implementation to make the POST request:

    From SettingHelper: public static string GetAuthorityEndpoint(string azuretenantId) => $"https://login.microsoftonline.com/{azuretenantId}/";

    private static async Task<OAuthResult> AuthenticateAsync(string resource = "https://yourAzureADProtectedResource.url/")
    {
        var oauthEndpoint = new Uri(new Uri(SettingsHelper.GetAuthorityEndpoint("your AAD Tenent ID")), "oauth2/token");

        using (var client = new HttpClient())
        {
            var result = await client.PostAsync(oauthEndpoint, new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("resource", resource),
                new KeyValuePair<string, string>("client_id", "your AAD App Id"),
                new KeyValuePair<string, string>("grant_type", "password"),
                new KeyValuePair<string, string>("username", "your.user@yourtenent.url"),
                new KeyValuePair<string, string>("password", "your password"),
                new KeyValuePair<string, string>("scope", "openid"),
                new KeyValuePair<string, string>("client_secret", "an access key for your AAD App"),
            }));

            var content = await result.Content.ReadAsStringAsync();
            var authResult = JsonConvert.DeserializeObject<OAuthResult>(content);
            return authResult;
        }
    }

    class OAuthResult
    {
        public string Token_Type { get; set; }
        public string Scope { get; set; }
        public int Expires_In { get; set; }
        public int Ext_Expires_In { get; set; }
        public int Expires_On { get; set; }
        public int Not_Before { get; set; }
        public Uri Resource { get; set; }
        public string Access_Token { get; set; }
    }

You can then go on to use the Auth result like this:

    private async Task<HttpClient> GetHttpClientWithAzureADAuthentication()
    {
        OAuthResult authResult;
        try
        {
            authResult = await AuthenticateAsync();
            var httpClient = GetHttpClient();
            httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {authResult.Access_Token}");

            return httpClient;
        }
        catch (Exception e)
        {
            Debug.WriteLine(e);
            throw;
        }
    }


问:
How to use transaction in oracle database from java back end?
I have to insert some information to my oracle database. Some of them are complex (array of arrays), so I can't pass them to a PL/SQL function. All the data can't be inserted using one query, and I have to insert data to multiple tables too. But if insertion fails once for a table, the whole insertion process should be rolled back. So I need to use transaction.

I am using java code and PreparedStatement, ResultSet, CallableStatement and other related things to perform database operations from my java back end. How can I define and use transactions from this java back end? Basically I am using Spring MVC.

N.B. No Hibernate related solution please.

答:
Use Connection.setAutoComit(false) just after obtaining the Connection instance.

This will make your connection a non auto-commit transaction.

See: http://docs.oracle.com/javase/8/docs/api/java/sql/Connection.html#setAutoCommit-boolean-


问:
Comparing elements in a list with its neighbours
I have a list of 29400 values in Python and I'm trying to check if each element of the list is larger than both the 2000 neighbors to its left and the 2000 neighbors to its right. If the element is larger than its 4000 neighbors, I want to retrieve the index of the element. If there aren't 2000 neighbors to the right I just want to compare it with future elements until I reach the end of the list, and vice versa if there aren't 2000 values to the left.

```<code>def find_peaks(t):
prev = []
future = []
peak_index = []
for i in range(len(t)-2000): # compare element with previous values
    for j in range(1,2001):
        if t[i]<t[i+j]:
            prev.append(False)
            break
        if j==2000:
            if t[i]<t[i+j]:
                prev.append(False)
                break
            prev.append(True)

for i in range(1999,len(t)-1): # compare element with future values
    for j in range(1,2001):
        if t[i]<t[i-j]:
            future.append(False)
            break
        if j==2000:
            if t[i]<t[i-j]:
                future.append(False)
                break
            future.append(True)
future = future[::-1] # reverse list
for i in range(0,len(prev)-1):
    if prev[i] == True:
        if prev[i] == True:
            peak_index.append(i)
</code>```

Does anyone know of any better ways to go about this? I was having trouble comparing elements near the end and the beginning of the list- If there aren't 2000 elements left in the list for me to compare with, then the list wraps around to the beginning of the list, which isn't something I want.

答:
My solution does not involve any language powerful inbuilt methods. Its just plain logic to find the target peaks. Basically I am iterating over each element and then in inner loop checking if its previous or future neighbors are present and less than the current element. I am initializing a isPeak variable to True for if none of the neighbors in both direction are greater than the current element, which indicates your current element is peak element. After that just getting the index of target element.

```<code>def find_peaks(t , neighbour_length=2000):
    peak_index = []
    for i in range(len(t)): # compare element with previous values
        isPeak = True #intialize to true
        for j in range(i, neighbour_length + i):

            # Check if previous index value is present
            if (2*i-j-1 >= 0):
                # Check if next neighbour is less or break
                if(t[i] <= t[2*i-j-1]):
                    isPeak = False
                    break
            # Check if Future element is present
            if (j+i+1 < len(t)):
                #Check if next future neighbour ir less or break
                if(t[i] <= t[i+j+1]):
                    isPeak = False
                    break

        if(isPeak):
            peak_index.append(i)

    return peak_index
</code>```

Hope it Helps!

Body:
I have a list of 29400 values in Python and I'm trying to check if each element of the list is larger than both the 2000 neighbors to its left and the 2000 neighbors to its right. If the element is larger than its 4000 neighbors, I want to retrieve the index of the element. If there aren't 2000 neighbors to the right I just want to compare it with future elements until I reach the end of the list, and vice versa if there aren't 2000 values to the left.

def find_peaks(t):
prev = []
future = []
peak_index = []
for i in range(len(t)-2000): # compare element with previous values
    for j in range(1,2001):
        if t[i]<t[i+j]:
            prev.append(False)
            break
        if j==2000:
            if t[i]<t[i+j]:
                prev.append(False)
                break
            prev.append(True)

for i in range(1999,len(t)-1): # compare element with future values
    for j in range(1,2001):
        if t[i]<t[i-j]:
            future.append(False)
            break
        if j==2000:
            if t[i]<t[i-j]:
                future.append(False)
                break
            future.append(True)
future = future[::-1] # reverse list
for i in range(0,len(prev)-1):
    if prev[i] == True:
        if prev[i] == True:
            peak_index.append(i)

Does anyone know of any better ways to go about this? I was having trouble comparing elements near the end and the beginning of the list- If there aren't 2000 elements left in the list for me to compare with, then the list wraps around to the beginning of the list, which isn't something I want.

Body:
My solution does not involve any language powerful inbuilt methods. Its just plain logic to find the target peaks. Basically I am iterating over each element and then in inner loop checking if its previous or future neighbors are present and less than the current element. I am initializing a isPeak variable to True for if none of the neighbors in both direction are greater than the current element, which indicates your current element is peak element. After that just getting the index of target element.

def find_peaks(t , neighbour_length=2000):
    peak_index = []
    for i in range(len(t)): # compare element with previous values
        isPeak = True #intialize to true
        for j in range(i, neighbour_length + i):

            # Check if previous index value is present
            if (2*i-j-1 >= 0):
                # Check if next neighbour is less or break
                if(t[i] <= t[2*i-j-1]):
                    isPeak = False
                    break
            # Check if Future element is present
            if (j+i+1 < len(t)):
                #Check if next future neighbour ir less or break
                if(t[i] <= t[i+j+1]):
                    isPeak = False
                    break

        if(isPeak):
            peak_index.append(i)

    return peak_index

Hope it Helps!


问:
Looking for ways to simplify my code
I'm having trouble adding another function in that macro I used to activate or deactivate columns in a Excel Workbook we are using at work. I'm getting the Out of stack space error when running it just adding one of the following function.

Mostly, I've used an If( ;1;0) to manage the activation part and an If(;TRUE;FALSE) for the locked/unlocked part. The function I want to had is based on the same idea using a verification code to Clearcontents of a cell and locked it. If the verification code is false, then, I want the cell to be unlocked so the user can write the value. Here is the code line I want to had times 15 as already done for the locked, unlocked function.

```<code>If Range("AS16") = "Vrai" Then
Range("AA16").ClearContents
Range("AA16").Locked = True
Else:
Range("AA16").Locked = False
End If
</code>```

Here is the code I'm using right now.

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
ActiveSheet.Unprotect ("Francis")
Dim Cell As Range
Set Cell = ActiveCell
Application.ScreenUpdating = False

For Each cellule In Range("S50:X50")
If cellule.Value = "1" Then cellule.EntireColumn.Hidden = False
Next cellule

For Each cellule In Range("S50:X50")
If cellule.Value = "0" Then cellule.EntireColumn.Hidden = True
Next cellule

For Each cellule In Range("I50:J50")
If cellule.Value = "1" Then cellule.EntireColumn.Hidden = False
Next cellule

For Each cellule In Range("I50:J50")
If cellule.Value = "0" Then cellule.EntireColumn.Hidden = True
Next cellule

If Range("AR16") = "Vrai" Then
Range("K16").Locked = False
Range("O16").Locked = False
Else:
Range("K16").Locked = True
Range("O16").Locked = True
End If

If Range("AR18") = "Vrai" Then
Range("K18").Locked = False
Range("O18").Locked = False
Else:
Range("K18").Locked = True
Range("O18").Locked = True
End If

If Range("AR20") = "Vrai" Then
Range("K20").Locked = False
Range("O20").Locked = False
Else:
Range("K20").Locked = True
Range("O20").Locked = True
End If

If Range("AR22") = "Vrai" Then
Range("K22").Locked = False
Range("O22").Locked = False
Else:
Range("K22").Locked = True
Range("O22").Locked = True
End If

If Range("AR24") = "Vrai" Then
Range("K24").Locked = False
Range("O24").Locked = False
Else:
Range("K24").Locked = True
Range("O24").Locked = True
End If

If Range("AR26") = "Vrai" Then
Range("K26").Locked = False
Range("O26").Locked = False
Else:
Range("K26").Locked = True
Range("O26").Locked = True
End If

If Range("AR28") = "Vrai" Then
Range("K28").Locked = False
Range("O28").Locked = False
Else:
Range("K28").Locked = True
Range("O28").Locked = True
End If

If Range("AR30") = "Vrai" Then
Range("K30").Locked = False
Range("O30").Locked = False
Else:
Range("K30").Locked = True
Range("O30").Locked = True
End If

If Range("AR32") = "Vrai" Then
Range("K32").Locked = False
Range("O32").Locked = False
Else:
Range("K32").Locked = True
Range("O32").Locked = True
End If

If Range("AR34") = "Vrai" Then
Range("K34").Locked = False
Range("O34").Locked = False
Else:
Range("K34").Locked = True
Range("O34").Locked = True
End If

If Range("AR36") = "Vrai" Then
Range("K36").Locked = False
Range("O36").Locked = False
Else:
Range("K36").Locked = True
Range("O36").Locked = True
End If

If Range("AR38") = "Vrai" Then
Range("K38").Locked = False
Range("O38").Locked = False
Else:
Range("K38").Locked = True
Range("O38").Locked = True
End If

If Range("AR40") = "Vrai" Then
Range("K40").Locked = False
Range("O40").Locked = False
Else:
Range("K40").Locked = True
Range("O40").Locked = True
End If

If Range("AR42") = "Vrai" Then
Range("K42").Locked = False
Range("O42").Locked = False
Else:
Range("K42").Locked = True
Range("O42").Locked = True
End If

If Range("AR44") = "Vrai" Then
Range("K44").Locked = False
Range("O44").Locked = False
Else:
Range("K44").Locked = True
Range("O44").Locked = True
End If

Application.ScreenUpdating = True
Application.Goto Cell

'ActiveSheet.Protect Password:="Francis"
End Sub
</code>```

Thanks a lot for your help.

Have a nice day!

答:
This section can be simplified:

```<code>For Each cellule In Range("S50:X50")
If cellule.Value = "1" Then cellule.EntireColumn.Hidden = False
Next cellule

For Each cellule In Range("S50:X50")
If cellule.Value = "0" Then cellule.EntireColumn.Hidden = True
Next cellule

For Each cellule In Range("I50:J50")
If cellule.Value = "1" Then cellule.EntireColumn.Hidden = False
Next cellule

For Each cellule In Range("I50:J50")
If cellule.Value = "0" Then cellule.EntireColumn.Hidden = True
Next cellule
</code>```

To the following (however, note that this will unhide any non-zero values).

```<code>For Each cellule in Range("S50:X50")
    cellule.EntireColumn.Hidden = (cellule.Value = "0")
Next
For Each cellule in Range("I50:J50")
    cellule.EntireColumn.Hidden = (cellule.Value = "0")
Next
</code>```

And this section:

```<code>If Range("AR16") = "Vrai" Then
Range("K16").Locked = False
Range("O16").Locked = False
Else:
Range("K16").Locked = True
Range("O16").Locked = True
End If

If Range("AR18") = "Vrai" Then
Range("K18").Locked = False
Range("O18").Locked = False
Else:
Range("K18").Locked = True
Range("O18").Locked = True
End If

....
</code>```

Can be simplified using a loop over Range("AR16:AR44")

```<code>For Each cellule in Range("AR16:AR44") Step 2
    cellule.Offset(,-33).Locked = (cellule.Value = "Vrai")
    cellule.Offset(,-29).Locked = (cellule.Value = "Vrai")
Next
</code>```

Title: Looking for ways to simplify my code

Body:
I'm having trouble adding another function in that macro I used to activate or deactivate columns in a Excel Workbook we are using at work. I'm getting the Out of stack space error when running it just adding one of the following function.

Mostly, I've used an If( ;1;0) to manage the activation part and an If(;TRUE;FALSE) for the locked/unlocked part. The function I want to had is based on the same idea using a verification code to Clearcontents of a cell and locked it. If the verification code is false, then, I want the cell to be unlocked so the user can write the value. Here is the code line I want to had times 15 as already done for the locked, unlocked function.

If Range("AS16") = "Vrai" Then
Range("AA16").ClearContents
Range("AA16").Locked = True
Else:
Range("AA16").Locked = False
End If

Here is the code I'm using right now.

Private Sub Worksheet_Change(ByVal Target As Range)
ActiveSheet.Unprotect ("Francis")
Dim Cell As Range
Set Cell = ActiveCell
Application.ScreenUpdating = False

For Each cellule In Range("S50:X50")
If cellule.Value = "1" Then cellule.EntireColumn.Hidden = False
Next cellule

For Each cellule In Range("S50:X50")
If cellule.Value = "0" Then cellule.EntireColumn.Hidden = True
Next cellule

For Each cellule In Range("I50:J50")
If cellule.Value = "1" Then cellule.EntireColumn.Hidden = False
Next cellule

For Each cellule In Range("I50:J50")
If cellule.Value = "0" Then cellule.EntireColumn.Hidden = True
Next cellule

If Range("AR16") = "Vrai" Then
Range("K16").Locked = False
Range("O16").Locked = False
Else:
Range("K16").Locked = True
Range("O16").Locked = True
End If

If Range("AR18") = "Vrai" Then
Range("K18").Locked = False
Range("O18").Locked = False
Else:
Range("K18").Locked = True
Range("O18").Locked = True
End If

If Range("AR20") = "Vrai" Then
Range("K20").Locked = False
Range("O20").Locked = False
Else:
Range("K20").Locked = True
Range("O20").Locked = True
End If

If Range("AR22") = "Vrai" Then
Range("K22").Locked = False
Range("O22").Locked = False
Else:
Range("K22").Locked = True
Range("O22").Locked = True
End If

If Range("AR24") = "Vrai" Then
Range("K24").Locked = False
Range("O24").Locked = False
Else:
Range("K24").Locked = True
Range("O24").Locked = True
End If

If Range("AR26") = "Vrai" Then
Range("K26").Locked = False
Range("O26").Locked = False
Else:
Range("K26").Locked = True
Range("O26").Locked = True
End If

If Range("AR28") = "Vrai" Then
Range("K28").Locked = False
Range("O28").Locked = False
Else:
Range("K28").Locked = True
Range("O28").Locked = True
End If

If Range("AR30") = "Vrai" Then
Range("K30").Locked = False
Range("O30").Locked = False
Else:
Range("K30").Locked = True
Range("O30").Locked = True
End If

If Range("AR32") = "Vrai" Then
Range("K32").Locked = False
Range("O32").Locked = False
Else:
Range("K32").Locked = True
Range("O32").Locked = True
End If

If Range("AR34") = "Vrai" Then
Range("K34").Locked = False
Range("O34").Locked = False
Else:
Range("K34").Locked = True
Range("O34").Locked = True
End If

If Range("AR36") = "Vrai" Then
Range("K36").Locked = False
Range("O36").Locked = False
Else:
Range("K36").Locked = True
Range("O36").Locked = True
End If

If Range("AR38") = "Vrai" Then
Range("K38").Locked = False
Range("O38").Locked = False
Else:
Range("K38").Locked = True
Range("O38").Locked = True
End If

If Range("AR40") = "Vrai" Then
Range("K40").Locked = False
Range("O40").Locked = False
Else:
Range("K40").Locked = True
Range("O40").Locked = True
End If

If Range("AR42") = "Vrai" Then
Range("K42").Locked = False
Range("O42").Locked = False
Else:
Range("K42").Locked = True
Range("O42").Locked = True
End If

If Range("AR44") = "Vrai" Then
Range("K44").Locked = False
Range("O44").Locked = False
Else:
Range("K44").Locked = True
Range("O44").Locked = True
End If

Application.ScreenUpdating = True
Application.Goto Cell

'ActiveSheet.Protect Password:="Francis"
End Sub

Thanks a lot for your help.

Have a nice day!

Body:
This section can be simplified:

For Each cellule In Range("S50:X50")
If cellule.Value = "1" Then cellule.EntireColumn.Hidden = False
Next cellule

For Each cellule In Range("S50:X50")
If cellule.Value = "0" Then cellule.EntireColumn.Hidden = True
Next cellule

For Each cellule In Range("I50:J50")
If cellule.Value = "1" Then cellule.EntireColumn.Hidden = False
Next cellule

For Each cellule In Range("I50:J50")
If cellule.Value = "0" Then cellule.EntireColumn.Hidden = True
Next cellule

To the following (however, note that this will unhide any non-zero values).

For Each cellule in Range("S50:X50")
    cellule.EntireColumn.Hidden = (cellule.Value = "0")
Next
For Each cellule in Range("I50:J50")
    cellule.EntireColumn.Hidden = (cellule.Value = "0")
Next

And this section:

If Range("AR16") = "Vrai" Then
Range("K16").Locked = False
Range("O16").Locked = False
Else:
Range("K16").Locked = True
Range("O16").Locked = True
End If

If Range("AR18") = "Vrai" Then
Range("K18").Locked = False
Range("O18").Locked = False
Else:
Range("K18").Locked = True
Range("O18").Locked = True
End If

....

Can be simplified using a loop over Range("AR16:AR44")

For Each cellule in Range("AR16:AR44") Step 2
    cellule.Offset(,-33).Locked = (cellule.Value = "Vrai")
    cellule.Offset(,-29).Locked = (cellule.Value = "Vrai")
Next


问:
Optimise Coordinate Data Collection using array JavaScript
Currently I am storing distinct routes in routea, routeb, routec, etc.
I would like to collect them all onto one route and a set of two nested for loops to generate polylines.
Currently, I am using brute force, so
...

```<code>for (var i = 0, latlng1= [], len1 = routea.length; i < len1; i++) {
        latlng1.push(new L.LatLng(routea[i][0], routea[i][1]));
    }

    for (var i = 0, latlng2 = [], len2 = routeb.length; i < len2; i++) {
        latlng2.push(new L.LatLng(routeb[i][0], routeb[i][1]));}
</code>```

My attempt to nest the loop has been

```<code>route = [routea, routeb, routec];
for (var j = 0, lena = route; j < lena; j++) {
    for (var i = 0, latlng1= [], len = route[j].length; i < len; i++) {
        latlng.push(new L.LatLng(route[i][0], route[i][1]));
    }
    var pathmat = L.featureGroup ([L.polyline(latlng1[j])]);
    }
</code>```

But I get the following error
Uncaught TypeError: Cannot read property '_leaflet_id' of undefined
    at Object.stamp

答:
No need to loop through the routea, routeb... tables. You can build a polyline just with a coordinates array :

```<code>var route = [routea, routeb, routec];
var polylines = [];
for (var j = 0; j < route.length; j++) {
    polylines.push(L.polyline(route[j]);
}
</code>```

Then do whatever you want with the polylines. If you want to put all of them in a feature group :

```<code>var fg = L.featureGroup(polylines);
</code>```

Body:
Currently I am storing distinct routes in routea, routeb, routec, etc.
I would like to collect them all onto one route and a set of two nested for loops to generate polylines.
Currently, I am using brute force, so
...

for (var i = 0, latlng1= [], len1 = routea.length; i < len1; i++) {
        latlng1.push(new L.LatLng(routea[i][0], routea[i][1]));
    }

    for (var i = 0, latlng2 = [], len2 = routeb.length; i < len2; i++) {
        latlng2.push(new L.LatLng(routeb[i][0], routeb[i][1]));}

My attempt to nest the loop has been

route = [routea, routeb, routec];
for (var j = 0, lena = route; j < lena; j++) {
    for (var i = 0, latlng1= [], len = route[j].length; i < len; i++) {
        latlng.push(new L.LatLng(route[i][0], route[i][1]));
    }
    var pathmat = L.featureGroup ([L.polyline(latlng1[j])]);
    }

But I get the following error
Uncaught TypeError: Cannot read property '_leaflet_id' of undefined
    at Object.stamp

Body:
No need to loop through the routea, routeb... tables. You can build a polyline just with a coordinates array :

var route = [routea, routeb, routec];
var polylines = [];
for (var j = 0; j < route.length; j++) {
    polylines.push(L.polyline(route[j]);
}

Then do whatever you want with the polylines. If you want to put all of them in a feature group :

var fg = L.featureGroup(polylines);


问:
Hiding a button on clicking it in fragment for always with shared preferences
I want yo hide a button which is in fragment XML, by clicking on it , for always it will be hidden till uninstalling the app, by shared preferences. But I am getting errors , 'Unknown method setVisibility of android.widget.button' and   'btnsearch variable must be final to be used in  local class'  . here is my code:</p>

```<code>package com.niezwm.bododictionary.fragments;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;
import android.view.ViewGroup;
import android.widget.Button;
import android.content.Context;
import android.content.SharedPreferences;
import com.niezwm.bododictionary.R;

public class SearchFragment extends Fragment{

SharedPreferences sharedPreferences;
Button btnsearch;

public SearchFragment() {
// Required empty public constructor
 }

@Override
public void onCreate(Bundle     savedInstanceState) {
     super.onCreate(savedInstanceState);
}
@Override
public View   onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){
View rootView =  inflater.inflate(R.layout.fragment_search, container,false);
Button btnsearch =(Button) rootView.findViewById(R.id.btnsearch);
SharedPreferences sharedPreferences =this.getActivity().getSharedPreferences("pref",0);
btnsearch.setVisiblity(sharedPreferences.getBoolean("visiblity",false));
      btnsearch.setOnClickListener(new   View.OnClickListener(){
@Override
public void onClick(View view){
if(
                        btnsearch.getVisibility()==View.INVISIBLE){
      btnsearch.setVisibility(View.VISIBLE);
SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putBoolean("visiblity",true)
                        .commit();
                        }
                   Toast.makeText(getActivity(), "search", Toast.LENGTH_LONG).show();
}
// end onClick
});
return rootView;
}
// end onCreateView
}
</code>```

答:
If you access those two variables in the anonymous inner class you have to make them final:

```<code>final Button btnsearch = (Button) rootView.findViewById(R.id.btnsearch);
final SharedPreferences sharedPreferences = this.getActivity().getSharedPreferences("pref", 0);
</code>```

EDIT

setVisibility() wants an int, not a boolean.

```<code>boolean visibility = sharedPreferences.getBoolean("visiblity", false);
btnsearch.setVisibility(visibility ? View.VISIBLE : View.GONE);
</code>```

Body:
I want yo hide a button which is in fragment XML, by clicking on it , for always it will be hidden till uninstalling the app, by shared preferences. But I am getting errors , 'Unknown method setVisibility of android.widget.button' and   'btnsearch variable must be final to be used in  local class'  . here is my code:

package com.niezwm.bododictionary.fragments;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;
import android.view.ViewGroup;
import android.widget.Button;
import android.content.Context;
import android.content.SharedPreferences;
import com.niezwm.bododictionary.R;

public class SearchFragment extends Fragment{

SharedPreferences sharedPreferences;
Button btnsearch;

public SearchFragment() {
// Required empty public constructor
 }

@Override
public void onCreate(Bundle     savedInstanceState) {
     super.onCreate(savedInstanceState);
}
@Override
public View   onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){
View rootView =  inflater.inflate(R.layout.fragment_search, container,false);
Button btnsearch =(Button) rootView.findViewById(R.id.btnsearch);
SharedPreferences sharedPreferences =this.getActivity().getSharedPreferences("pref",0);
btnsearch.setVisiblity(sharedPreferences.getBoolean("visiblity",false));
      btnsearch.setOnClickListener(new   View.OnClickListener(){
@Override
public void onClick(View view){
if(
                        btnsearch.getVisibility()==View.INVISIBLE){
      btnsearch.setVisibility(View.VISIBLE);
SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putBoolean("visiblity",true)
                        .commit();
                        }
                   Toast.makeText(getActivity(), "search", Toast.LENGTH_LONG).show();
}
// end onClick
});
return rootView;
}
// end onCreateView
}

Body:
If you access those two variables in the anonymous inner class you have to make them final:

final Button btnsearch = (Button) rootView.findViewById(R.id.btnsearch);
final SharedPreferences sharedPreferences = this.getActivity().getSharedPreferences("pref", 0);

EDIT

setVisibility() wants an int, not a boolean.

boolean visibility = sharedPreferences.getBoolean("visiblity", false);
btnsearch.setVisibility(visibility ? View.VISIBLE : View.GONE);


问:
Grab object id and insert into session storage Angular
I have a controller that populates a second drop-down box depending on the selection of the first, this works well although WebStorm sees it as a syntax error.
I know want to post the ID of the format fname to my session storage to use else where, however I have tried the code bellow and I see Value as

[object Object]

if I use

```<code>sessionStorage.setItem('format', $scope.formats);
</code>```

and

undefined

if I use

sessionStorage.setItem('format', $scope.formats.id);

I have also tried

```<code>sessionStorage.setItem('format', $scope.formats.formatType.id);
</code>```

I get nothing not even a empty value

how do I correctly add the ID to my format value in my session storage ?

Full code

```<code>FirstModule.controller('dropDown', function ($scope) {

$scope.productsandformats = [
    {
        "name": "staff",
        "format": [
            {"Fname": "bill", "id": "1"},
            {"Fname": "bob", "id": "2"},
            {"Fname": "tom", "id": "3"}
        ]
    },
    {
        "name": "managers",
        "format": [
            {"Fname": "dick", "id": "4"},
            {"Fname": "jhon", "id": "5"}
        ]
    },

    {
        "name": "directors",
        "format": [
            {"Fname": "willy", "id": "6"}
        ]
    },

    {
        "name": "temp",
        "format": [
            {"Fname": "jeff", "id": "18"},
            {"Fname": "billy", "id": "19"}
        ]
    }];

$scope.productTypeChange = function () {
    $scope.formats = $scope.productsandformats.find(ps => ps.name == $scope.formData.ProductType.name)

    sessionStorage.setItem('format', $scope.formats.id);

}
</code>```

});

To further more explain how I get the ID, The code bellow enables the user to select A fname from the name type for example if select staff you get bill, bob and tom then after you select one it,ll print out the selected name and fname including the fname id, the fname id is what i need to send to the session storage

HTML

```<code><div class="radio col-sm-6" style="margin-top: 0 !important;">
    <label>
        <input type="radio" ng-model="formData.type" value="Create" >
        <span class="glyphicon glyphicon-unchecked">
        </span>
        Need to make a poster?
    </label>
</div>

<div class="radio col-sm-6">
    <label>
        <input type="radio" ng-model="formData.type" value="Preview">
        <span class="glyphicon glyphicon-eye-open">
        </span>
        Already have a poster?
    </label>
</div>
</code>```

答:
So I used the answer above but to achieve the id I had to use this </p>

```<code> $scope.myFunc = function() {
        var jsonItem = JSON.parse($scope.formData.formatType.id);
        sessionStorage.setItem('format', jsonItem);
    }
</code>```

<p>@Bolza answer was good but I needed more so kept digging and experimenting </p>

Body:
I have a controller that populates a second drop-down box depending on the selection of the first, this works well although WebStorm sees it as a syntax error.
I know want to post the ID of the format fname to my session storage to use else where, however I have tried the code bellow and I see Value as

[object Object]

if I use

sessionStorage.setItem('format', $scope.formats);

and

undefined

if I use

sessionStorage.setItem('format', $scope.formats.id);

I have also tried

sessionStorage.setItem('format', $scope.formats.formatType.id);

I get nothing not even a empty value

how do I correctly add the ID to my format value in my session storage ?

Full code

FirstModule.controller('dropDown', function ($scope) {

$scope.productsandformats = [
    {
        "name": "staff",
        "format": [
            {"Fname": "bill", "id": "1"},
            {"Fname": "bob", "id": "2"},
            {"Fname": "tom", "id": "3"}
        ]
    },
    {
        "name": "managers",
        "format": [
            {"Fname": "dick", "id": "4"},
            {"Fname": "jhon", "id": "5"}
        ]
    },

    {
        "name": "directors",
        "format": [
            {"Fname": "willy", "id": "6"}
        ]
    },

    {
        "name": "temp",
        "format": [
            {"Fname": "jeff", "id": "18"},
            {"Fname": "billy", "id": "19"}
        ]
    }];

$scope.productTypeChange = function () {
    $scope.formats = $scope.productsandformats.find(ps => ps.name == $scope.formData.ProductType.name)

    sessionStorage.setItem('format', $scope.formats.id);

}

});

To further more explain how I get the ID, The code bellow enables the user to select A fname from the name type for example if select staff you get bill, bob and tom then after you select one it,ll print out the selected name and fname including the fname id, the fname id is what i need to send to the session storage

HTML

        <input type="radio" ng-model="formData.type" value="Create" >

        Need to make a poster?

        <input type="radio" ng-model="formData.type" value="Preview">

        Already have a poster?

Body:
So I used the answer above but to achieve the id I had to use this

 $scope.myFunc = function() {
        var jsonItem = JSON.parse($scope.formData.formatType.id);
        sessionStorage.setItem('format', jsonItem);
    }

@Bolza answer was good but I needed more so kept digging and experimenting