问:
Local storage to change background colour
I am trying to change the background colour of my website with local storage. I am using onchange() within the HTML for the colours() function, and the rest is the JavaScript below

```<code>var bgcolour;

window.onload = function theme(){

    document.body.style.backgroundColor = "red";
    localStorage.setItem("bgcolour", 1);
}

function colours(){
    localStorage.bgcolour = document.getElementById("party").value;

    if (localStorage.bgcolour == '1'){
        document.body.style.backgroundColor = "red";
    }
}
</code>```

It does nothing. It doesn't even change, let alone store it as local storage.

I keep missing vital, small parts of code and it feels like I have done it again with this one.

Any help is greatly appreciated!

HTML:

```<code> <select name="pnumber" id="party" onchange="colours()">
     <option value="1">1</option>
     <option value="2">2</option>
     <option value="3">3</option>
     <option value="4">4</option>
     <option value="5">5</option>
     <option value="6">6</option>
     <option value="7">7</option>
     <option value="8">8</option>
     <option value="9">9</option>
     <option value="10">10</option>
     <option value="11">11</option>
     <option value="12">12</option>
     <option value="13">13</option>
     <option value="14">14</option>
     <option value="15">15 (maximum)</option>
 </select>
</code>```

答:
I believe something is wrong with your HTML. See this plunk. I copy pasted all of your javascript and I'm assuming your HTML is something like this:

```<code><input type="text" id="party" onchange="colours()" />
</code>```

You will notice that the background is originally gray, then putting a value "1" in the textbox will make the background red.

Body:
I am trying to change the background colour of my website with local storage. I am using onchange() within the HTML for the colours() function, and the rest is the JavaScript below

var bgcolour;

window.onload = function theme(){

    document.body.style.backgroundColor = "red";
    localStorage.setItem("bgcolour", 1);
}

function colours(){
    localStorage.bgcolour = document.getElementById("party").value;

    if (localStorage.bgcolour == '1'){
        document.body.style.backgroundColor = "red";
    }
}

It does nothing. It doesn't even change, let alone store it as local storage.

I keep missing vital, small parts of code and it feels like I have done it again with this one.

Any help is greatly appreciated!

HTML:

 <select name="pnumber" id="party" onchange="colours()">
     <option value="1">1</option>
     <option value="2">2</option>
     <option value="3">3</option>
     <option value="4">4</option>
     <option value="5">5</option>
     <option value="6">6</option>
     <option value="7">7</option>
     <option value="8">8</option>
     <option value="9">9</option>
     <option value="10">10</option>
     <option value="11">11</option>
     <option value="12">12</option>
     <option value="13">13</option>
     <option value="14">14</option>
     <option value="15">15 (maximum)</option>
 </select>

Body:
I believe something is wrong with your HTML. See this plunk. I copy pasted all of your javascript and I'm assuming your HTML is something like this:

<input type="text" id="party" onchange="colours()" />

You will notice that the background is originally gray, then putting a value "1" in the textbox will make the background red.


来源: stackexchange

问:
How can div maintain the same size when on mobile
I am working on a UI that, when displaying on a mobile device, gets too small for it to be used properly.

I have the size of the div fixed in pixels, and it keeps the size if the window is resized, but when I test it on mobile mode on chrome or on a actual mobile device, it shrinks. How can I stop it from behaving like that?

答:
in the css, set the divs min-width to the width that you want, along with the viewport meta. like this : </p>

```<code><html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <style>
           div#mydiv{
              min-width: <== put here the width that you want;
           }
        </style>
    </head>
    <body>
         <div id="mydiv"></div>
    </body>
</html>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
in the css, set the divs min-width to the width that you want, along with the viewport meta. like this :

<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <style>
           div#mydiv{
              min-width: <== put here the width that you want;
           }
        </style>
    </head>
    <body>
         <div id="mydiv"></div>
    </body>
</html>


问:
Vagrant Ubuntu Can't Resize Disk
I have a vagrant instance (using VirtualBox), and I'm using the vagrant-disksize plugin to allocate more disk space for it.

However the Ubuntu instance doesn't seem to "see" the extra space.

VirtualBox settings show 20GB virtual and ~6GB actual.

Further inspection of the Ubuntu settings show that only ~6GB are available.

How can I fix this?

答:
As the doc of the plugin states

Depending on the guest, you may need to resize the partition and the
  filesystem from within the guest. At present the plugin only resizes
  the underlying disk.

You can follow the instructions from this answer for the remaining steps after the virtual disk has been increased

Title: Vagrant Ubuntu Can't Resize Disk


问:
How to keep flex element's width after removing contents?
I have this flexible layout and some JS https://jsfiddle.net/7k8t3xgc/3/

```<code><div class="window">

    <div class="left">
         <div class="optional">optional content</div>
    </div>

    <div class="right">
        <div class="wordpool"></div>
        <div class="category"></div>
    </div>

</div>
</code>```

The .wordpool element is filled with some words that need to be moved to the .category element by clicking on them.

What is happening now, is that the .window element is shrinking in width when you click the words. Is there a way to prevent this behaviour? Only way I can think of is to calculate wordpools width on render and set it into a style attribute, but it has its drawbacks with responsiveness.

I can't remove the flex functionality, because both left (optional) and right panels need to be same width and centered.

I can't use static width as it needs to be responsive.

It can't be something like .window { width: 90%; } because of short content looking silly on wide screens.

Both left and right content changes between pages in my app (think of a quiz or Google Forms - can be text, can be images, checkboxes, radiobuttons etc.) but the HTML template is the same.

答:
Just to provide another solution, that may or not be what you want:

Don't change the elements from container, just have them on both containers, and toggle the opacity.

You can rearrange them using flexbox and order

var buttons = [{
    name: "lorem"
  },
  {
    name: "ipsum"
  },
  {
    name: "dolor"
  },
  {
    name: "sit"
  },
  {
    name: "amet"
  }
];

$(document).ready(function() {
  for (b of buttons) {
    $('.wordpool').append($("", {
      class: "word",
      id: b.name
    }).html(b.name));
    $('.category').append($("", {
      class: "word hidden",
      id: b.name
    }).html(b.name));
  }

  $(".wordpool").on("click", "span", function() {
    $(this).toggleClass('hidden');
    $(".category #" + $(this).attr('id')).toggleClass('hidden');
  });

  $(".category").on("click", "span", function() {
    $(this).toggleClass('hidden');
    $(".wordpool #" + $(this).attr('id')).toggleClass('hidden');
  });

  $("body").on("click", ".showoptional", function() {
    $(".left").toggle();
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body {
  height: 100%;
  margin: 0;
}

.wrapper {
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  padding: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f4efdc;
}

.showoptional {
  position: absolute;
  top: 5px;
  left: 5px;
}

.window {
  background: #fff;
  box-shadow: 0 0 10px #ccc;
  display: flex;
}

.left,
.right {
  padding: 20px;
  flex: 1 0 0px;
}

.left {
  display: none;
}

.optional {
  background: #eee;
  text-align: center;
  padding: 50px 0;
}

.word {
  display: inline-block;
  margin: 2px 5px;
  padding: 3px 5px;
  border: 1px solid #ddd;
  cursor: pointer;
}

.hidden {
  opacity: 0;
  order: 99;
}

.wordpool {
  text-align: center;
  display: flex;
}

.category {
  margin-top: 10px;
  border: 1px solid #ccc;
  min-height: 60px;
}

.category .word {
  display: block;
  text-align: center;
  margin: 2px;
}</code>```

  <input type="button" class="showoptional" value="Trigger optional content" />

optional content

```

Body:
I have this flexible layout and some JS https://jsfiddle.net/7k8t3xgc/3/

optional content

The .wordpool element is filled with some words that need to be moved to the .category element by clicking on them.

What is happening now, is that the .window element is shrinking in width when you click the words. Is there a way to prevent this behaviour? Only way I can think of is to calculate wordpools width on render and set it into a style attribute, but it has its drawbacks with responsiveness.

I can't remove the flex functionality, because both left (optional) and right panels need to be same width and centered.

I can't use static width as it needs to be responsive.

It can't be something like .window { width: 90%; } because of short content looking silly on wide screens.

Both left and right content changes between pages in my app (think of a quiz or Google Forms - can be text, can be images, checkboxes, radiobuttons etc.) but the HTML template is the same.

Body:
Just to provide another solution, that may or not be what you want:

Don't change the elements from container, just have them on both containers, and toggle the opacity.

You can rearrange them using flexbox and order

var buttons = [{
    name: "lorem"
  },
  {
    name: "ipsum"
  },
  {
    name: "dolor"
  },
  {
    name: "sit"
  },
  {
    name: "amet"
  }
];

$(document).ready(function() {
  for (b of buttons) {
    $('.wordpool').append($("<span>", {
      class: "word",
      id: b.name
    }).html(b.name));
    $('.category').append($("<span>", {
      class: "word hidden",
      id: b.name
    }).html(b.name));
  }

  $(".wordpool").on("click", "span", function() {
    $(this).toggleClass('hidden');
    $(".category #" + $(this).attr('id')).toggleClass('hidden');
  });

  $(".category").on("click", "span", function() {
    $(this).toggleClass('hidden');
    $(".wordpool #" + $(this).attr('id')).toggleClass('hidden');
  });

  $("body").on("click", ".showoptional", function() {
    $(".left").toggle();
  });

});

html,
body {
  height: 100%;
  margin: 0;
}

.wrapper {
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  padding: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f4efdc;
}

.showoptional {
  position: absolute;
  top: 5px;
  left: 5px;
}

.window {
  background: #fff;
  box-shadow: 0 0 10px #ccc;
  display: flex;
}

.left,
.right {
  padding: 20px;
  flex: 1 0 0px;
}

.left {
  display: none;
}

.optional {
  background: #eee;
  text-align: center;
  padding: 50px 0;
}

.word {
  display: inline-block;
  margin: 2px 5px;
  padding: 3px 5px;
  border: 1px solid #ddd;
  cursor: pointer;
}

.hidden {
  opacity: 0;
  order: 99;
}

.wordpool {
  text-align: center;
  display: flex;
}

.category {
  margin-top: 10px;
  border: 1px solid #ccc;
  min-height: 60px;
}

.category .word {
  display: block;
  text-align: center;
  margin: 2px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">

  <input type="button" class="showoptional" value="Trigger optional content" />

  <div class="window">

    <div class="left">
      <div class="optional">optional content</div>
    </div>

    <div class="right">
      <div class="wordpool"></div>
      <div class="category"></div>
    </div>

  </div>

</div>


问:
Laravel, how to redirect as 301 and 302
I cannot find info for redirecting as 301/302 in the Laravel docs.

In my routes.php file I use:

```<code>Route::get('foo', function(){
    return Redirect::to('/bar');
});
</code>```

Is this a 301 or 302 by default? Is there a way to set it manually? Any idea why this would be omitted from the docs?

答:
I update the answer for Laravel 5!
Now you can find on docs redirect helper:

```<code>return redirect('/home');

return redirect()->route('route.name');
</code>```

As usual.. whenever you are unsure, you can have a look at Laravel's API documentation with the source code. The Redirector class defines a $status = 302 as default value (302 is a temporary redirect).

If you wish have a permanent URL redirection (HTTP response status code 301 Moved Permanently), you can define the status code with the redirect() function:

```<code>Route::get('foo', function(){
    return redirect('/bar', 301);
});
</code>```

Title: Laravel, how to redirect as 301 and 302

Body:
I cannot find info for redirecting as 301/302 in the Laravel docs.

In my routes.php file I use:

Route::get('foo', function(){
    return Redirect::to('/bar');
});

Is this a 301 or 302 by default? Is there a way to set it manually? Any idea why this would be omitted from the docs?

Body:
I update the answer for Laravel 5!
Now you can find on docs redirect helper:

return redirect('/home');

return redirect()->route('route.name');

As usual.. whenever you are unsure, you can have a look at Laravel's API documentation with the source code. The Redirector class defines a $status = 302 as default value (302 is a temporary redirect).

If you wish have a permanent URL redirection (HTTP response status code 301 Moved Permanently), you can define the status code with the redirect() function:

Route::get('foo', function(){
    return redirect('/bar', 301);
});


问:
switch command in C# not working
I'm new to C# and I'm practising by coding a simple Rock, Paper Scissors game, however I have a problem with my "switch" command.
I want the user to input either Rock, Paper or Scissors, and then take the input and go to a particular case, however I can't figure out how to do it.</p>

```<code>    {
        //random number generator
            Random random = new Random();
            int randomNumber = random.Next(1,4);

        //user input
            Console.WriteLine("PLease Enter Rock, Paper or Scissors");
            string input = Console.ReadLine();

        //compare input and random number
        switch (input)
        {
            case Rock:
                if (randomNumber == 1)
                {
                    Console.WriteLine("It's a draw, computer also chose Rock");
                }
                else if (randomNumber == 2)
                {
                    Console.WriteLine("You loose, computer chose Paper");
                }
                else if (randomNumber == 3)
                {
                    Console.WriteLine("You win, computer chose Scissors");
                }
                break;

            case Paper:
                if (randomNumber == 1)
                {
                    Console.WriteLine("You win, computer chose Rock");
                }
                else if (randomNumber == 2)
                {
                    Console.WriteLine("It's a draw, computer also chose Paper");
                }
                else if (randomNumber == 3)
                {
                    Console.WriteLine("You loose, computer chose Scissors");

                }
                break;

            case Scissors:
                if (randomNumber == 1)
                {
                    Console.WriteLine("You loose, computer chose Rock");
                }
                else if (randomNumber == 2)
                {
                    Console.WriteLine("You win, computer chose Paper");
                }
                else if (randomNumber == 3)
                {
                    Console.WriteLine("It's a draw, computer chose Scissors");

                }
                break;
        }
</code>```

答:
The cases must be written as string literals (in quotes):

```<code>switch (input)
{
    case "Rock":
        // ...
        break;

    case "Paper":
        // ...
        break;

    case "Scissors":
        // ...
        break;
}
</code>```

Or alternatively, define some variables that hold these values, e.g.

```<code>string Rock = "Rock";
</code>```

Title: switch command in C# not working

Body:
I'm new to C# and I'm practising by coding a simple Rock, Paper Scissors game, however I have a problem with my "switch" command.
I want the user to input either Rock, Paper or Scissors, and then take the input and go to a particular case, however I can't figure out how to do it.

    {
        //random number generator
            Random random = new Random();
            int randomNumber = random.Next(1,4);

        //user input
            Console.WriteLine("PLease Enter Rock, Paper or Scissors");
            string input = Console.ReadLine();

        //compare input and random number
        switch (input)
        {
            case Rock:
                if (randomNumber == 1)
                {
                    Console.WriteLine("It's a draw, computer also chose Rock");
                }
                else if (randomNumber == 2)
                {
                    Console.WriteLine("You loose, computer chose Paper");
                }
                else if (randomNumber == 3)
                {
                    Console.WriteLine("You win, computer chose Scissors");
                }
                break;

            case Paper:
                if (randomNumber == 1)
                {
                    Console.WriteLine("You win, computer chose Rock");
                }
                else if (randomNumber == 2)
                {
                    Console.WriteLine("It's a draw, computer also chose Paper");
                }
                else if (randomNumber == 3)
                {
                    Console.WriteLine("You loose, computer chose Scissors");

                }
                break;

            case Scissors:
                if (randomNumber == 1)
                {
                    Console.WriteLine("You loose, computer chose Rock");
                }
                else if (randomNumber == 2)
                {
                    Console.WriteLine("You win, computer chose Paper");
                }
                else if (randomNumber == 3)
                {
                    Console.WriteLine("It's a draw, computer chose Scissors");

                }
                break;
        }

Body:
The cases must be written as string literals (in quotes):

switch (input)
{
    case "Rock":
        // ...
        break;

    case "Paper":
        // ...
        break;

    case "Scissors":
        // ...
        break;
}

Or alternatively, define some variables that hold these values, e.g.

string Rock = "Rock";


问:
Can not load Office Addin in Word online when set Requirement Set in manifest file
I load office add-in js file from CDN with this link: https://appsforoffice.microsoft.com/lib/1/hosted/office.js

As document said this is the latest version of the office api. In my add-in, I only use Office.context.document.setSelectedDataAsync which is belong to Selection Requirements Set to replace value from my Word

I configure the manifest file with this code

```<code><Requirements>
   <Sets DefaultMinVersion="1.1">
      <Set Name="Selection" MinVersion="1.1"/>
   </Sets>
   <Methods>
      <Method Name="Document.setSelectedDataAsync"/>
   </Methods>
</Requirements>
</code>```

When I publish the manifest file in Office 365, the add-in does not appear in the Admin Managed Tab (I'm testing in Word online and Word 2016)

I've tried to remove Methods Tag but the add-in still not show up. When I remove the Requirements tag, the add-in shows up again.

What I've done wrong here? Does I use wrong version of Office Api or the config in manifest is wrong?

答:
If you're not trying to restrict where your add-in shows up, then consider not using the requirement set definition in the manifest.

Have you tried using the "Upload My Add-in" link (top right in the dialog shown) to upload your manifest and verify that it works? If that works, then perhaps there's an issue in how the manifest was published to Office 365?

Thanks!

Body:
I load office add-in js file from CDN with this link: https://appsforoffice.microsoft.com/lib/1/hosted/office.js

As document said this is the latest version of the office api. In my add-in, I only use Office.context.document.setSelectedDataAsync which is belong to Selection Requirements Set to replace value from my Word

I configure the manifest file with this code

<Requirements>
   <Sets DefaultMinVersion="1.1">
      <Set Name="Selection" MinVersion="1.1"/>
   </Sets>
   <Methods>
      <Method Name="Document.setSelectedDataAsync"/>
   </Methods>
</Requirements>

When I publish the manifest file in Office 365, the add-in does not appear in the Admin Managed Tab (I'm testing in Word online and Word 2016)

I've tried to remove Methods Tag but the add-in still not show up. When I remove the Requirements tag, the add-in shows up again.

What I've done wrong here? Does I use wrong version of Office Api or the config in manifest is wrong?


问:
best way to sum up Matrix elements parallel in c#
What is the fastest most efficient way to sumUp all matrix elements parallel in .net 4.0 ?

using Parallel.For end in inner loop making lock(objectLock) { result += matrix[i, j] } is 2 times slowwer then sequential approach.

thanks for any hints,
bye

答: Well you can consider your martrix[m,n] to m arrays whose length is n and then sum the m arrays parallelly. And by the way, you shouldn't use lock here, use Interlocked.Add instead. I'm busy now, I'll write an example if I have time then.

ContentLicense: CC BY-SA 2.5


问:
Angular 2 multiple font colors in a textarea
I have a text area with one string binded to it. With the text color as white by default.

```<code><textarea style="background-color: black;color:#fff;" [(ngModel)]="outputText"></textarea>
</code>```

The bound string contains multiple variables.

```<code>return this.outputText = this.test1 + " test1Stat" + this.test2 + " test2Stat" + this.test3 + " test3Stat";
</code>```

What I want to do is, if test1 is less than 1, it should show "test1 test1Stat" in red, while everything else is in green.  Is there a way to do this?

答:
It's not possible to color part of the text in a textarea,
However-  you can try to use the 'contenteditable'  property instead.

It basically turns your div into a textbox,  and you can use html tags and such inside.

.greenText{
color:green;}

div{
border:black solid 1px;
padding:20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div contenteditable="true">text text <span class='greenText'>GREEN TEXT</span> more text that you can edit</div></code>```

Body:
I have a text area with one string binded to it. With the text color as white by default.

<textarea style="background-color: black;color:#fff;" [(ngModel)]="outputText"></textarea>

The bound string contains multiple variables.

return this.outputText = this.test1 + " test1Stat" + this.test2 + " test2Stat" + this.test3 + " test3Stat";

What I want to do is, if test1 is less than 1, it should show "test1 test1Stat" in red, while everything else is in green.  Is there a way to do this?

Body:
It's not possible to color part of the text in a textarea,
However-  you can try to use the 'contenteditable'  property instead.

It basically turns your div into a textbox,  and you can use html tags and such inside.

.greenText{
color:green;}

div{
border:black solid 1px;
padding:20px;
}

    <div contenteditable="true">text text <span class='greenText'>GREEN TEXT</span> more text that you can edit</div>


问:
Apply operations on groupBy result of stream
I have a List of fruit which contains name and ID

```<code>List<Fruit> fruitList = Arrays.asList(new Fruit("apple", 1), new Fruit("orange", 2), new Fruit("orange", 3));
</code>```

I want to rename the fruit name with name_Id only if duplicate fruit name exists like in case of my list orange will rename to orange_2 and orange_3 but the apple will remain apple..
How can I do it in single stream expression.

The solution that I came up with is

```<code>Map<String, List<Fruit>> fruitMap = fruitList.stream().collect(Collectors.groupingBy(Fruit::getName));

        Set<Entry<String, List<Fruit>>> entry = fruitMap.entrySet();

        for (Entry<String, List<Fruit>> en : entry) {
            List<Fruit> fruit = en.getValue();
            if (fruit.size() > 1) {
                fruit.stream().map(d -> {
                    d.setName(d.getName() + "_" + d.getId());
                    return d;
                }).collect(Collectors.toList());
            }
        }
    }
</code>```

but this is way more than one stream expression.

答:
Here's a (sort of) one-liner:

```<code>fruitList.stream().collect(Collectors.groupingBy(Fruit::getName))
    .values().stream()
        .filter(list -> list.size() > 1)
        .forEach(list -> list.forEach(Fruit::renameWithId));
</code>```

This assumes you have the following method in Fruit:

```<code>public void renameWithId() {
    name = name + "_" + id;
}
</code>```

If you can't modify your Fruit class, you could do the renaming inline:

```<code>fruitList.stream().collect(Collectors.groupingBy(Fruit::getName))
    .values().stream()
        .filter(list -> list.size() > 1)
        .forEach(list -> list.forEach(fruit ->
            fruit.setName(fruit.getName() + "_" + fruit.getId())));
</code>```

These long one-liners are so long that they are no longer one-liners, despite their name... Besides, the code ends up being hardly readable and is a pain to maintain and test. So I suggest you move the code that traverses the map and renames the fruits to a new method:

```<code>private void renameRepeatedFruits(Map<String, List<Fruit>> fruitMap) {
    fruitMap.values().stream()
        .filter(list -> list.size() > 1)
        .forEach(list -> list.forEach(Fruit::renameWithId));
}
</code>```

This would allow you to greatly simplify the first version of the code to:

```<code>renameRepeatedFruits(
    fruitList.stream().collect(Collectors.groupingBy(Fruit::getName)));
</code>```

Body:
I have a List of fruit which contains name and ID

List<Fruit> fruitList = Arrays.asList(new Fruit("apple", 1), new Fruit("orange", 2), new Fruit("orange", 3));

I want to rename the fruit name with name_Id only if duplicate fruit name exists like in case of my list orange will rename to orange_2 and orange_3 but the apple will remain apple..
How can I do it in single stream expression.

The solution that I came up with is

Map<String, List<Fruit>> fruitMap = fruitList.stream().collect(Collectors.groupingBy(Fruit::getName));

        Set<Entry<String, List<Fruit>>> entry = fruitMap.entrySet();

        for (Entry<String, List<Fruit>> en : entry) {
            List<Fruit> fruit = en.getValue();
            if (fruit.size() > 1) {
                fruit.stream().map(d -> {
                    d.setName(d.getName() + "_" + d.getId());
                    return d;
                }).collect(Collectors.toList());
            }
        }
    }

but this is way more than one stream expression.

Body:
Here's a (sort of) one-liner:

fruitList.stream().collect(Collectors.groupingBy(Fruit::getName))
    .values().stream()
        .filter(list -> list.size() > 1)
        .forEach(list -> list.forEach(Fruit::renameWithId));

This assumes you have the following method in Fruit:

public void renameWithId() {
    name = name + "_" + id;
}

If you can't modify your Fruit class, you could do the renaming inline:

fruitList.stream().collect(Collectors.groupingBy(Fruit::getName))
    .values().stream()
        .filter(list -> list.size() > 1)
        .forEach(list -> list.forEach(fruit ->
            fruit.setName(fruit.getName() + "_" + fruit.getId())));

These long one-liners are so long that they are no longer one-liners, despite their name... Besides, the code ends up being hardly readable and is a pain to maintain and test. So I suggest you move the code that traverses the map and renames the fruits to a new method:

private void renameRepeatedFruits(Map<String, List<Fruit>> fruitMap) {
    fruitMap.values().stream()
        .filter(list -> list.size() > 1)
        .forEach(list -> list.forEach(Fruit::renameWithId));
}

This would allow you to greatly simplify the first version of the code to:

renameRepeatedFruits(
    fruitList.stream().collect(Collectors.groupingBy(Fruit::getName)));


问:
ObservableBuffer giving IndexOutOfBounds in Scala
I am mesmerized. The below code is giving me an indexoutofbound error. But if I were to delete the slashes enabling for(j <- i until tmpArray.length) it would work. I really do not understand why it is happening, and would appreciate an explanation.

```<code> for(i <- 0 until tmpArray.length)
{
 // for(j <- i until tmpArray.length)
 // {
    if( date.getValue != null && tmpArray(i).date != date.getValue )
    {
      tmpArray.remove(i)
    }
//  }
}
</code>```

答:
You're modifying the array as you "iterate" over it.

You are actually iterating over the range 0 until tmpArray.length, which is calculated up front. At some point, you reduce the length of the array (or, I assume so, as I can't find remove on the Array class). But it's still going to continue the iteration up to whatever the last index was when you created the range.

When you uncomment the inner for block, you're making it recompute the range for each step of the outer for. And it just so happens that the j range will simply have nothing in it if i >= tmpArray.length. So it inadvertently guards against that failure.

This is very C-style (imperative) code. It looks like all you're trying to do is remove some items from an array. That's what filter is for.

```<code>val result = tmpArray.filter { d =>
  if(date.getValue != null && d != date.getValue) false else true
}
</code>```

This creates a new array (result) by passing an anonymous function to tmpArray.filter. It will pass each item in the array to your "predicate", and if it returns true, it'll keep that item in result, otherwise it will omit it.

You should note that I avoided saying "loop". Scala's for isn't for making loops. It's actually syntax sugar for calling methods like foreach and map. Google "scala for comprehensions" for more detail.

If you insist on creating a C-style loop using indexes and a loop variable, you'll want to use while, so that you can check if i < tmpArray.length each time.

Body:
I am mesmerized. The below code is giving me an indexoutofbound error. But if I were to delete the slashes enabling for(j <- i until tmpArray.length) it would work. I really do not understand why it is happening, and would appreciate an explanation.

 for(i <- 0 until tmpArray.length)
{
 // for(j <- i until tmpArray.length)
 // {
    if( date.getValue != null && tmpArray(i).date != date.getValue )
    {
      tmpArray.remove(i)
    }
//  }
}

Body:
You're modifying the array as you "iterate" over it.

You are actually iterating over the range 0 until tmpArray.length, which is calculated up front. At some point, you reduce the length of the array (or, I assume so, as I can't find remove on the Array class). But it's still going to continue the iteration up to whatever the last index was when you created the range.

When you uncomment the inner for block, you're making it recompute the range for each step of the outer for. And it just so happens that the j range will simply have nothing in it if i >= tmpArray.length. So it inadvertently guards against that failure.

This is very C-style (imperative) code. It looks like all you're trying to do is remove some items from an array. That's what filter is for.

val result = tmpArray.filter { d =>
  if(date.getValue != null && d != date.getValue) false else true
}

This creates a new array (result) by passing an anonymous function to tmpArray.filter. It will pass each item in the array to your "predicate", and if it returns true, it'll keep that item in result, otherwise it will omit it.

You should note that I avoided saying "loop". Scala's for isn't for making loops. It's actually syntax sugar for calling methods like foreach and map. Google "scala for comprehensions" for more detail.

If you insist on creating a C-style loop using indexes and a loop variable, you'll want to use while, so that you can check if i < tmpArray.length each time.


问:
Apache rewrite + Magento don't work as expected
I need to implement the following rewrite rules for my Magento 1 store - to remove a query string if it contains either param1 or param2 and URI is not /myfilter/.

Here is an example:

```<code>www.mystore.com/myfilter/ --> www.mystore.com/myfilter/

www.mystore.com/myfilter/?param1=1 --> www.mystore.com/myfilter/param1=1

www.mystore.com/<something>/?param1=1 --> www.mystore.com/<something>/

www.mystore.com/<something>/?param2=2 --> www.mystore.com/<something>/
</code>```

I added the following in .htaccess:

```<code>RewriteEngine on
RewriteCond %{REQUEST_URI} !^/myfilter/?
RewriteCond %{QUERY_STRING} param1 [OR]
RewriteCond %{QUERY_STRING} param2
RewriteRule (.*) /$1? [R=301,L]
</code>```

before standard Magento redirects:

```<code>############################################
## always send 404 on missing files in these folders

    RewriteCond %{REQUEST_URI} !^/(media|skin|js)/

############################################
## never rewrite for existing files, directories and links

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-l

############################################
## rewrite everything else to index.php

    RewriteRule .* index.php [L]
</code>```

But it works the wrong way.
These URLs work:

```<code>www.mystore.com/myfilter/ --> www.mystore.com/myfilter/

www.mystore.com/myfilter/?param3=1 --> www.mystore.com/myfilter/?param3=1

www.mystore.com/<something>/?param1=1 --> www.mystore.com/<something>/

www.mystore.com/<something>/?param2=2 --> www.mystore.com/<something>/
</code>```

But when URI contains /myfilter/ and either param1 or param2, it is redirecting me to /index.php:

```<code>www.mystore.com/myfilter/?param1=1 --> www.mystore.com/index.php
</code>```

Did I miss something?

答:
These rules made a trick I needed:</p>

```<code>RewriteEngine on
RewriteCond %{REQUEST_URI} !^/(index.php/)?myfilter/ [NC]
RewriteCond %{QUERY_STRING} param1 [OR]
RewriteCond %{QUERY_STRING} param2
RewriteRule (.*) /$1? [R=301,L]

RewriteCond %{REQUEST_URI} ^/myfilter/ [NC]
RewriteRule (.*) index.php/myfilter/ [L]
</code>```

Body:
I need to implement the following rewrite rules for my Magento 1 store - to remove a query string if it contains either param1 or param2 and URI is not /myfilter/.

Here is an example:

www.mystore.com/myfilter/ --> www.mystore.com/myfilter/

www.mystore.com/myfilter/?param1=1 --> www.mystore.com/myfilter/param1=1

www.mystore.com/<something>/?param1=1 --> www.mystore.com/<something>/

www.mystore.com/<something>/?param2=2 --> www.mystore.com/<something>/

I added the following in .htaccess:

RewriteEngine on
RewriteCond %{REQUEST_URI} !^/myfilter/?
RewriteCond %{QUERY_STRING} param1 [OR]
RewriteCond %{QUERY_STRING} param2
RewriteRule (.*) /$1? [R=301,L]

before standard Magento redirects:

############################################
## always send 404 on missing files in these folders

    RewriteCond %{REQUEST_URI} !^/(media|skin|js)/

############################################
## never rewrite for existing files, directories and links

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-l

############################################
## rewrite everything else to index.php

    RewriteRule .* index.php [L]

But it works the wrong way.
These URLs work:

www.mystore.com/myfilter/ --> www.mystore.com/myfilter/

www.mystore.com/myfilter/?param3=1 --> www.mystore.com/myfilter/?param3=1

www.mystore.com/<something>/?param1=1 --> www.mystore.com/<something>/

www.mystore.com/<something>/?param2=2 --> www.mystore.com/<something>/

But when URI contains /myfilter/ and either param1 or param2, it is redirecting me to /index.php:

www.mystore.com/myfilter/?param1=1 --> www.mystore.com/index.php

Did I miss something?

Body:
These rules made a trick I needed:

RewriteEngine on
RewriteCond %{REQUEST_URI} !^/(index.php/)?myfilter/ [NC]
RewriteCond %{QUERY_STRING} param1 [OR]
RewriteCond %{QUERY_STRING} param2
RewriteRule (.*) /$1? [R=301,L]

RewriteCond %{REQUEST_URI} ^/myfilter/ [NC]
RewriteRule (.*) index.php/myfilter/ [L]


问:
Launching a webpage with Firefox using selenium
I am currently reading Automate the Boring Stuff with Python and trying to learn how to use Selenium. For now, I am just trying to open a webpage and can't even get that to work. I know there are easier ways to launch a webpage with python, but my goal is to work with the webpage content later, so that is why I am using selenium.

```<code>from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://www.python.org")
</code>```

When I run this code, it does successfully launch Firefox but it does not open the web page I specified. This error is also returned.

```<code>Traceback (most recent call last):
  File "/Users/lbor/Desktop/se.py", line 2, in <module>
    driver = webdriver.Firefox()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/firefox/webdriver.py", line 80, in __init__
    self.binary, timeout)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/firefox/extension_connection.py", line 52, in __init__
    self.binary.launch_browser(self.profile, timeout=timeout)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/firefox/firefox_binary.py", line 68, in launch_browser
    self._wait_until_connectable(timeout=timeout)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/firefox/firefox_binary.py", line 108, in _wait_until_connectable
    % (self.profile.path))
selenium.common.exceptions.WebDriverException: Message: Can't load the profile. Profile Dir: /var/folders/4c/gsw7v5b118j406zxj3lxctt40000gn/T/tmp_dgwff4s If you specified a log_file in the FirefoxBinary constructor, check it for details.
</code>```

I don't understand what this problem is or how to go about fixing it. I am running OS 10.12.5, Python 3.6, Selenium 2.53.6, Firefox 53.0.3. As for the geckodriver, I don't know what that is or how to install it.

答:
You can download geckodriver from here.

After that, you need to load it up, using:

```<code>geckodriver = os.path.dirname(os.path.realpath(__file__)) + "/geckodriver"

drv = webdriver.Firefox(geckodriver)
</code>```

Body:
I am currently reading Automate the Boring Stuff with Python and trying to learn how to use Selenium. For now, I am just trying to open a webpage and can't even get that to work. I know there are easier ways to launch a webpage with python, but my goal is to work with the webpage content later, so that is why I am using selenium.

from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://www.python.org")

When I run this code, it does successfully launch Firefox but it does not open the web page I specified. This error is also returned.

Traceback (most recent call last):
  File "/Users/lbor/Desktop/se.py", line 2, in <module>
    driver = webdriver.Firefox()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/firefox/webdriver.py", line 80, in __init__
    self.binary, timeout)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/firefox/extension_connection.py", line 52, in __init__
    self.binary.launch_browser(self.profile, timeout=timeout)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/firefox/firefox_binary.py", line 68, in launch_browser
    self._wait_until_connectable(timeout=timeout)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/firefox/firefox_binary.py", line 108, in _wait_until_connectable
    % (self.profile.path))
selenium.common.exceptions.WebDriverException: Message: Can't load the profile. Profile Dir: /var/folders/4c/gsw7v5b118j406zxj3lxctt40000gn/T/tmp_dgwff4s If you specified a log_file in the FirefoxBinary constructor, check it for details.

I don't understand what this problem is or how to go about fixing it. I am running OS 10.12.5, Python 3.6, Selenium 2.53.6, Firefox 53.0.3. As for the geckodriver, I don't know what that is or how to install it.

Body:
You can download geckodriver from here.

After that, you need to load it up, using:

geckodriver = os.path.dirname(os.path.realpath(__file__)) + "/geckodriver"

drv = webdriver.Firefox(geckodriver)


问:
Hibernate Query Returning only one value
I am trying to create a Spring Hibernate App and I am accessing a table that has the following values:

```<code>select REPAIR_STATUS_CD,STATUS_DATE
from repair_status
where REPAIR_CONF_NO ='1234567';

REPAIR_STATUS_CD STATUS_DATE
----- -------------------- -
NEWO  25-FEB-2016 20:07:45
RLSD  25-FEB-2016 20:07:45
REQA  25-FEB-2016 20:13:24
URCD  26-FEB-2016 19:43:40
UINS  26-FEB-2016 19:43:45
UBER  27-FEB-2016 09:42:59
RQT6  27-FEB-2016 09:46:28
RQXP  03-MAR-2016 12:24:43
RBER  04-MAR-2016 21:52:22
SPCM  09-MAY-2016 18:13:33
SCOM  10-MAY-2016 19:09:54
</code>```

Now in the DAOImpl Class I am fetching the same using the below code.

```<code>Session session = sessionFactory.getCurrentSession();

            session.beginTransaction();

            Query<RepairStatus> query = session.createQuery("from     RepairStatus where repairConfNo = '"+repairConfNo+"' ");
            List<RepairStatus> repairStatusList = query.getResultList();
            System.out.println("Inside Repair Status Service");
            for(RepairStatus repairStatus: repairStatusList){
                System.out.println(repairStatus.getRepairStatusCode());
            }
</code>```

But when I print the output using the sysout and the for loop I am getting the following:

Inside Repair Status Service

```<code>NEWO
NEWO
NEWO
NEWO
NEWO
NEWO
NEWO
NEWO
NEWO
</code>```

Why are the rows getting repeated although the database has proper values.

Thanks a lot in advance :)

Also this is my Entity Class

```<code>package com.gsx.entity;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="TG_REPAIR_STATUS")
public class RepairStatus {

@Id
@Column(name="REPAIR_CONF_NO")
private String repairConfNo;

@Column(name="REPAIR_STATUS_CD")
private String repairStatusCode;

@Column(name="STATUS_DATE")
private Date statusDate;

public void setStatusDate(Date statusDate) {
    this.statusDate = statusDate;
}

public String getRepairConfNo() {
    return repairConfNo;
}

public void setRepairConfNo(String repairConfNo) {
    this.repairConfNo = repairConfNo;
}

public Date getStatusDate() {
    return statusDate;
}

public String getRepairStatusCode() {
    return repairStatusCode;
}

public void setRepairStatusCode(String repairStatusCode) {
    this.repairStatusCode = repairStatusCode;
}

}
</code>```

答:
You should replace

```<code>Query<RepairStatus> query = session.createQuery("from     RepairStatus where repairConfNo = '"+repairConfNo+"' ");
</code>```

to

```<code>Query<RepairStatus> query = session.createQuery("from     RepairStatus where repairConfNo =:repairConfNo");
parameterQuery.setParameter("repairConfNo", you_repairConfNo);
List<RepairStatus> repairStatusList = query.getResultList();
</code>```

Query is look good, you need to enable the show_sql

if your are using hibernate.cfg.xmlthen you can enable the sql like

```<code><property name="show_sql">true</property>
</code>```

then debug the generated sql by hibernate, it can help you to find out the issue.

Also your table name is TG_REPAIR_STATUS

```<code>@Table(name="TG_REPAIR_STATUS")
public class RepairStatus
</code>```

and you are running query

```<code>select REPAIR_STATUS_CD,STATUS_DATE
from repair_status
where REPAIR_CONF_NO ='1234567';
</code>```

on repair_status  table instead of TG_REPAIR_STATUS  table, please verify this on your database

Body:
I am trying to create a Spring Hibernate App and I am accessing a table that has the following values:

select REPAIR_STATUS_CD,STATUS_DATE
from repair_status
where REPAIR_CONF_NO ='1234567';

REPAIR_STATUS_CD STATUS_DATE
----- -------------------- -
NEWO  25-FEB-2016 20:07:45
RLSD  25-FEB-2016 20:07:45
REQA  25-FEB-2016 20:13:24
URCD  26-FEB-2016 19:43:40
UINS  26-FEB-2016 19:43:45
UBER  27-FEB-2016 09:42:59
RQT6  27-FEB-2016 09:46:28
RQXP  03-MAR-2016 12:24:43
RBER  04-MAR-2016 21:52:22
SPCM  09-MAY-2016 18:13:33
SCOM  10-MAY-2016 19:09:54

Now in the DAOImpl Class I am fetching the same using the below code.

Session session = sessionFactory.getCurrentSession();

            session.beginTransaction();

            Query<RepairStatus> query = session.createQuery("from     RepairStatus where repairConfNo = '"+repairConfNo+"' ");
            List<RepairStatus> repairStatusList = query.getResultList();
            System.out.println("Inside Repair Status Service");
            for(RepairStatus repairStatus: repairStatusList){
                System.out.println(repairStatus.getRepairStatusCode());
            }

But when I print the output using the sysout and the for loop I am getting the following:

Inside Repair Status Service

NEWO
NEWO
NEWO
NEWO
NEWO
NEWO
NEWO
NEWO
NEWO

Why are the rows getting repeated although the database has proper values.

Thanks a lot in advance :)

Also this is my Entity Class

package com.gsx.entity;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="TG_REPAIR_STATUS")
public class RepairStatus {

@Id
@Column(name="REPAIR_CONF_NO")
private String repairConfNo;

@Column(name="REPAIR_STATUS_CD")
private String repairStatusCode;

@Column(name="STATUS_DATE")
private Date statusDate;

public void setStatusDate(Date statusDate) {
    this.statusDate = statusDate;
}

public String getRepairConfNo() {
    return repairConfNo;
}

public void setRepairConfNo(String repairConfNo) {
    this.repairConfNo = repairConfNo;
}

public Date getStatusDate() {
    return statusDate;
}

public String getRepairStatusCode() {
    return repairStatusCode;
}

public void setRepairStatusCode(String repairStatusCode) {
    this.repairStatusCode = repairStatusCode;
}

}

Body:
You should replace

Query<RepairStatus> query = session.createQuery("from     RepairStatus where repairConfNo = '"+repairConfNo+"' ");

to

Query<RepairStatus> query = session.createQuery("from     RepairStatus where repairConfNo =:repairConfNo");
parameterQuery.setParameter("repairConfNo", you_repairConfNo);
List<RepairStatus> repairStatusList = query.getResultList();

Query is look good, you need to enable the show_sql

if your are using hibernate.cfg.xmlthen you can enable the sql like

<property name="show_sql">true</property>

then debug the generated sql by hibernate, it can help you to find out the issue.

Also your table name is TG_REPAIR_STATUS

@Table(name="TG_REPAIR_STATUS")
public class RepairStatus

and you are running query

select REPAIR_STATUS_CD,STATUS_DATE
from repair_status
where REPAIR_CONF_NO ='1234567';

on repair_status  table instead of TG_REPAIR_STATUS  table, please verify this on your database


答:
You can install geckodriver here, by selecting the appropriate version for your computer:

```<code>https://github.com/mozilla/geckodriver/releases
</code>```

Then, in your code, you pass the full path for the location of the geckodriver on your computer to the Firefox method:

```<code>browser = webdriver.Firefox(executable_path="/Users/username/Location/geckodriver")

browser.get("https://google.com") #this will load the the google homepage.
#you can specify any page you want here.
</code>```

Title: Launching a webpage with Firefox using selenium

Body:
You can install geckodriver here, by selecting the appropriate version for your computer:

https://github.com/mozilla/geckodriver/releases

Then, in your code, you pass the full path for the location of the geckodriver on your computer to the Firefox method:

browser = webdriver.Firefox(executable_path="/Users/username/Location/geckodriver")

browser.get("https://google.com") #this will load the the google homepage.
#you can specify any page you want here.


问:
How are multidimensional arrays stored in memory?
I was learning about pointers and multidimensional arrays.

I know that they are comprised of several sub arrays arranged one after the other like this.

int C[ 3 ][ 2 ][ 2 ];

In this example C = 800  This is a pointer to the first array element of the 3 integer array.

So, I assume there is a block of memory reserved to store the reference variable C like this

What I don't understand is how dereferencing work with arrays.

In normal context *C mean get the value stored at the address 800. So *C = 2

But here *C would be 800. I understand this logically. This is a pointer to the 2 integer array inside.

But how does the compiler understand that? Where are the information about the other arrays stored in memory?

source for screenshots - mycodeschool youtube channel

答:
When you declare a static array tab[x][y] the compiler will use tab[x * y] and calculate the right offset. It doesn't work like double pointers, like char **tab. In that case you have an array of pointers, each one pointing on an array of char.

When you declare a function using a static array, you have to specify the size of the dimensions excepted the last.
For example:

Void fn(char t[4][5][6][])

And t[x][y][z][a] will be replaced per t[x × 4 × 5 × 6 + y × 5 × 6 + z × 6 + a]


问:
Groovy paradigm for conditional with find
This code works, but the duplicate find seems less than optimal. Is it possible to implement the same functionality without the duplication?</p>

```<code>def pattern = ~'some_regex'
def inFile = new File('in')

inFile.eachLine { String line ->
    if (line.find(pattern)) {
        line.find(pattern) { match ->
            ... // do something
        }
    }
    else {
        ... // do something (else)
    }
}
</code>```

答:
I'd suggest to use eachMatch()

```<code>inFile.eachLine { String line ->
    String matched
    line.eachMatch( pattern ){
      matched = it[ 0 ]
      doSomethingWithMatch matched
    }
    if( !matched ) doNoMatch()
}
</code>```

Body:
This code works, but the duplicate find seems less than optimal. Is it possible to implement the same functionality without the duplication?

def pattern = ~'some_regex'
def inFile = new File('in')

inFile.eachLine { String line ->
    if (line.find(pattern)) {
        line.find(pattern) { match ->
            ... // do something
        }
    }
    else {
        ... // do something (else)
    }
}

Body:
I'd suggest to use eachMatch()

inFile.eachLine { String line ->
    String matched
    line.eachMatch( pattern ){
      matched = it[ 0 ]
      doSomethingWithMatch matched
    }
    if( !matched ) doNoMatch()
}


问:
How to import the electron ipcRenderer in a react / webpack 2 setup
using a electron, react (es6 / jsx), sass, pouchdb and webpack 2 setup. I fail to import or require ipcRenderer to make communication between main and renderer process possible. My setup can be found here: https://github.com/wende60/timeTracker

Any hints how to get the ipcRenderer into a react component?

Cheers, jo

答:
Found a good solution for this issue using webpack-target-electron-renderer So I can develop the web-part in a localhost environment with hot-reloading. electron is required only in the electron environment.

You can see a working example here:
https://github.com/wende60/webpack-web-and-electron-example, forked from acao's webpack-web-and-electron-example and updated for webpack 2 and hot-replacement.

If you are interested in a webpack, electron, react, sass and pouchdb setup have a look here:
https://github.com/wende60/timeTracker
Work is still in progress...


问:
how to create explode effect the UIView?
i need explode effect when the view change i.e., explode animation when i move to the next view. i found this type of animation in facebook app when click the icon in the dash board

please help me

答: On action...take a image View add it as subview to your view,load with series of images of explosion(or any thing which you want) start it animating, when the animation finishes from the delegate remove it from superview.</p>


问:
Change DOM content through .firstChild property
I am trying to select an element by its relation with the rest of this DOM:

```<code><div id="dad">
    <p>son</p>
    <p>son</p>
</div>
</code>```

As seen here:

```<code>let daddy = document.getElementById('dad');
daddy.firstChild.textContent = "Im first";
</code>```

What JS makes is, instead of changing its inner HTML, inserting the string as the first element of the 'dad'
.

This makes sense but, how can I make use of this property to select this first child and replace its content? Instead of inserting content as the element's first child.

答:
The children() method returns all direct children of the selected element.

This method only traverse a single level down the DOM tree.

```<code>$("#dad").children(":first").text("Im first");
</code>```

Body:
I am trying to select an element by its relation with the rest of this DOM:

son

son

As seen here:

let daddy = document.getElementById('dad');
daddy.firstChild.textContent = "Im first";

What JS makes is, instead of changing its inner HTML, inserting the string as the first element of the 'dad'
.

This makes sense but, how can I make use of this property to select this first child and replace its content? Instead of inserting content as the element's first child.

Body:
The children() method returns all direct children of the selected element.

This method only traverse a single level down the DOM tree.

$("#dad").children(":first").text("Im first");


问:
Cannot open a newtab in selenium webdriver on Mac OS X
I should be able to open a new tab in selenium for python using the code

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://stackoverflow.com/")

body = driver.find_element_by_tag_name("body")
body.send_keys(Keys.COMMAND + 't')
</code>```

But no new tab opens, and no error message appears (http://stackoverflow.com/ does load).

Note that I am using Keys.COMMAND + 't' because I am running the code on OS X.

I have no idea what is causing the issue as posts like this one, indicate that my code should work.

Updated to include answers

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://stackoverflow.com/")

current_tab = driver.current_window_handle
driver.execute_script('window.open();')
new_tab = [tab for tab in driver.window_handles if tab != current_tab][0]
driver.switch_to.window(new_tab)
driver.get("http://github.com")
inputElement = driver.find_element_by_id("user[login]")
inputElement.send_keys('1')

current_tab = driver.current_window_handle
driver.execute_script('window.open();')
new_tab = [tab for tab in driver.window_handles if tab != current_tab][0]
driver.switch_to.window(new_tab)
driver.get("http://github.com")
inputElement = driver.find_element_by_id("user[email]")
inputElement.send_keys('2')
</code>```

答:
Try below code to open new tab and switch to it:

```<code>driver = webdriver.Firefox()
driver.get("http://stackoverflow.com/")

current_tab = driver.current_window_handle
driver.execute_script('window.open("http://github.com");')
new_tab = [tab for tab in driver.window_handles if tab != current_tab][0]
driver.switch_to.window(new_tab)
inputElement = driver.find_element_by_id("user[login]")
inputElement.send_keys('1')

driver.execute_script('window.open("http://github.com");')
third_tab = [tab for tab in driver.window_handles if tab not in (current_tab, new_tab)][0]
driver.switch_to.window(third_tab)
inputElement = driver.find_element_by_id("user[email]")
inputElement.send_keys('2')
</code>```

You can use driver.close() to close new tab and driver.switch_to.window(current_tab) to switch back to initial tab

Also note that you can pass page URL you want to open in new tab as argument to window.open() like:

```<code>driver.execute_script('window.open("https://google.com");')
</code>```

Body:
I should be able to open a new tab in selenium for python using the code

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://stackoverflow.com/")

body = driver.find_element_by_tag_name("body")
body.send_keys(Keys.COMMAND + 't')

But no new tab opens, and no error message appears (http://stackoverflow.com/ does load).

Note that I am using Keys.COMMAND + 't' because I am running the code on OS X.

I have no idea what is causing the issue as posts like this one, indicate that my code should work.

Updated to include answers

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://stackoverflow.com/")

current_tab = driver.current_window_handle
driver.execute_script('window.open();')
new_tab = [tab for tab in driver.window_handles if tab != current_tab][0]
driver.switch_to.window(new_tab)
driver.get("http://github.com")
inputElement = driver.find_element_by_id("user[login]")
inputElement.send_keys('1')

current_tab = driver.current_window_handle
driver.execute_script('window.open();')
new_tab = [tab for tab in driver.window_handles if tab != current_tab][0]
driver.switch_to.window(new_tab)
driver.get("http://github.com")
inputElement = driver.find_element_by_id("user[email]")
inputElement.send_keys('2')

Body:
Try below code to open new tab and switch to it:

driver = webdriver.Firefox()
driver.get("http://stackoverflow.com/")

current_tab = driver.current_window_handle
driver.execute_script('window.open("http://github.com");')
new_tab = [tab for tab in driver.window_handles if tab != current_tab][0]
driver.switch_to.window(new_tab)
inputElement = driver.find_element_by_id("user[login]")
inputElement.send_keys('1')

driver.execute_script('window.open("http://github.com");')
third_tab = [tab for tab in driver.window_handles if tab not in (current_tab, new_tab)][0]
driver.switch_to.window(third_tab)
inputElement = driver.find_element_by_id("user[email]")
inputElement.send_keys('2')

You can use driver.close() to close new tab and driver.switch_to.window(current_tab) to switch back to initial tab

Also note that you can pass page URL you want to open in new tab as argument to window.open() like:

driver.execute_script('window.open("https://google.com");')


问:
VMSizeDoesntSupportPremiumStorage Azure Creating VM From VHD
I'm using this template to create an Azure VM from an existing disk.

I'm using the EXACT same VM size "Standard_D11_v2" that the existing disk was created on, however I keep receiving the error listed below.

Any help would be GREATLY appreciated, I can't seem to get past this and I'm confused why I could originally have Standard_D11_V2 VM running this exact disk, but now I cannot.

Error response

```<code>{
  "status": "Failed",
  "error": {
    "code": "ResourceDeploymentFailure",
    "message": "The resource operation completed with terminal provisioning state 'Failed'.",
    "details": [
      {
        "code": "VMSizeDoesntSupportPremiumStorage",
        "message": "Storage account type Premium_LRS is not supported for VM size Standard_D11_v2."
      }
    ]
  }
}
</code>```

Here is my script:

```<code>{
    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "osDiskVhdUri": {
            "type": "String",
            "metadata": {
                "description": "Uri of the existing VHD"
            }
        },
        "osType": {
            "allowedValues": [
                "Windows",
                "Linux"
            ],
            "type": "String",
            "metadata": {
                "description": "Type of OS on the existing vhd"
            }
        },
        "vmSize": {
            "defaultValue": "Standard_A2",
            "type": "String",
            "metadata": {
                "description": "Size of the VM"
            }
        },
        "vmName": {
            "type": "String",
            "metadata": {
                "description": "Name of the VM"
            }
        }
    },
    "variables": {
        "diagStorageAccountName": "[concat(uniquestring(resourceGroup().id), 'specvm')]",
        "api-version": "2015-06-15",
        "addressPrefix": "10.0.0.0/16",
        "subnetName": "Subnet",
        "subnetPrefix": "10.0.0.0/24",
        "publicIPAddressName": "specializedVMPublicIP",
        "publicIPAddressType": "Dynamic",
        "virtualNetworkName": "specializedVMVNET",
        "vnetID": "[resourceId('Microsoft.Network/virtualNetworks',variables('virtualNetworkName'))]",
        "subnetRef": "[concat(variables('vnetID'),'/subnets/',variables('subnetName'))]",
        "nicName": "specializedVMNic"
    },
    "resources": [
        {
            "type": "Microsoft.Storage/storageAccounts",
            "sku": {
                "name": "Standard_GRS"
            },
            "kind": "Storage",
            "name": "[variables('diagStorageAccountName')]",
            "apiVersion": "2016-01-01",
            "location": "[resourceGroup().location]",
            "properties": {}
        },
        {
            "type": "Microsoft.Network/virtualNetworks",
            "name": "[variables('virtualNetworkName')]",
            "apiVersion": "[variables('api-version')]",
            "location": "[resourceGroup().location]",
            "properties": {
                "addressSpace": {
                    "addressPrefixes": [
                        "[variables('addressPrefix')]"
                    ]
                },
                "subnets": [
                    {
                        "name": "[variables('subnetName')]",
                        "properties": {
                            "addressPrefix": "[variables('subnetPrefix')]"
                        }
                    }
                ]
            }
        },
        {
            "type": "Microsoft.Network/networkInterfaces",
            "name": "[variables('nicName')]",
            "apiVersion": "[variables('api-version')]",
            "location": "[resourceGroup().location]",
            "properties": {
                "ipConfigurations": [
                    {
                        "name": "ipconfig1",
                        "properties": {
                            "privateIPAllocationMethod": "Dynamic",
                            "publicIPAddress": {
                                "id": "[resourceId('Microsoft.Network/publicIPAddresses',variables('publicIPAddressName'))]"
                            },
                            "subnet": {
                                "id": "[variables('subnetRef')]"
                            }
                        }
                    }
                ]
            },
            "dependsOn": [
                "[concat('Microsoft.Network/publicIPAddresses/', variables('publicIPAddressName'))]",
                "[concat('Microsoft.Network/virtualNetworks/', variables('virtualNetworkName'))]"
            ]
        },
        {
            "type": "Microsoft.Network/publicIPAddresses",
            "name": "[variables('publicIPAddressName')]",
            "apiVersion": "[variables('api-version')]",
            "location": "[resourceGroup().location]",
            "properties": {
                "publicIPAllocationMethod": "[variables('publicIPAddressType')]"
            }
        },
        {
            "type": "Microsoft.Compute/virtualMachines",
            "name": "[parameters('vmName')]",
            "apiVersion": "[variables('api-version')]",
            "location": "[resourceGroup().location]",
            "properties": {
                "hardwareProfile": {
                    "vmSize": "[parameters('vmSize')]"
                },
                "storageProfile": {
                    "osDisk": {
                        "name": "[concat(parameters('vmName'),'-osDisk')]",
                        "osType": "[parameters('osType')]",
                        "caching": "ReadWrite",
                        "vhd": {
                            "uri": "[parameters('osDiskVhdUri')]"
                        },
                        "createOption": "Attach"
                    }
                },
                "networkProfile": {
                    "networkInterfaces": [
                        {
                            "id": "[resourceId('Microsoft.Network/networkInterfaces', variables('nicName'))]"
                        }
                    ]
                },
                "diagnosticsProfile": {
                    "bootDiagnostics": {
                        "enabled": "true",
                        "storageUri": "[concat(reference(concat('Microsoft.Storage/storageAccounts/', variables('diagStorageAccountName')), '2016-01-01').primaryEndpoints.blob)]"
                    }
                }
            },
            "dependsOn": [
                "[concat('Microsoft.Network/networkInterfaces/', variables('nicName'))]"
            ]
        }
    ]
}
</code>```

Here is where I found the above script:

https://github.com/Azure/azure-quickstart-templates/tree/master/201-vm-specialized-vhd

答:
You are trying to use a Premium Storage account for the VHD, but a VM size that does not support Premium Storage.  You have a couple choices to solve the issue:

Move the VHD to a standard storage account and use that storage account in your ARM template.

Use one of the DS size VMs that supports Premium Storage, such as Standard_DS11_v2.

You can read more about this at https://learn.microsoft.com/en-us/azure/storage/storage-premium-storage.

Body:
I'm using this template to create an Azure VM from an existing disk.

I'm using the EXACT same VM size "Standard_D11_v2" that the existing disk was created on, however I keep receiving the error listed below.

Any help would be GREATLY appreciated, I can't seem to get past this and I'm confused why I could originally have Standard_D11_V2 VM running this exact disk, but now I cannot.

Error response

{
  "status": "Failed",
  "error": {
    "code": "ResourceDeploymentFailure",
    "message": "The resource operation completed with terminal provisioning state 'Failed'.",
    "details": [
      {
        "code": "VMSizeDoesntSupportPremiumStorage",
        "message": "Storage account type Premium_LRS is not supported for VM size Standard_D11_v2."
      }
    ]
  }
}

Here is my script:

{
    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "osDiskVhdUri": {
            "type": "String",
            "metadata": {
                "description": "Uri of the existing VHD"
            }
        },
        "osType": {
            "allowedValues": [
                "Windows",
                "Linux"
            ],
            "type": "String",
            "metadata": {
                "description": "Type of OS on the existing vhd"
            }
        },
        "vmSize": {
            "defaultValue": "Standard_A2",
            "type": "String",
            "metadata": {
                "description": "Size of the VM"
            }
        },
        "vmName": {
            "type": "String",
            "metadata": {
                "description": "Name of the VM"
            }
        }
    },
    "variables": {
        "diagStorageAccountName": "[concat(uniquestring(resourceGroup().id), 'specvm')]",
        "api-version": "2015-06-15",
        "addressPrefix": "10.0.0.0/16",
        "subnetName": "Subnet",
        "subnetPrefix": "10.0.0.0/24",
        "publicIPAddressName": "specializedVMPublicIP",
        "publicIPAddressType": "Dynamic",
        "virtualNetworkName": "specializedVMVNET",
        "vnetID": "[resourceId('Microsoft.Network/virtualNetworks',variables('virtualNetworkName'))]",
        "subnetRef": "[concat(variables('vnetID'),'/subnets/',variables('subnetName'))]",
        "nicName": "specializedVMNic"
    },
    "resources": [
        {
            "type": "Microsoft.Storage/storageAccounts",
            "sku": {
                "name": "Standard_GRS"
            },
            "kind": "Storage",
            "name": "[variables('diagStorageAccountName')]",
            "apiVersion": "2016-01-01",
            "location": "[resourceGroup().location]",
            "properties": {}
        },
        {
            "type": "Microsoft.Network/virtualNetworks",
            "name": "[variables('virtualNetworkName')]",
            "apiVersion": "[variables('api-version')]",
            "location": "[resourceGroup().location]",
            "properties": {
                "addressSpace": {
                    "addressPrefixes": [
                        "[variables('addressPrefix')]"
                    ]
                },
                "subnets": [
                    {
                        "name": "[variables('subnetName')]",
                        "properties": {
                            "addressPrefix": "[variables('subnetPrefix')]"
                        }
                    }
                ]
            }
        },
        {
            "type": "Microsoft.Network/networkInterfaces",
            "name": "[variables('nicName')]",
            "apiVersion": "[variables('api-version')]",
            "location": "[resourceGroup().location]",
            "properties": {
                "ipConfigurations": [
                    {
                        "name": "ipconfig1",
                        "properties": {
                            "privateIPAllocationMethod": "Dynamic",
                            "publicIPAddress": {
                                "id": "[resourceId('Microsoft.Network/publicIPAddresses',variables('publicIPAddressName'))]"
                            },
                            "subnet": {
                                "id": "[variables('subnetRef')]"
                            }
                        }
                    }
                ]
            },
            "dependsOn": [
                "[concat('Microsoft.Network/publicIPAddresses/', variables('publicIPAddressName'))]",
                "[concat('Microsoft.Network/virtualNetworks/', variables('virtualNetworkName'))]"
            ]
        },
        {
            "type": "Microsoft.Network/publicIPAddresses",
            "name": "[variables('publicIPAddressName')]",
            "apiVersion": "[variables('api-version')]",
            "location": "[resourceGroup().location]",
            "properties": {
                "publicIPAllocationMethod": "[variables('publicIPAddressType')]"
            }
        },
        {
            "type": "Microsoft.Compute/virtualMachines",
            "name": "[parameters('vmName')]",
            "apiVersion": "[variables('api-version')]",
            "location": "[resourceGroup().location]",
            "properties": {
                "hardwareProfile": {
                    "vmSize": "[parameters('vmSize')]"
                },
                "storageProfile": {
                    "osDisk": {
                        "name": "[concat(parameters('vmName'),'-osDisk')]",
                        "osType": "[parameters('osType')]",
                        "caching": "ReadWrite",
                        "vhd": {
                            "uri": "[parameters('osDiskVhdUri')]"
                        },
                        "createOption": "Attach"
                    }
                },
                "networkProfile": {
                    "networkInterfaces": [
                        {
                            "id": "[resourceId('Microsoft.Network/networkInterfaces', variables('nicName'))]"
                        }
                    ]
                },
                "diagnosticsProfile": {
                    "bootDiagnostics": {
                        "enabled": "true",
                        "storageUri": "[concat(reference(concat('Microsoft.Storage/storageAccounts/', variables('diagStorageAccountName')), '2016-01-01').primaryEndpoints.blob)]"
                    }
                }
            },
            "dependsOn": [
                "[concat('Microsoft.Network/networkInterfaces/', variables('nicName'))]"
            ]
        }
    ]
}

Here is where I found the above script:

https://github.com/Azure/azure-quickstart-templates/tree/master/201-vm-specialized-vhd


问:
single or double quote in javascript append
i am beginner in Jquery,
confused about using single quote or double quote to call the value of myName Textbox, i want to catch the value of text box .

this is my code, calling function save_order is not working, because failure syntax in
document.getElementById('myName').value

what is the right syntax ?

```<code><script>
var param=3;
$('#saveList').append(
'<p>FullName : <input type="text" id="myName"></p>'+
'<p><input type="button" value="SAVE" onClick="save_order('+ param +',document.getElementById('myName').value)"></p>');
</script>
</code>```

pls help me anybody
thank you

答:
Having code within code within code is really just begging for quoting problems, to be honest.  Instead of stacking these languages on top of each other, use the jQuery library that you're already using to create the click handler for your new element.

It's not entirely clear if these added elements are unique and can have id values, so let's go with a class value for the input button.  And we'll use data- attributes for the dynamic values.  Something like this:

```<code>var param=3;
$('#saveList').append(
    '<p>FullName : <input type="text" id="myName"></p>'+
    '<p><input type="button" class="orderButton" value="SAVE" data-name="myName" data-param="'+ param +'"></p>');
</code>```

Your jQuery code can have a single click handler which responds to any "order button" click:

```<code>$(document).on('click', '.orderButton', function () {
    var nameElement = $(this).data('name');
    var name = $('#' + nameElement).val();
    var param = $(this).data('param');
    save_order(param, name);
});
</code>```

Keep the HTML and the JavaScript reasonable separated and the code becomes a lot cleaner and easier to maintain.  I'm sure this can be cleaned up quite a bit more, but this should at least be enough to get you started.

Body:
i am beginner in Jquery,
confused about using single quote or double quote to call the value of myName Textbox, i want to catch the value of text box .

this is my code, calling function save_order is not working, because failure syntax in
document.getElementById('myName').value

what is the right syntax ?

pls help me anybody
thank you

Body:
Having code within code within code is really just begging for quoting problems, to be honest.  Instead of stacking these languages on top of each other, use the jQuery library that you're already using to create the click handler for your new element.

It's not entirely clear if these added elements are unique and can have id values, so let's go with a class value for the input button.  And we'll use data- attributes for the dynamic values.  Something like this:

var param=3;
$('#saveList').append(
    '<p>FullName : <input type="text" id="myName"></p>'+
    '<p><input type="button" class="orderButton" value="SAVE" data-name="myName" data-param="'+ param +'"></p>');

Your jQuery code can have a single click handler which responds to any "order button" click:

$(document).on('click', '.orderButton', function () {
    var nameElement = $(this).data('name');
    var name = $('#' + nameElement).val();
    var param = $(this).data('param');
    save_order(param, name);
});

Keep the HTML and the JavaScript reasonable separated and the code becomes a lot cleaner and easier to maintain.  I'm sure this can be cleaned up quite a bit more, but this should at least be enough to get you started.


答:
Alternatively, loop through the child nodes until you find the first:

let daddy = document.getElementById('dad');
var child = daddy.firstChild;
while(child && child.nodeType !== 1) child = child.nextSibling;
child.textContent = "Im first";```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="dad">
    <p>son</p>
    <p>son</p>
</div></code>```

Title: Change DOM content through .firstChild property

Body:
Alternatively, loop through the child nodes until you find the first:

let daddy = document.getElementById('dad');
var child = daddy.firstChild;
while(child && child.nodeType !== 1) child = child.nextSibling;
child.textContent = "Im first";

<div id="dad">
    <p>son</p>
    <p>son</p>
</div>


问:
Join to a table only when column value is true
I am using SQL Server 2005. I am trying to join 2 tables together, but only when a column value in the main table is true. Like this:

```<code>select * from T1
join T2 on T1.value = T2.value
where T2.value2 = 'variable2'
and T2.value3 = 'variable3'
</code>```

There is a column value in T1 which says if I have to use the values in T2. I could to a case around the where clause, but it will always join to the table, and if the value in T1 is false, there are no values in T2 to join to, so the select returns no rows.

You can't put a case around the join, so I am a little bit stuck with this ... can anyone help ?

答:
What, if any, are the performance considerations related to conditional joins, I wonder? Is it equivalent to a UNION like this:</p>

```<code>SELECT T1.*
  FROM T1
  WHERE T1.use_t2 = FALSE
  AND T1.value2 = 'variable2'
  AND T1.value3 = 'variable3'
UNION ALL
SELECT T2.*
  FROM T1 JOIN T2 ON T1.value = T2.value
  WHERE T1.use_t2 = TRUE
  AND T2.value2 = 'variable2'
  AND T2.value3 = 'variable3'
</code>```

OwnerDisplayName: Arni Gunnar Ragnarsson

Body:
I am using SQL Server 2005. I am trying to join 2 tables together, but only when a column value in the main table is true. Like this:

select * from T1
join T2 on T1.value = T2.value
where T2.value2 = 'variable2'
and T2.value3 = 'variable3'

There is a column value in T1 which says if I have to use the values in T2. I could to a case around the where clause, but it will always join to the table, and if the value in T1 is false, there are no values in T2 to join to, so the select returns no rows.

You can't put a case around the join, so I am a little bit stuck with this ... can anyone help ?

Body:
What, if any, are the performance considerations related to conditional joins, I wonder? Is it equivalent to a UNION like this:

SELECT T1.*
  FROM T1
  WHERE T1.use_t2 = FALSE
  AND T1.value2 = 'variable2'
  AND T1.value3 = 'variable3'
UNION ALL
SELECT T2.*
  FROM T1 JOIN T2 ON T1.value = T2.value
  WHERE T1.use_t2 = TRUE
  AND T2.value2 = 'variable2'
  AND T2.value3 = 'variable3'

OwnerDisplayName: Mike Woodhouse


问:
Sum diff problem/bug in XSLT 1.0
I have this XML data and try and make a sum of it using the XSLT snippet below.

Xml

```<code><?xml version="1.0" encoding="utf-8"?>
<values>
    <value>159.14</value>
    <value>-2572.50</value>
    <value>-2572.50</value>
    <value>2572.50</value>
    <value>2572.50</value>
    <value>-159.14</value>
</values>
</code>```

Xslt

```<code><?xml version="1.0" encoding="utf-8"?>

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
    <xsl:value-of select="sum(values/value)"/>
</xsl:template>

</xsl:stylesheet>
</code>```

In my world the value should then be 0 but it ends up being -0.0000000000005684341886080801

Run it in Visual Studio and see for yourself. Why? is this happening?

答:
Try this</p>

```<code><xsl:value-of select="format-number(sum(values/value),'0.00')"/>
</code>```

Title: Sum diff problem/bug in XSLT 1.0

Body:
I have this XML data and try and make a sum of it using the XSLT snippet below.

Xml

<?xml version="1.0" encoding="utf-8"?>
<values>
    <value>159.14</value>
    <value>-2572.50</value>
    <value>-2572.50</value>
    <value>2572.50</value>
    <value>2572.50</value>
    <value>-159.14</value>
</values>

Xslt

<?xml version="1.0" encoding="utf-8"?>

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
    <xsl:value-of select="sum(values/value)"/>
</xsl:template>

</xsl:stylesheet>

In my world the value should then be 0 but it ends up being -0.0000000000005684341886080801

Run it in Visual Studio and see for yourself. Why? is this happening?

Body:
Try this

<xsl:value-of select="format-number(sum(values/value),'0.00')"/>


问:
How can i pass Data into my SQLite-Database
Hello there :)  I am pretty new to programming and I recently started an IONIC App. However I got stuck. I want to do something like a phone book where you can get random JSON contacts and save them to your sqlite database.

I got this:

```<code>import { Storage ] from '@ionic/storage';
    @component({
        selector: 'page-home'
        templateUrl: 'home.html'
});

export class HomePage {

  posts: any;
  persons: any;

constructor(public navCtrl: NavController, public http: Http, public storage: Storage) {

  this.http.get('https://jsonplaceholder.typicode.com/users').map(res=> res.json()).subscribe(data => {
  this.posts = data;
 });

}

//here i would like to recieve the data from the tapped Item

  setData(){
    console.log();
        this.storage.set('myData', this.posts);
        console.log(this.posts);
  };

  getData(){
     this.storage.get('myData').then((data) => {
       if (data !=null){
         console.log(data);
       }
    })
  };
}
</code>```

Here is the View:
When i click / tap the save-button i would like to store the values in my sqlite-database and display them in my "local contacts".

```<code><ion-content>
        <ion-list>
            <ion-item *ngFor="let post of posts">
                <ion-list>
                    <ul><h1>{{post.name}}</h1></ul>
                    <ul><p>{{post.username}}, {{post.email}}</p></ul>
                    <ul><p>phone: {{post.phone}}</p></ul>
                    <button ion-button (click)="setData()">Set Data</button>
                </ion-list>
            </ion-item>
        </ion-list>
    </ion-content>
</code>```

Maybe someone faced similar problems and can help me with this.
Thanks :)

答:
The best way to handle persistent storage with Ionic is using ionic-storage.

Ionic Storage is a package created and maintained by the ionic team to abstract development from the specifics of each browser or platform and automatically use the best storage solution available.

1. Installing Dependencies

In your case for SQLite you need to first install the dependencies for both Angular and Cordova:

npm install @ionic/storage --save

and

cordova plugin add cordova-sqlite-storage --save

Then edit your NgModule declaration in src/app/app.module.ts to add IonicStorageModule as an import:

import { IonicStorageModule } from '@ionic/storage';

@NgModule({
  declarations: [...],
  imports: [
    IonicModule.forRoot(MyApp),
    IonicStorageModule.forRoot({
      name: '__mydb',
      driverOrder: ['indexeddb', 'sqlite', 'websql'],
    })
  ],
  bootstrap: [...],
  entryComponents: [...],
  providers: [...],
})
export class AppModule { }
```
<br>
<h1>2. Inject Storage into your component </h1>
```import { Component } from '@angular/core';
import { Storage } from '@ionic/storage';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  constructor(public storage: Storage) {}
}
```
<br>
<h1>3. Storing data in SQLite</h1>
<p>Whenever you access storage, make sure to always wrap your code in the following:</p>
```storage.ready().then(() => { /* code here safely */});
```
<h3>3.1 Saving a key-value pair</h3>
```storage.ready().then(() => {
    storage.set('some key', 'some value');
});
```
<h3>3.2 Retrieving a value</h3>
```storage.ready().then(() => {
  storage.get('age').then((val: string) => {
      console.log('Your age is', val);
  });
});
```
<h3>3.3 Deleting a key-value pair</h3>
```storage.ready().then(() => {
    storage.remove('key').then((key: string) => { /* do something after deletion */})
});
```

Body:
Hello there :)  I am pretty new to programming and I recently started an IONIC App. However I got stuck. I want to do something like a phone book where you can get random JSON contacts and save them to your sqlite database.

I got this:

import { Storage ] from '@ionic/storage';
    @component({
        selector: 'page-home'
        templateUrl: 'home.html'
});

export class HomePage {

  posts: any;
  persons: any;

constructor(public navCtrl: NavController, public http: Http, public storage: Storage) {

  this.http.get('https://jsonplaceholder.typicode.com/users').map(res=> res.json()).subscribe(data => {
  this.posts = data;
 });

}

//here i would like to recieve the data from the tapped Item

  setData(){
    console.log();
        this.storage.set('myData', this.posts);
        console.log(this.posts);
  };

  getData(){
     this.storage.get('myData').then((data) => {
       if (data !=null){
         console.log(data);
       }
    })
  };
}

Here is the View:
When i click / tap the save-button i would like to store the values in my sqlite-database and display them in my "local contacts".

<ion-content>
        <ion-list>
            <ion-item *ngFor="let post of posts">
                <ion-list>

{{post.name}}

{{post.username}}, {{post.email}}

phone: {{post.phone}}

                    <button ion-button (click)="setData()">Set Data</button>
                </ion-list>
            </ion-item>
        </ion-list>
    </ion-content>

Maybe someone faced similar problems and can help me with this.
Thanks :)

Body:
The best way to handle persistent storage with Ionic is using ionic-storage.

Ionic Storage is a package created and maintained by the ionic team to abstract development from the specifics of each browser or platform and automatically use the best storage solution available.

1. Installing Dependencies

In your case for SQLite you need to first install the dependencies for both Angular and Cordova:

npm install @ionic/storage --save

and

cordova plugin add cordova-sqlite-storage --save

Then edit your NgModule declaration in src/app/app.module.ts to add IonicStorageModule as an import:

import { IonicStorageModule } from '@ionic/storage';

@NgModule({
  declarations: [...],
  imports: [
    IonicModule.forRoot(MyApp),
    IonicStorageModule.forRoot({
      name: '__mydb',
      driverOrder: ['indexeddb', 'sqlite', 'websql'],
    })
  ],
  bootstrap: [...],
  entryComponents: [...],
  providers: [...],
})
export class AppModule { }

2. Inject Storage into your component

import { Component } from '@angular/core';
import { Storage } from '@ionic/storage';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  constructor(public storage: Storage) {}
}

3. Storing data in SQLite

Whenever you access storage, make sure to always wrap your code in the following:

storage.ready().then(() => { /* code here safely */});

3.1 Saving a key-value pair

storage.ready().then(() => {
    storage.set('some key', 'some value');
});

3.2 Retrieving a value

storage.ready().then(() => {
  storage.get('age').then((val: string) => {
      console.log('Your age is', val);
  });
});

3.3 Deleting a key-value pair

storage.ready().then(() => {
    storage.remove('key').then((key: string) => { /* do something after deletion */})
});


问:
How to parse AJAX by cURL?
I am trying to parse this url:

https://halykbank.kz/presscenter/novosti
```

<p>The news are loaded by AJAX. In network I found URL, that must show loaded news, but there only </p>

```{"result":false,"hint":"NO_AUTHORIZATION_DATA"}
```

<p>Why I am getting this? Here the URL, that I think must show me loaded news:</p>

<pre class="lang-none prettyprint-override"><code>https://backend.halykbank.kz/struct/category-items?categoryId=199&sort=position%20desc&offset=200&limit=100
</code>```

答:
```<code>composer require guzzlehttp/guzzle:~6.0

$client = new GuzzleHttp\Client();
$res = $client->get('https://api.github.com/user', ['auth' =>  ['user', 'pass']]);
echo $res->getStatusCode(); // 200
$json_string = $res->getBody();

$json_obj = json_decode($json_string); //return Object<BR>
$json_arr = json_decode($json_string,true); //return Array
</code>```

Title: How to parse AJAX by cURL?

Body:
I am trying to parse this url:

https://halykbank.kz/presscenter/novosti

The news are loaded by AJAX. In network I found URL, that must show loaded news, but there only

{"result":false,"hint":"NO_AUTHORIZATION_DATA"}

Why I am getting this? Here the URL, that I think must show me loaded news:

https://backend.halykbank.kz/struct/category-items?categoryId=199&sort=position%20desc&offset=200&limit=100


问:
Excel - SQL 'INSERT INTO' Query Syntax Error
I'm attempting a simple insertion query to an MS Access database with Data from Excel. I'm using a parameterized query with hardcoded values for testing. Running the query directly in Access works, but attempting to execute it via VBA results in a syntax error. The query is currently inserting every field except for the auto-generated ID in the Access table.

Sub Test_SQL()
    Dim conn As ADODB.Connection
    Dim cmd As ADODB.Command
    Dim result
    Dim id As Integer

    Dim year As Integer
    Dim month As String
    Dim combocode As String
    Dim credamt As Double
    Dim qty As Integer
    Dim itemcode As String
    Dim sepbundleamt As Double
    Dim prodname As String

    '*********query variables********************
    year = 2017
    month = "July"
    combocode = "COMBCOD1"
    credamt = 420
    qty = 21
    itemcode = "ITEMCOD1"
    sepbundleamt = 12
    prodname = "Test Product"

    '********open DB connection and execute insertion******
    On Error GoTo ErrorHandler

    Set conn = New ADODB.Connection
    Set cmd = New ADODB.Command
    With conn
        .Provider = "Microsoft.ACE.OLEDB.12.0;"
        .ConnectionString = [redacted]
        .Open
    End With

    With cmd
        .ActiveConnection = conn
        .CommandType = adCmdText
        .CommandText = "INSERT INTO SB_DSLR (Year, Month, ComboCode, CreditAmt, Qty, ItemCode, SepBundleAmt, ProductName) VALUES (?,?,?,?,?,?,?,?);"
    End With
    With cmd.Parameters
        .Append cmd.CreateParameter("Year", adInteger, adParamInput, 4, year)
        .Append cmd.CreateParameter("Month", adWChar, adParamInput, 10, month)
        .Append cmd.CreateParameter("ComboCode", adWChar, adParamInput, 10, combocode)
        .Append cmd.CreateParameter("CreditAmt", adDouble, adParamInput, 10, credamt)
        .Append cmd.CreateParameter("Qty", adInteger, adParamInput, 10, qty)
        .Append cmd.CreateParameter("ItemCode", adWChar, adParamInput, 8, itemcode)
        .Append cmd.CreateParameter("SepBundleAmt", adDouble, adParamInput, 10, sepbundleamt)
        .Append cmd.CreateParameter("ProductName", adWChar, adParamInput, 100, prodname)
    End With

    cmd.Execute
    conn.Close
    Set cmd = Nothing
    Exit Sub

ErrorHandler:
    MsgBox (Err.Number & ": " & Err.Description)
    If conn.State = adStateOpen Then
        conn.Close
    End If
    Set cmd = Nothing
End Sub
```

答:
There are multiple reasons for that general error but the fact that same query works in the MSAccess.exe suggests reserved words is the cause.

Indeed, Month and Year are Jet reserved words and Year is an MS Access reserved word. Both are named functions and parameters to other methods. Sometimes the .exe can be lenient whereas ODBC connections are more restrictive. Therefore, consider escaping such words with backticks or square brackets, or altogether avoiding such words.

.CommandText = "INSERT INTO SB_DSLR (`Year`, `Month`, ComboCode, CreditAmt, Qty, ItemCode, SepBundleAmt, ProductName) VALUES (?,?,?,?,?,?,?,?);"

.CommandText = "INSERT INTO SB_DSLR ([Year], [Month], ComboCode, CreditAmt, Qty, ItemCode, SepBundleAmt, ProductName) VALUES (?,?,?,?,?,?,?,?);"
```


答:
What you are seeing is expected. This is because of text nodes which are a little less obvious than other elements. Looking at your html:

```<code><div id="dad">
    <p>son</p>
    <p>son</p>
</div>
</code>```

You have your #dad div, inside of which are 3 text nodes and 2 element notes. Can you spot the text nodes now? (hint, new lines and tabs are text). For this reason, many browsers now implement firstElementChild.

You can also check to make sure the nodeType === 1 before modifying it. You can read about the different node types here. You can also remove all the white space, but this makes for hard to read code:

```<code><div id="dad"><p>son</p><p>son</p></div>
</code>```

Body:
What you are seeing is expected. This is because of text nodes which are a little less obvious than other elements. Looking at your html:

<div id="dad">
    <p>son</p>
    <p>son</p>
</div>

You have your #dad div, inside of which are 3 text nodes and 2 element notes. Can you spot the text nodes now? (hint, new lines and tabs are text). For this reason, many browsers now implement firstElementChild.

You can also check to make sure the nodeType === 1 before modifying it. You can read about the different node types here. You can also remove all the white space, but this makes for hard to read code:

<div id="dad"><p>son</p><p>son</p></div>


问:
Change fixed position on click
I'm going to try make it clear:

I have a mobile menu with media queries and a header fixed on mobile. The situation is the customer want the header (with logo) fixed on top, but when I try to expand the menu item (like Menu > SubMenu > Submenu) it expand vertically but I can not scroll to bottom (the page is scrolling behind it, but not the menu). So I figured out how to make it work: When the site loads the header is fixed, but when someone tries to use the top menu, they must click on the hamburger menu and (this what I want you to help me), and when they click on the hamburger menu the header should pass from position:fixed to position:static, just then the mobile menu will scroll down as I want.

Here the site: http://centro.anden.pe

Any ideas? Thank you in advance.

答:
You didn't attached code, but here's a functional example of that idea (click on the hamburguer menu)

$(document).ready(function() {

      $("#hamburguer_menu").on("click", function() {
        $("#change-div-if-click").css("background-color", "yellow")
        $("#change-div-if-click").css("position", "static")
        alert ('now the position is static')
      });

    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#hamburguer_menu {
      height: 60px;
      width: 60px;
      background-color: yellow;
    }

    #change-div-if-click {
      background-color: teal;
    }
    </code>```

Change when clicked

    ```

Title: Change fixed position on click

Body:
You didn't attached code, but here's a functional example of that idea (click on the hamburguer menu)

$(document).ready(function() {

      $("#hamburguer_menu").on("click", function() {
        $("#change-div-if-click").css("background-color", "yellow")
        $("#change-div-if-click").css("position", "static")
        alert ('now the position is static')
      });

    });

#hamburguer_menu {
      height: 60px;
      width: 60px;
      background-color: yellow;
    }

    #change-div-if-click {
      background-color: teal;
    }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

    <body>

    <div id="hamburguer_menu">
      <img src="https://www.iconfinder.com/data/icons/tupix-1/30/list-512.png" / height="60px" width="60px">
    </div>

    <div id="change-div-if-click">
      <p>Change when clicked</p>
    </div>

    </body>

    </html>


问:
How to sort NSMutableOrderedSet alphabetically?
I want to sort an NSMutableOrderedSet of strings, alphabetically.  Is there a method?  I've searched but can't find any.

Looking for something like this if it was an array:

```<code>sortedArray = [originalArray sortedArrayUsingSelector:@selector
 (localizedCaseInsensitiveCompare:)];
</code>```

答:
Use localizedStandardCompare instead of localizedCaseInsensitiveCompare, suppose you want 1, 2, 3, 4, 5 ...., 100 or more, then after 9 localizedCaseInsensitiveCompare is not able to sort your set, it will print like 1,10,2... etc. but localizedStandardCompare will sort accurately.

```<code>[nameOfSet sortUsingComparator:(NSComparator)^(id obj1, id obj2){
        return [obj1 localizedStandardCompare:obj2]; }];
</code>```

Thanks

Body:
I want to sort an NSMutableOrderedSet of strings, alphabetically.  Is there a method?  I've searched but can't find any.

Looking for something like this if it was an array:

sortedArray = [originalArray sortedArrayUsingSelector:@selector
 (localizedCaseInsensitiveCompare:)];

Body:
Use localizedStandardCompare instead of localizedCaseInsensitiveCompare, suppose you want 1, 2, 3, 4, 5 ...., 100 or more, then after 9 localizedCaseInsensitiveCompare is not able to sort your set, it will print like 1,10,2... etc. but localizedStandardCompare will sort accurately.

[nameOfSet sortUsingComparator:(NSComparator)^(id obj1, id obj2){
        return [obj1 localizedStandardCompare:obj2]; }];

Thanks