问:
document.ready not working on linking a page through ahref
The document only loads when the page is hit directly with its url, it does not work if the page is loaded through an ahref link.

```<code>$(document).ready(function(){
alert( "document loaded" );
});
</code>```

I know this has been asked before and I tried a few things and nothing worked. The window also does not get loaded on opening a page through a link

```<code>$( window ).on( "load", function() {
  alert( "window loaded" );
});
</code>```

I also tried pageinit, not sure if I used it wrong but it did not work.
Any help will be appreciated

Also, I am using rails

My application

    <meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/>
    <title>DevPortal</title>
    <%= csrf_meta_tags %>
    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>

    <%= yield %>

```
</div>
</div>
</p>

<p>I link my one page to another using the following code snippet:</p>

```

    My link

```

答:
This worked for me as I was using turbolinks</p>

```<code>$(document).on('turbolinks:load', function() {
   alert("It works");
});
</code>```

Body:
The document only loads when the page is hit directly with its url, it does not work if the page is loaded through an ahref link.

$(document).ready(function(){
alert( "document loaded" );
});

I know this has been asked before and I tried a few things and nothing worked. The window also does not get loaded on opening a page through a link

$( window ).on( "load", function() {
  alert( "window loaded" );
});

I also tried pageinit, not sure if I used it wrong but it did not work.
Any help will be appreciated

Also, I am using rails

My application

    <meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/>
    <title>DevPortal</title>
    <%= csrf_meta_tags %>
    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>

    <%= yield %>

I link my one page to another using the following code snippet:

    My link

Body:
This worked for me as I was using turbolinks

$(document).on('turbolinks:load', function() {
   alert("It works");
});


来源: stackexchange

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

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

答:
You don't need Jquery for this, just use plain JS. There are multiple ways of doing this. The easiest is:

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

You may also want to load is using JSON, especially if its variable and from a file.

```<code>var newObjectString = // the data from the file.
var newObject = JSON.parse(newObjectString)
</code>```

ContentLicense: CC BY-SA 3.0

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

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

Body:
You don't need Jquery for this, just use plain JS. There are multiple ways of doing this. The easiest is:

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

You may also want to load is using JSON, especially if its variable and from a file.

var newObjectString = // the data from the file.
var newObject = JSON.parse(newObjectString)


问:
.htaccess Multiple Rewrite Rule overwriting issue
First all i'm not an expert of .htaccess and Rewrite Rules.

I have some Rewrite rules and all of them are working.
When i added new rules; it's overwriting other rules and redirecting wrong page

```<code>RewriteRule ^([^/]+)/([0-9]+)/?$ article-list.php?link=$1&page=$2 [L,QSA,NC]
RewriteRule ^([^/]+)/?$ article-list.php?link=$1 [L,QSA]
RewriteRule ^videolar/$ video-list.php?page=$1 [L,QSA]
</code>```

When i try to hit url www.mywebpage.com/videolar/1

Unfourtunately it's redirecting to article-list.php page.

Is there any way to resolve the issue?

Any help will greatly appricated.

Full Htaccess;

```<code>Options +FollowSymLinks -MultiViews

RewriteEngine On
RewriteBase /

RewriteRule ^uye-ol/?$ register.php [L,NC]
RewriteRule ^uye-girisi/?$ login.php [L,NC]
RewriteRule ^sifremi-unuttum/?$ forget-password.php [L,NC]
RewriteRule ^yazarlar/?$ writer-list.php [L,NC]
RewriteRule ^videolar/?$ video-list.php?page=$1 [L,QSA]
RewriteRule ^foto-galeri/?$ gallery-list.php [L,NC]
RewriteRule ^biyografiler/?$ biography-list.php [L,NC]
RewriteRule ^yazar/([^/]+)-([^/]+)/([^/]+)-([^/]+)/?$ writer-article.php?link=$1&writerId=$2&articleLink=$3&writerArticleId=$4 [L,QSA]
RewriteRule ^yazar/([^/]+)-([0-9]+)/([0-9]+)/?$ writer-article-list.php?link=$1&writerId=$2&page=$3 [L,QSA]
RewriteRule ^foto-galeri/([0-9]+)/?$ gallery-list.php?page=$1 [L,QSA]
RewriteRule ^foto-galeri/([^/]+)-([^/]+)/([^/]+)/?$ gallery-photo.php?link=$1&i=$2&photo=$3 [L,QSA]
RewriteRule ^videolar/([^/]+)-([^/]+)/?$ video.php?link=$1&i=$2 [L,QSA]
RewriteRule ^haber/([^/]+)-([^/]+)/?$ article.php?link=$1&i=$2 [L,QSA]
RewriteRule ^biyografi/([^/]+)-([^/]+)/?$ biography.php?link=$1&bioId=$2 [L,QSA]
RewriteRule ^([^/]+)/([0-9]+)/?$ article-list.php?link=$1&page=$2 [L,QSA,NC]
RewriteRule ^([^/]+)/?$ article-list.php?link=$1 [L,QSA]
RewriteRule ^videolar/$ video-list.php?page=$1 [L,QSA]
</code>```

答:
```<code>RewriteRule ^([^/]+)/([0-9]+)/?$ article-list.php?link=$1&page=$2 [L,QSA,NC]
RewriteRule ^([^/]+)/?$ article-list.php?link=$1 [L,QSA]
RewriteRule ^videolar/$ video-list.php?page=$1 [L,QSA]
</code>```

You need to change the order of these directives so that the most specific is first. As it stands, the first directive matches the URL /videolar/1 and so "wins".

However, the last rule you have won't match /videolar/1 either (it will only match /videolar/), so the pattern needs to be modified.

Try something like the following instead:

```<code>RewriteRule ^videolar/([0-9]+)/?$ video-list.php?page=$1 [L,QSA]
RewriteRule ^([^/]+)/([0-9]+)/?$ article-list.php?link=$1&page=$2 [L,QSA,NC]
RewriteRule ^([^/]+)/?$ article-list.php?link=$1 [L,QSA]
</code>```

Body:
First all i'm not an expert of .htaccess and Rewrite Rules.

I have some Rewrite rules and all of them are working.
When i added new rules; it's overwriting other rules and redirecting wrong page

RewriteRule ^([^/]+)/([0-9]+)/?$ article-list.php?link=$1&page=$2 [L,QSA,NC]
RewriteRule ^([^/]+)/?$ article-list.php?link=$1 [L,QSA]
RewriteRule ^videolar/$ video-list.php?page=$1 [L,QSA]

When i try to hit url www.mywebpage.com/videolar/1

Unfourtunately it's redirecting to article-list.php page.

Is there any way to resolve the issue?

Any help will greatly appricated.

Full Htaccess;

Options +FollowSymLinks -MultiViews

RewriteEngine On
RewriteBase /

RewriteRule ^uye-ol/?$ register.php [L,NC]
RewriteRule ^uye-girisi/?$ login.php [L,NC]
RewriteRule ^sifremi-unuttum/?$ forget-password.php [L,NC]
RewriteRule ^yazarlar/?$ writer-list.php [L,NC]
RewriteRule ^videolar/?$ video-list.php?page=$1 [L,QSA]
RewriteRule ^foto-galeri/?$ gallery-list.php [L,NC]
RewriteRule ^biyografiler/?$ biography-list.php [L,NC]
RewriteRule ^yazar/([^/]+)-([^/]+)/([^/]+)-([^/]+)/?$ writer-article.php?link=$1&writerId=$2&articleLink=$3&writerArticleId=$4 [L,QSA]
RewriteRule ^yazar/([^/]+)-([0-9]+)/([0-9]+)/?$ writer-article-list.php?link=$1&writerId=$2&page=$3 [L,QSA]
RewriteRule ^foto-galeri/([0-9]+)/?$ gallery-list.php?page=$1 [L,QSA]
RewriteRule ^foto-galeri/([^/]+)-([^/]+)/([^/]+)/?$ gallery-photo.php?link=$1&i=$2&photo=$3 [L,QSA]
RewriteRule ^videolar/([^/]+)-([^/]+)/?$ video.php?link=$1&i=$2 [L,QSA]
RewriteRule ^haber/([^/]+)-([^/]+)/?$ article.php?link=$1&i=$2 [L,QSA]
RewriteRule ^biyografi/([^/]+)-([^/]+)/?$ biography.php?link=$1&bioId=$2 [L,QSA]
RewriteRule ^([^/]+)/([0-9]+)/?$ article-list.php?link=$1&page=$2 [L,QSA,NC]
RewriteRule ^([^/]+)/?$ article-list.php?link=$1 [L,QSA]
RewriteRule ^videolar/$ video-list.php?page=$1 [L,QSA]

Body:
RewriteRule ^([^/]+)/([0-9]+)/?$ article-list.php?link=$1&page=$2 [L,QSA,NC]
RewriteRule ^([^/]+)/?$ article-list.php?link=$1 [L,QSA]
RewriteRule ^videolar/$ video-list.php?page=$1 [L,QSA]

You need to change the order of these directives so that the most specific is first. As it stands, the first directive matches the URL /videolar/1 and so "wins".

However, the last rule you have won't match /videolar/1 either (it will only match /videolar/), so the pattern needs to be modified.

Try something like the following instead:

RewriteRule ^videolar/([0-9]+)/?$ video-list.php?page=$1 [L,QSA]
RewriteRule ^([^/]+)/([0-9]+)/?$ article-list.php?link=$1&page=$2 [L,QSA,NC]
RewriteRule ^([^/]+)/?$ article-list.php?link=$1 [L,QSA]


问:
Trouble with adding multiple values into array
I'm trying to learn more about arrays and so I just wrote this simple function:
(I'm calling doThis from an onClick for testing purposes).

```<code>function doThis() {
    var multiplier = 3;
    var list = [23, 54, 23, 25, 65];
    var products = multiply(list, multiplier);
    console.log(products);
}
function multiply(list, multiplier) {
    list.forEach(function (element){
        var multi = [element * multiplier];
        console.log(multi);
        return multi;
    });
}
</code>```

My issue is two-fold:

var products is returning undefined.

When I step through the code in the debugger, it shows the arithmetic being done correctly, but it doesn't store more than one value in the variable multi.

The end goal would be to have var products hold the multi array.

答:
You could use a for loop while you're learning about arrays:

```<code>function multiply(list, multiplier) {
    var multi = [];
    for (i = 0; i < list.length; i++) {
        multi.push(list[i] * multiplier)
    }

    return multi;
}
</code>```

Body:
I'm trying to learn more about arrays and so I just wrote this simple function:
(I'm calling doThis from an onClick for testing purposes).

function doThis() {
    var multiplier = 3;
    var list = [23, 54, 23, 25, 65];
    var products = multiply(list, multiplier);
    console.log(products);
}
function multiply(list, multiplier) {
    list.forEach(function (element){
        var multi = [element * multiplier];
        console.log(multi);
        return multi;
    });
}

My issue is two-fold:

var products is returning undefined.

When I step through the code in the debugger, it shows the arithmetic being done correctly, but it doesn't store more than one value in the variable multi.

The end goal would be to have var products hold the multi array.

Body:
You could use a for loop while you're learning about arrays:

function multiply(list, multiplier) {
    var multi = [];
    for (i = 0; i < list.length; i++) {
        multi.push(list[i] * multiplier)
    }

    return multi;
}


问:
Undefined index errors (PHP)
I'm getting notices of an undefined index "id" on lines 3, 6 and 7 in this code. I can't figure out what I'm doing wrong:

```<code>    if ( isset($_POST['action']) && $_POST['action'] == 'save' ) {
    foreach ($options as $value) {
        if(($value['type'] === "checkbox" or $value['type'] === "multiselect" ) and is_array($_REQUEST[ $value['id'] ]))
            { $_REQUEST[ $value['id'] ]=implode(',',$_REQUEST[ $value['id'] ]); //This will take from the array and make one string
            }
        $key = $value['id'];
        $val = $_REQUEST[$key];
        $settings[$key] = $val;
    }
</code>```

I'm thinking this is a small thing to fix but haven't had any luck with anything I've tried. One thing I did do is run var_dump($key) and sometimes $key is null and sometimes it's not. So I'm assuming it has to do with this.

This is part of an options page for a WordPress theme, by the way. This is the code that runs as part of the "save" function.

The script actually works properly if debug mode is turned off, but when debug mode is on, these notices pop up when hitting the save button on the options page. Thanks in advance for any insights, and let me know if I need to post more code to give more context.

EDIT: I've posted the options page in pastebin. It's long. It contains t13lo's fixes. The problem code is on line 1957. Thanks: http://pastebin.com/NGX6qzgr

答:
Have no idea what your code is suppose to be doing, but based on what you've posted give this a shot.. (replacing obviously just the foreach loop part of your code)..

```<code>foreach ($options as $value) {
    if( !isset( $value['id'] ) )
        continue;
    if( !isset( $_REQUEST[$value['id']] ) ) {
        $settings[$value['id']] = '';
        continue;
    }
    if( $value['type'] === "checkbox" || $value['type'] === "multiselect" ) {
        // No isset check here, the top conditional catches non-set items
        if( is_array( $_REQUEST[$value['id']] ) )
            $_REQUEST[$value['id']] = implode( ',', $_REQUEST[$value['id']] );
    }
    $settings[$value['id']] = $_REQUEST[$value['id']];
}
</code>```

Should do exactly the same as before, with exception to checking vars are set first, at also setting a value in the $settings array to an empty string when the matching $_REQUEST var isn't set.. (assuming i'm following what the code is doing correctly that is)..

EDIT: Following discussion in comments i've updated the code above, that should fix the notice on line 1957. It makes sense for that key not to be set for your code, not all the array items in $options are actually options, some refer to headings/tabs(whatever) that get output on your theme's options page(so it makes sense to skip them in the loop above).

I think that will solve your problem, but having said that i think it's important to point out that the code in that function is not ideal, the whole saving mechanism doesn't look very well sanitized overall. I'd be inclined to suggest setting the required capability for that page to manage_options so it's restricted to administrators at least until such time a replacement can be put in place(suggestions for which should be in a seperate question, and ideally on WPSE).

ContentLicense: CC BY-SA 2.5

Title: Undefined index errors (PHP)

Body:
I'm getting notices of an undefined index "id" on lines 3, 6 and 7 in this code. I can't figure out what I'm doing wrong:

    if ( isset($_POST['action']) && $_POST['action'] == 'save' ) {
    foreach ($options as $value) {
        if(($value['type'] === "checkbox" or $value['type'] === "multiselect" ) and is_array($_REQUEST[ $value['id'] ]))
            { $_REQUEST[ $value['id'] ]=implode(',',$_REQUEST[ $value['id'] ]); //This will take from the array and make one string
            }
        $key = $value['id'];
        $val = $_REQUEST[$key];
        $settings[$key] = $val;
    }

I'm thinking this is a small thing to fix but haven't had any luck with anything I've tried. One thing I did do is run var_dump($key) and sometimes $key is null and sometimes it's not. So I'm assuming it has to do with this.

This is part of an options page for a WordPress theme, by the way. This is the code that runs as part of the "save" function.

The script actually works properly if debug mode is turned off, but when debug mode is on, these notices pop up when hitting the save button on the options page. Thanks in advance for any insights, and let me know if I need to post more code to give more context.

EDIT: I've posted the options page in pastebin. It's long. It contains t13lo's fixes. The problem code is on line 1957. Thanks: http://pastebin.com/NGX6qzgr

Body:
Have no idea what your code is suppose to be doing, but based on what you've posted give this a shot.. (replacing obviously just the foreach loop part of your code)..

foreach ($options as $value) {
    if( !isset( $value['id'] ) )
        continue;
    if( !isset( $_REQUEST[$value['id']] ) ) {
        $settings[$value['id']] = '';
        continue;
    }
    if( $value['type'] === "checkbox" || $value['type'] === "multiselect" ) {
        // No isset check here, the top conditional catches non-set items
        if( is_array( $_REQUEST[$value['id']] ) )
            $_REQUEST[$value['id']] = implode( ',', $_REQUEST[$value['id']] );
    }
    $settings[$value['id']] = $_REQUEST[$value['id']];
}

Should do exactly the same as before, with exception to checking vars are set first, at also setting a value in the $settings array to an empty string when the matching $_REQUEST var isn't set.. (assuming i'm following what the code is doing correctly that is)..

EDIT: Following discussion in comments i've updated the code above, that should fix the notice on line 1957. It makes sense for that key not to be set for your code, not all the array items in $options are actually options, some refer to headings/tabs(whatever) that get output on your theme's options page(so it makes sense to skip them in the loop above).

I think that will solve your problem, but having said that i think it's important to point out that the code in that function is not ideal, the whole saving mechanism doesn't look very well sanitized overall. I'd be inclined to suggest setting the required capability for that page to manage_options so it's restricted to administrators at least until such time a replacement can be put in place(suggestions for which should be in a seperate question, and ideally on WPSE).


问:
what is the use of Zone.js in Angular 2
Currently am learning Angular 2.0 and i come accross the file Zone.js, and i would like to know what is the purpose of the file Zone.js and how will it make my application better.

答: Zone.js uses for async calls and internally for the error and stack trace angular 2 is using it. So you cannot ignore this script.</p>

Title: what is the use of Zone.js in Angular 2

ContentLicense: CC BY-SA 4.0


问:
Make a box and store the input in a variable tkinter
I'm trying to make a ping tool with a GUI on tkinter. The thing is that i would like to create a box where you could enter a web domain and then click ping and ping to that web. right now I have to change the web to ping on the code (V1.0) but i really tried to make the changes mentioned above but they don`t seem to work.

This is the original code:

```<code>#Imports
from subprocess import Popen, PIPE, STDOUT
import Tkinter as tk
from Tkinter import Tk
from threading import Thread

def create_worker(target):
    return Thread(target=target)

def start_worker(worker):
    worker.start()

#Ping printed on tkinter window root
def commande():
    cmd = 'ping -c 10 google.com'
    p = Popen(cmd.split(), stdout=PIPE, stderr=STDOUT)
    for line in iter(p.stdout.readline, ''):
    result.configure(text=line)

#tkinter code
root = Tk()
root.title('PingTool')
root.geometry('450x70+400+400')

worker = create_worker(commande)
tk.Button(root, text='Ping', command=lambda:start_worker(worker)).pack()

result = tk.Label(root)
result.pack()

root.mainloop()
</code>```

One not working version:

```<code>from subprocess import Popen, PIPE, STDOUT
import Tkinter as tk
from Tkinter import Tk
from threading import Thread

#intput on the console
u = input('Website to ping: ')

def create_worker(target):
    return Thread(target=target)

def start_worker(worker):
    worker.start()

def commande():
    cmd = 'ping -c 10 ' + u
    p = Popen(cmd.split(), stdout=PIPE, stderr=STDOUT)#
    for line in iter(p.stdout.readline, ''): #changes the text printed instead of printing multiple times
        result.configure(text=line)#

root = Tk()
root.title('PingTool')
root.geometry('450x70+400+400')

worker = create_worker(commande)
tk.Button(root, text='Ping', command=lambda: start_worker(worker)).pack()

result = tk.Label(root)
result.pack()

root.mainloop()
</code>```

The 'not working version' has the 'problem' that the input is written on the console. The idea is to create a label and input the text there.
I know this might not be the best place to ask something like this because it seems that i just want the work done but trust me I've really tried.
Thank you

PD: I'm starting with tkinter.

答:
subprocess.check_output should be enough for what you want to do https://pymotw.com/2/subprocess/index.html#module-subprocess  A simple program follows that runs the command when the button is pressed, and prints the output.  I'll leave something for you to do, i.e. configure the text on a Label http://effbot.org/tkinterbook/label.htm and also you should add some code for an entry that is not a valid website.</p>

```<code>import sys
if sys.version_info[0] < 3:
    import Tkinter as tk     ## Python 2.x
else:
    import tkinter as tk     ## Python 3.x

import subprocess

def button_callback():
    ent_contents=ent.get()
    output=subprocess.check_output("ping -c 10 "+ent_contents,
                                    shell=True)
    print "*****after", output, "\n"

root=tk.Tk()
ent=tk.Entry(root)
ent.grid(row=0, column=0)
ent.focus_set()

tk.Button(root, text="ping website", bg="lightblue",
          command=button_callback).grid(row=1, column=0)
tk.Button(root, text="Exit Program", bg="orange",
          command=root.quit).grid(row=2, column=0)

root.mainloop()
</code>```

Body:
I'm trying to make a ping tool with a GUI on tkinter. The thing is that i would like to create a box where you could enter a web domain and then click ping and ping to that web. right now I have to change the web to ping on the code (V1.0) but i really tried to make the changes mentioned above but they don`t seem to work.

This is the original code:

#Imports
from subprocess import Popen, PIPE, STDOUT
import Tkinter as tk
from Tkinter import Tk
from threading import Thread

def create_worker(target):
    return Thread(target=target)

def start_worker(worker):
    worker.start()

#Ping printed on tkinter window root
def commande():
    cmd = 'ping -c 10 google.com'
    p = Popen(cmd.split(), stdout=PIPE, stderr=STDOUT)
    for line in iter(p.stdout.readline, ''):
    result.configure(text=line)

#tkinter code
root = Tk()
root.title('PingTool')
root.geometry('450x70+400+400')

worker = create_worker(commande)
tk.Button(root, text='Ping', command=lambda:start_worker(worker)).pack()

result = tk.Label(root)
result.pack()

root.mainloop()

One not working version:

from subprocess import Popen, PIPE, STDOUT
import Tkinter as tk
from Tkinter import Tk
from threading import Thread

#intput on the console
u = input('Website to ping: ')

def create_worker(target):
    return Thread(target=target)

def start_worker(worker):
    worker.start()

def commande():
    cmd = 'ping -c 10 ' + u
    p = Popen(cmd.split(), stdout=PIPE, stderr=STDOUT)#
    for line in iter(p.stdout.readline, ''): #changes the text printed instead of printing multiple times
        result.configure(text=line)#

root = Tk()
root.title('PingTool')
root.geometry('450x70+400+400')

worker = create_worker(commande)
tk.Button(root, text='Ping', command=lambda: start_worker(worker)).pack()

result = tk.Label(root)
result.pack()

root.mainloop()

The 'not working version' has the 'problem' that the input is written on the console. The idea is to create a label and input the text there.
I know this might not be the best place to ask something like this because it seems that i just want the work done but trust me I've really tried.
Thank you

PD: I'm starting with tkinter.

Body:
subprocess.check_output should be enough for what you want to do https://pymotw.com/2/subprocess/index.html#module-subprocess  A simple program follows that runs the command when the button is pressed, and prints the output.  I'll leave something for you to do, i.e. configure the text on a Label http://effbot.org/tkinterbook/label.htm and also you should add some code for an entry that is not a valid website.

import sys
if sys.version_info[0] < 3:
    import Tkinter as tk     ## Python 2.x
else:
    import tkinter as tk     ## Python 3.x

import subprocess

def button_callback():
    ent_contents=ent.get()
    output=subprocess.check_output("ping -c 10 "+ent_contents,
                                    shell=True)
    print "*****after", output, "\n"

root=tk.Tk()
ent=tk.Entry(root)
ent.grid(row=0, column=0)
ent.focus_set()

tk.Button(root, text="ping website", bg="lightblue",
          command=button_callback).grid(row=1, column=0)
tk.Button(root, text="Exit Program", bg="orange",
          command=root.quit).grid(row=2, column=0)

root.mainloop()


问:
How to create custom window chrome in wpf?
How can I create a basic custom window chrome for a WPF window, that doesn't include the close button and still a moveable and resizeable window?</p>

答:
I've just used the example below for .net 4.5 and it works very well. Interestingly, it uses a code behind for a resource dictionary for the click events. All you have to do is reference the resource dictionary in your app.xaml file and then assign the Window the Style CustomWindowStyle.  This was shamelessly stolen from http://www.eidias.com/blog/2014/1/27/restyle-your-window.

```<code><ResourceDictionary x:Class="WpfApp7.WindowStyle"
                    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <Style x:Key="CustomWindowStyle" TargetType="{x:Type Window}">
        <Setter Property="WindowChrome.WindowChrome">
            <Setter.Value>
                <WindowChrome CaptionHeight="30"
                              CornerRadius="4"
                              GlassFrameThickness="0"
                              NonClientFrameEdges="None"
                              ResizeBorderThickness="5"
                              UseAeroCaptionButtons="False" />
            </Setter.Value>
        </Setter>

        <Setter Property="BorderBrush" Value="Black" />
        <Setter Property="Background" Value="Gray" />

        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Window}">
                    <Grid>
                        <Border Background="{TemplateBinding Background}"
                                BorderBrush="{TemplateBinding BorderBrush}"
                                BorderThickness="5,30,5,5">
                            <AdornerDecorator>
                                <ContentPresenter />
                            </AdornerDecorator>
                        </Border>

                        <Grid Height="30"
                            VerticalAlignment="Top">

                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="Auto"/>
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="Auto"/>
                            </Grid.ColumnDefinitions>

                            <StackPanel Orientation="Horizontal" Margin="5,0">
                                <Button Content="A" Margin="0,0,5,0" VerticalAlignment="Center" Click="Button_Click" WindowChrome.IsHitTestVisibleInChrome="True"/>
                                <Button Content="B" Margin="0,0,5,0" VerticalAlignment="Center" Click="Button_Click" WindowChrome.IsHitTestVisibleInChrome="True"/>
                                <Button Content="C" Margin="0,0,5,0" VerticalAlignment="Center" Click="Button_Click" WindowChrome.IsHitTestVisibleInChrome="True"/>
                                <Button Content="D" Margin="0,0,5,0" VerticalAlignment="Center" Click="Button_Click" WindowChrome.IsHitTestVisibleInChrome="True"/>
                            </StackPanel>

                            <TextBlock Margin="5,0,0,0"
                                       VerticalAlignment="Center"
                                       HorizontalAlignment="Center"
                                       FontSize="16"
                                       Foreground="White"
                                       Text="{TemplateBinding Title}"
                                       Grid.Column="1"/>

                            <StackPanel Orientation="Horizontal"
                                        Grid.Column="2">
                                <Button x:Name="btnClose"
                                    Width="15"
                                    Margin="5"
                                    Click="CloseClick"
                                    Content="X"
                                    WindowChrome.IsHitTestVisibleInChrome="True" />

                                <Button x:Name="btnRestore"
                                    Width="15"
                                    Margin="5"
                                    Click="MaximizeRestoreClick"
                                    Content="#"
                                    WindowChrome.IsHitTestVisibleInChrome="True" />

                                <Button x:Name="btnMinimize"
                                    Width="15"
                                    Margin="5"
                                    VerticalContentAlignment="Bottom"
                                    Click="MinimizeClick"
                                    Content="_"
                                    WindowChrome.IsHitTestVisibleInChrome="True" />
                            </StackPanel>
                        </Grid>

                    </Grid>

                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>
</code>```

And for the code behind:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace WpfApp7
{
    public partial class WindowStyle : ResourceDictionary
    {
        public WindowStyle()
        {
            InitializeComponent();
        }

        private void CloseClick(object sender, RoutedEventArgs e)
        {
            var window = (Window)((FrameworkElement)sender).TemplatedParent;
            window.Close();
        }

        private void MaximizeRestoreClick(object sender, RoutedEventArgs e)
        {
            var window = (Window)((FrameworkElement)sender).TemplatedParent;
            if (window.WindowState == System.Windows.WindowState.Normal)
            {
                window.WindowState = System.Windows.WindowState.Maximized;
            }
            else
            {
                window.WindowState = System.Windows.WindowState.Normal;
            }
        }

        private void MinimizeClick(object sender, RoutedEventArgs e)
        {
            var window = (Window)((FrameworkElement)sender).TemplatedParent;
            window.WindowState = System.Windows.WindowState.Minimized;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Hello!");
        }
    }
}
</code>```

Body:
I've just used the example below for .net 4.5 and it works very well. Interestingly, it uses a code behind for a resource dictionary for the click events. All you have to do is reference the resource dictionary in your app.xaml file and then assign the Window the Style CustomWindowStyle.  This was shamelessly stolen from http://www.eidias.com/blog/2014/1/27/restyle-your-window.

<ResourceDictionary x:Class="WpfApp7.WindowStyle"
                    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <Style x:Key="CustomWindowStyle" TargetType="{x:Type Window}">
        <Setter Property="WindowChrome.WindowChrome">
            <Setter.Value>
                <WindowChrome CaptionHeight="30"
                              CornerRadius="4"
                              GlassFrameThickness="0"
                              NonClientFrameEdges="None"
                              ResizeBorderThickness="5"
                              UseAeroCaptionButtons="False" />
            </Setter.Value>
        </Setter>

        <Setter Property="BorderBrush" Value="Black" />
        <Setter Property="Background" Value="Gray" />

        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Window}">
                    <Grid>
                        <Border Background="{TemplateBinding Background}"
                                BorderBrush="{TemplateBinding BorderBrush}"
                                BorderThickness="5,30,5,5">
                            <AdornerDecorator>
                                <ContentPresenter />
                            </AdornerDecorator>
                        </Border>

                        <Grid Height="30"
                            VerticalAlignment="Top">

                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="Auto"/>
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="Auto"/>
                            </Grid.ColumnDefinitions>

                            <StackPanel Orientation="Horizontal" Margin="5,0">
                                <Button Content="A" Margin="0,0,5,0" VerticalAlignment="Center" Click="Button_Click" WindowChrome.IsHitTestVisibleInChrome="True"/>
                                <Button Content="B" Margin="0,0,5,0" VerticalAlignment="Center" Click="Button_Click" WindowChrome.IsHitTestVisibleInChrome="True"/>
                                <Button Content="C" Margin="0,0,5,0" VerticalAlignment="Center" Click="Button_Click" WindowChrome.IsHitTestVisibleInChrome="True"/>
                                <Button Content="D" Margin="0,0,5,0" VerticalAlignment="Center" Click="Button_Click" WindowChrome.IsHitTestVisibleInChrome="True"/>
                            </StackPanel>

                            <TextBlock Margin="5,0,0,0"
                                       VerticalAlignment="Center"
                                       HorizontalAlignment="Center"
                                       FontSize="16"
                                       Foreground="White"
                                       Text="{TemplateBinding Title}"
                                       Grid.Column="1"/>

                            <StackPanel Orientation="Horizontal"
                                        Grid.Column="2">
                                <Button x:Name="btnClose"
                                    Width="15"
                                    Margin="5"
                                    Click="CloseClick"
                                    Content="X"
                                    WindowChrome.IsHitTestVisibleInChrome="True" />

                                <Button x:Name="btnRestore"
                                    Width="15"
                                    Margin="5"
                                    Click="MaximizeRestoreClick"
                                    Content="#"
                                    WindowChrome.IsHitTestVisibleInChrome="True" />

                                <Button x:Name="btnMinimize"
                                    Width="15"
                                    Margin="5"
                                    VerticalContentAlignment="Bottom"
                                    Click="MinimizeClick"
                                    Content="_"
                                    WindowChrome.IsHitTestVisibleInChrome="True" />
                            </StackPanel>
                        </Grid>

                    </Grid>

                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

And for the code behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace WpfApp7
{
    public partial class WindowStyle : ResourceDictionary
    {
        public WindowStyle()
        {
            InitializeComponent();
        }

        private void CloseClick(object sender, RoutedEventArgs e)
        {
            var window = (Window)((FrameworkElement)sender).TemplatedParent;
            window.Close();
        }

        private void MaximizeRestoreClick(object sender, RoutedEventArgs e)
        {
            var window = (Window)((FrameworkElement)sender).TemplatedParent;
            if (window.WindowState == System.Windows.WindowState.Normal)
            {
                window.WindowState = System.Windows.WindowState.Maximized;
            }
            else
            {
                window.WindowState = System.Windows.WindowState.Normal;
            }
        }

        private void MinimizeClick(object sender, RoutedEventArgs e)
        {
            var window = (Window)((FrameworkElement)sender).TemplatedParent;
            window.WindowState = System.Windows.WindowState.Minimized;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Hello!");
        }
    }
}


问:
setting d3 graph from inside of an anonymous function
I am trying to read a JSON file which looks like:

```<code>[ {
"parent" : "cmeta_transform",
"path" : "hcat://sample/dt=yyyyMMddHH",
"child" : "lite_video_hourly"
} ]
</code>```

Then, I am iterating over the contents and setting the Node and Edges from inside the data.forEach function call (code below)

But, it seems like the variable g is not getting set when I iterate over it. If I do it outside the anonymous function, it works.
What am I missing?

```<code><script id="js">
// Create a new directed graph
var g = new dagreD3.graphlib.Graph().setGraph({});

d3.json("expectedOutput.json", function(data) {
    data.forEach(function (job) {
        console.log(job); // I do see job values correctly.
        g.setNode(job.child, { label: job.child });
        g.setEdge(job.parent,     job.child,     { label: job.path });
    });
});

console.log(g); // g doesn't have the nodes & edges values set above

// if I do this
g.setNode(job.child, { label: job.child });
g.setEdge(job.parent,     job.child,     { label: job.path });
console.log(g); // I see g is set properly
</script>
</code>```

答:
This happens because requesting the JSON via AJAX is an asynchronous operation so the console.log is executed before what's inside the anonymous function.

You may want to look at promises in JavaScript or at least put your code inside that function so the result of the request is available to your code. At the simplest level this should work:

```<code>function draw(data) {
  var g = new dagreD3.graphlib.Graph().setGraph({});
  data.forEach(function (job) {
      console.log(job); // I do see job values correctly.
      g.setNode(job.child, { label: job.child });
      g.setEdge(job.parent,     job.child,     { label: job.path });
  });
  // carry on doing what you need in here...
}

d3.json("expectedOutput.json", draw);
</code>```

Body:
I am trying to read a JSON file which looks like:

[ {
"parent" : "cmeta_transform",
"path" : "hcat://sample/dt=yyyyMMddHH",
"child" : "lite_video_hourly"
} ]

Then, I am iterating over the contents and setting the Node and Edges from inside the data.forEach function call (code below)

But, it seems like the variable g is not getting set when I iterate over it. If I do it outside the anonymous function, it works.
What am I missing?

Body:
This happens because requesting the JSON via AJAX is an asynchronous operation so the console.log is executed before what's inside the anonymous function.

You may want to look at promises in JavaScript or at least put your code inside that function so the result of the request is available to your code. At the simplest level this should work:

function draw(data) {
  var g = new dagreD3.graphlib.Graph().setGraph({});
  data.forEach(function (job) {
      console.log(job); // I do see job values correctly.
      g.setNode(job.child, { label: job.child });
      g.setEdge(job.parent,     job.child,     { label: job.path });
  });
  // carry on doing what you need in here...
}

d3.json("expectedOutput.json", draw);


问:
Font Size in SQL Results To Grid View in Visual Studio
I'm working with VS21017 and I have a SQL file (scripts.sql) in my solution. When I open that file, I can connect to a database and execute queries.

The results grid for a typical SELECT statement is in a really small font.

I've looked in the Tools > Options menu under the Database Tools and SQL Server Tools headings, but can not find a way to increase/adjust the size of the font in that results grid. I have also tried various keyboard shortcuts that affect other places in VS, like Ctrl + < and Ctrl + >, which work in C#, HTML, and T-SQL editors.

How can I adjust the size of the font in that results grid?

Thanks!

答:
Found it:

Tools>Options>Environment>Fonts and Colors

Show Settings For>"SQL Results - Grid"


问:
Troubles with errno.h
I'm coding a simple SDL program with VC10. The problem that I am having is at compiling the program:

Error 1 error C1083: Cannot open include file: 'errno.h': No such file
  or directory c:\program files\microsoft visual studio
  10.0\vc\include\cerrno 14

Error 2 error C1083: Cannot open include file: 'errno.h': No such file
  or directory c:\program files\microsoft visual studio
  10.0\vc\include\cerrno 14

Error 3 error C1083: Cannot open include file: 'errno.h': No such file
  or directory c:\program files\microsoft visual studio
  10.0\vc\include\cerrno 14

Error 4 error C1083: Cannot open include file: 'errno.h': No such file
  or directory c:\program files\microsoft visual studio
  10.0\vc\include\cerrno 14

I'm not sure what could be the problem. I don't have an errno.h file in my includes. And I have no idea of where to get it or if it was there. What can I do? I have been looking for an errno.h file around but all seem aimed at Linux platforms.

答: The solution for me was re-running the installer, selecting "Individual Components", and adding the older common tools (v140).</p>

Title: Troubles with errno.h


问:
how to merge one row data to one column in sql server
i have one trigger like this:

```<code>alter trigger newTrigger
on table2
after insert
as
begin
    declare @rowData nvarchar(max)
    if exists(select * from inserted)
    begin
        Set @rowData = (select * from inserted)
    end

    insert into table1(rowData, date)
    values(@rowData, getdate())
end
</code>```

i want after insert into table2, the inserted record and date insert to table1
but i cant merge the data of row into one column!

```<code>------------------table2--------------------
id   |  name  |   lname  | birth
1        j          jj       2000-03-03

-------------------table1 after insert into table2 -----------------
rowData            |     date
a,j,jj,2000-03-03       2017-05-07
</code>```

答:
You have to do the conversion and add one by one each column

eg:

```<code>Set @rowData = (select cast(col1 as varchar(10)) + cast(col2 as varchar(10)) from inserted)
</code>```

for your edit with the col names. If the column already is varchar, the only that you have to take care is to avoid the length overflow :

```<code>Set @rowData = (select cast((id + ',' + name + ',' + lname + ',' + cast(birth as varchar(12)) ) as varchar(4000))  from inserted)
</code>```

Body:
i have one trigger like this:

alter trigger newTrigger
on table2
after insert
as
begin
    declare @rowData nvarchar(max)
    if exists(select * from inserted)
    begin
        Set @rowData = (select * from inserted)
    end

    insert into table1(rowData, date)
    values(@rowData, getdate())
end

i want after insert into table2, the inserted record and date insert to table1
but i cant merge the data of row into one column!

------------------table2--------------------
id   |  name  |   lname  | birth
1        j          jj       2000-03-03

-------------------table1 after insert into table2 -----------------
rowData            |     date
a,j,jj,2000-03-03       2017-05-07

Body:
You have to do the conversion and add one by one each column

eg:

Set @rowData = (select cast(col1 as varchar(10)) + cast(col2 as varchar(10)) from inserted)

for your edit with the col names. If the column already is varchar, the only that you have to take care is to avoid the length overflow :

Set @rowData = (select cast((id + ',' + name + ',' + lname + ',' + cast(birth as varchar(12)) ) as varchar(4000))  from inserted)


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

There are two Tables

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

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

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

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

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

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

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

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

答:
correlated subquery w/ an exists so it can early exit

The select 1 in the subquery is because we have to select a value but it doesn't matter what value that is.  since the coloration (DNC.Phone_Number = CL.Phone_Number) is all we are after; along with your limits on call_log.

```<code>DELETE
FROM DNC
WHERE exists (SELECT 1
              FROM Call_logs CL
              WHERE CL.call_date < 'DATE'
                and CL.Status = 'DNC'
                and DNC.Phone_Number = CL.Phone_Number)
</code>```

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

There are two Tables

Table 1: DNC
Table 2: Call_Logs

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

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

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

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

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

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

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

Body:
correlated subquery w/ an exists so it can early exit

The select 1 in the subquery is because we have to select a value but it doesn't matter what value that is.  since the coloration (DNC.Phone_Number = CL.Phone_Number) is all we are after; along with your limits on call_log.

DELETE
FROM DNC
WHERE exists (SELECT 1
              FROM Call_logs CL
              WHERE CL.call_date < 'DATE'
                and CL.Status = 'DNC'
                and DNC.Phone_Number = CL.Phone_Number)


问:
Fading in/out GameObject
I'm fairly new to coding, I'm still trying to develop that logic of thinking to help me create the solutions I'm wanting for games. Currently, I'm in Unity trying to create a 2D GameObject that's a wall hiding a secret door. I want that GameObject to fade out (about 90%) when the player GameObject triggers it, revealing the space behind and the hidden door.

So far, I've managed to figure out how to render the "secret wall" GO inactive on the trigger, so it disappears, but this doesn't produce the visual that I'm going for. As I said, I'm still working on developing that coder's way of thinking, so while I've done a lot of research to solve this problem, many of the results I don't readily understand.

Here's my code:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SecretDoor1 : MonoBehaviour {

    void OnTriggerEnter2D (Collider2D SecretDoorTrig) {
         if (SecretDoorTrig.gameObject.tag == "Player") {
             GetComponent<SpriteRenderer> ().enabled = false;
         }
         else {
             GetComponent<SpriteRenderer> ().enabled = true;
         }
    }

    void OnTriggerExit2D (Collider2D SecretDoorTrig) {

         if (SecretDoorTrig.gameObject.tag == "Player") {

             GetComponent<SpriteRenderer> ().enabled = true;
         }
         else {
             GetComponent<SpriteRenderer> ().enabled = false;
         }
    }
}
</code>```

答:
The way I have accomplished this has been change the alpha on the sprite color.

Color(R,G,B,A). A is the alpha.

SpriteRenderer.color = new Color(1f,1f,1f,1f) is opaque.

SpriteRenderer.color = new Color(1f,1f,1f,.5f) is about 50%
transparent.

SpriteRenderer.color = new Color(1f,1f,1f,0f) is about
100% transparent, sprite cannot be seen.

Title: Fading in/out GameObject

Body:
I'm fairly new to coding, I'm still trying to develop that logic of thinking to help me create the solutions I'm wanting for games. Currently, I'm in Unity trying to create a 2D GameObject that's a wall hiding a secret door. I want that GameObject to fade out (about 90%) when the player GameObject triggers it, revealing the space behind and the hidden door.

So far, I've managed to figure out how to render the "secret wall" GO inactive on the trigger, so it disappears, but this doesn't produce the visual that I'm going for. As I said, I'm still working on developing that coder's way of thinking, so while I've done a lot of research to solve this problem, many of the results I don't readily understand.

Here's my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SecretDoor1 : MonoBehaviour {

    void OnTriggerEnter2D (Collider2D SecretDoorTrig) {
         if (SecretDoorTrig.gameObject.tag == "Player") {
             GetComponent<SpriteRenderer> ().enabled = false;
         }
         else {
             GetComponent<SpriteRenderer> ().enabled = true;
         }
    }

    void OnTriggerExit2D (Collider2D SecretDoorTrig) {

         if (SecretDoorTrig.gameObject.tag == "Player") {

             GetComponent<SpriteRenderer> ().enabled = true;
         }
         else {
             GetComponent<SpriteRenderer> ().enabled = false;
         }
    }
}


问:
Convert an Array to Json Laravel
im getting this error

ErrorException in helpers.php line 685:
  preg_replace(): Parameter mismatch, pattern is a string while replacement is an array

i want to convert the comments entity, but i dont know how that will look.

whats the best choice? toJson() or json_encode?

this is my controller

```<code>public function update($id, Request $request)
    {
        $trip = Trip::find($id);
        $trip = Trip::with('comments')->where('id', $id)->first();
        $trip->fill($request->input());

        if($request->has('comments')){
            // foreach($request->comments as $comments){
            //     $comments = Comment::find($id);
            //     $comments->fill($request->input());
            //     $comments->save();

                 $commentArray=[];
        foreach($request->comments as $key=>$commentEntity) {
            // dd($commentEntity);
            // dd($request->comments);
             $comment =Comment::find($id);
            $comment->comment=$commentEntity['comment'];
            $comment->trip_id=$commentEntity['trip_id'];
            $comment->date=date('Y,m,d,G,i,s');
            $comment->user_id=$commentEntity['user_id'];
            $comment->save();
            }
        }

       if($request->files){
        foreach($request->files as $files){
            $file = File::find($id);
            $file->save();
            }
     }

        $trip->save();
        return response()->json($trip);

    }
</code>```

I already try with :

```<code>            **// $strFromArr = serialize($comment); and
            // $comment->toJson(); and this way too
            //$json = json_encode($comment);**
</code>```

答:
As @omadonex said, there is no need to convert the model before returning it from the controller.
In Laravel's controllers you can just return model/collection and Laravel will take care of the conversions.

I don't think that the return $trip; was preventing your data to be updated - so I suggest you to make the change and re-debug your code.

For your comments update, add comment id to every row that you send and use this foreach:

```<code>foreach($request->comments as $commentEntity) {
    $comment = Comment::find($commentEntity['id']);
    $comment->comment = $commentEntity['comment'];
    $comment->trip_id = $commentEntity['trip_id'];
    $comment->date = date('Y,m,d,G,i,s');
    $comment->user_id = $commentEntity['user_id'];
    $comment->save();
}
</code>```

Title: Convert an Array to Json Laravel

Body:
im getting this error

ErrorException in helpers.php line 685:
  preg_replace(): Parameter mismatch, pattern is a string while replacement is an array

i want to convert the comments entity, but i dont know how that will look.

whats the best choice? toJson() or json_encode?

this is my controller

public function update($id, Request $request)
    {
        $trip = Trip::find($id);
        $trip = Trip::with('comments')->where('id', $id)->first();
        $trip->fill($request->input());

        if($request->has('comments')){
            // foreach($request->comments as $comments){
            //     $comments = Comment::find($id);
            //     $comments->fill($request->input());
            //     $comments->save();

                 $commentArray=[];
        foreach($request->comments as $key=>$commentEntity) {
            // dd($commentEntity);
            // dd($request->comments);
             $comment =Comment::find($id);
            $comment->comment=$commentEntity['comment'];
            $comment->trip_id=$commentEntity['trip_id'];
            $comment->date=date('Y,m,d,G,i,s');
            $comment->user_id=$commentEntity['user_id'];
            $comment->save();
            }
        }

       if($request->files){
        foreach($request->files as $files){
            $file = File::find($id);
            $file->save();
            }
     }

        $trip->save();
        return response()->json($trip);

    }

I already try with :

            **// $strFromArr = serialize($comment); and
            // $comment->toJson(); and this way too
            //$json = json_encode($comment);**

Body:
As @omadonex said, there is no need to convert the model before returning it from the controller.
In Laravel's controllers you can just return model/collection and Laravel will take care of the conversions.

I don't think that the return $trip; was preventing your data to be updated - so I suggest you to make the change and re-debug your code.

For your comments update, add comment id to every row that you send and use this foreach:

foreach($request->comments as $commentEntity) {
    $comment = Comment::find($commentEntity['id']);
    $comment->comment = $commentEntity['comment'];
    $comment->trip_id = $commentEntity['trip_id'];
    $comment->date = date('Y,m,d,G,i,s');
    $comment->user_id = $commentEntity['user_id'];
    $comment->save();
}


问:
How to paste multiple lines in Vim?
QUESTION:

I am deleting/copying every other line with :g/^/+d
However, when I try pasting all of those lines only the last line gets pasted. How do I paste every single line that I deleted/copied?

RESOLVED:

Thanks everyone! With your help I was able to finish my video (I work on a Youtube channel called Vim Girl where I make guided Vim Golf challenges.) Here's the link if you're interested: https://youtu.be/S9o5bHUAbP0

答:
you could write a macro to append everything to the end:

```<code>qdddGp<ctrl + o>jq
</code>```

then run it as many times (20, e.g.) as you need using:

```<code>20@d
</code>```

Title: How to paste multiple lines in Vim?

Body:
you could write a macro to append everything to the end:

qdddGp<ctrl + o>jq

then run it as many times (20, e.g.) as you need using:

20@d


问:
Onclick JS function call, returns "Can't find variable" only in Safari Console
So I have a very simple JS function written that works like the following.

There is a button that has the following code:

```<code><button type="submit" class="large button" onclick="addCart(76,95,73,96);">
    <i class="icon-shopping-cart"></i> Add to Cart
</button>
</code>```

Now when that is clicked there is a very simple function added to the page below that looks like the following:

```<code><script type="text/javascript">
    function addCart(pid, pattr, pval, pscent = 0) {
    ...
    }
</script>
</code>```

This works perfectly in Chrome, Firefox, Chrome for Mobile, Safari for Mobile.

But this does not seem to work on Safari on Mac. Instead I get the following error:

ReferenceError: Can't find variable: addCart

I cannot figure out why. It's hard for me to add a listener because there are 7 buttons and a wide arrange of variables that are being sent, and I'd rather send that like I'm currently doing.

答:
I finally found the issue.

The function was creating an error in Safari so it was never being defined. I changed the function to the following:

```<code>function addCart(pid, pattr, pval, pscent) {
    pscent = (typeof pscent !== 'undefined') ?  pscent : 0;
...
}
</code>```

Notice the big difference is that I was no longer using the Function to declare a default value for 'pscent' and instead I do it the old school method. Not sure if this is being caused by an older version of Safari or what.

If you are here because of a similar error, look for some potential JS error in the function which will prevent the function from being declared.

Body:
So I have a very simple JS function written that works like the following.

There is a button that has the following code:

<button type="submit" class="large button" onclick="addCart(76,95,73,96);">
     Add to Cart
</button>

Now when that is clicked there is a very simple function added to the page below that looks like the following:

This works perfectly in Chrome, Firefox, Chrome for Mobile, Safari for Mobile.

But this does not seem to work on Safari on Mac. Instead I get the following error:

ReferenceError: Can't find variable: addCart

I cannot figure out why. It's hard for me to add a listener because there are 7 buttons and a wide arrange of variables that are being sent, and I'd rather send that like I'm currently doing.

Body:
I finally found the issue.

The function was creating an error in Safari so it was never being defined. I changed the function to the following:

function addCart(pid, pattr, pval, pscent) {
    pscent = (typeof pscent !== 'undefined') ?  pscent : 0;
...
}

Notice the big difference is that I was no longer using the Function to declare a default value for 'pscent' and instead I do it the old school method. Not sure if this is being caused by an older version of Safari or what.

If you are here because of a similar error, look for some potential JS error in the function which will prevent the function from being declared.


问:
VS 2017 for Android emulator not working - xamarin
Installed VS 2017 (prof & community) RTM for xamarin development. Getting the below error while running the app. I have verified that installed the Intel Acceleration component. Any insights ?

1>C:\Users\Sowmyan\documents\visual studio 2017\Projects\App1\App1\App1.Android\App1.Android.csproj : warning XA0105: The $(TargetFrameworkVersion) for FormsViewGroup.dll (v7.1) is greater than the $(TargetFrameworkVersion) for your project (v6.0). You need to increase the $(TargetFrameworkVersion) for your project.
1>C:\Users\Sowmyan\documents\visual studio 2017\Projects\App1\App1\App1.Android\App1.Android.csproj : warning XA0105: The $(TargetFrameworkVersion) for Xamarin.Forms.Platform.Android.dll (v7.1) is greater than the $(TargetFrameworkVersion) for your project (v6.0). You need to increase the $(TargetFrameworkVersion) for your project.
1>C:\Users\Sowmyan\documents\visual studio 2017\Projects\App1\App1\App1.Android\App1.Android.csproj : warning XA0105: The $(TargetFrameworkVersion) for Xamarin.Forms.Platform.dll (v7.1) is greater than the $(TargetFrameworkVersion) for your project (v6.0). You need to increase the $(TargetFrameworkVersion) for your project.
1>    Processing: obj\Debug\res\layout\tabbar.xml
1>    Processing: obj\Debug\res\layout\toolbar.xml
1>    Processing: obj\Debug\res\values\styles.xml
1>    Processing: obj\Debug\res\layout\tabbar.xml
1>    Processing: obj\Debug\res\layout\toolbar.xml
1>    Processing: obj\Debug\res\values\styles.xml
2>Starting deploy VisualStudio_android-23_x86_phone ...
2>Starting emulator VisualStudio_android-23_x86_phone ...
2>C:\PROGRA~2\Android\ANDROI~1\tools\emulator.EXE -partition-size 512 -no-boot-anim -avd VisualStudio_android-23_x86_phone -prop monodroid.avdname=VisualStudio_android-23_x86_phone
**2>emulator: ERROR: x86 emulation currently requires hardware acceleration!**
2>Please ensure Intel HAXM is properly installed and usable.
2>CPU acceleration status: HAXM is not installed on this machine
2>Emulator VisualStudio_android-23_x86_phone cannot be started.
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========
========== Deploy: 0 succeeded, 1 failed, 0 skipped ==========```

答: I had a similar problem on my laptop.  It turned out the Virtualization was turned off in my BIOS.  My recommendation is to enter the BIOS setup on reboot   (refer to manual as all machines are different) and see if Intel Virtualization is enabled.  If not, you will need to enable it.</p>


答:
Use map() When you are planning to return a new array from an existing array. forEach() let you iterate the array but doesn't return any new array.

function doThis() {
    var multiplier = 3;
    var list = [23, 54, 23, 25, 65];
    var products = multiply(list, multiplier);
    console.log(products);
}
function multiply(list, multiplier) {
   return list.map(function (element){
        return element * multiplier;
    });
}

doThis();```

Title: Trouble with adding multiple values into array

Body:
I'm trying to learn more about arrays and so I just wrote this simple function:
(I'm calling doThis from an onClick for testing purposes).

function doThis() {
    var multiplier = 3;
    var list = [23, 54, 23, 25, 65];
    var products = multiply(list, multiplier);
    console.log(products);
}
function multiply(list, multiplier) {
    list.forEach(function (element){
        var multi = [element * multiplier];
        console.log(multi);
        return multi;
    });
}

My issue is two-fold:

var products is returning undefined.

When I step through the code in the debugger, it shows the arithmetic being done correctly, but it doesn't store more than one value in the variable multi.

The end goal would be to have var products hold the multi array.


问:
sed regular expression to replace value with variable of same name
I am trying to replace a some variables in a yml file.

Samepl.yml

```<code>spring:
  metadataMap:
    instanceId: ${spring.application.name}:${randomvalue}
client:
  version: 1.0
  myval: {{ myVal }}
</code>```

I am using following command to replace all the values inside double braces eg: {{ var }}  with a environment variable of same name i.e value of: ${var} it should fail if variable is undefined. But no luck

```<code>cat sample.yml | sed -e "s/{{ \(.*\) }}/${\1:?}/g" > /tmp/a
</code>```

Any suggestions?

答:
You can use Perl for that:

```<code>perl -pE 's:{{\s*(\S+?)\s*}}:$ENV{$1} // die "$1 not set":ge'
</code>```

If your Perl is older than 5.10, you need to be more verbose:

```<code>perl -pe 's%{{\s*(\S+?)\s*}}%exists $ENV{$1} ? $ENV{$1} : die "$1 not set"%ge'
</code>```

Body:
I am trying to replace a some variables in a yml file.

Samepl.yml

spring:
  metadataMap:
    instanceId: ${spring.application.name}:${randomvalue}
client:
  version: 1.0
  myval: {{ myVal }}

I am using following command to replace all the values inside double braces eg: {{ var }}  with a environment variable of same name i.e value of: ${var} it should fail if variable is undefined. But no luck

cat sample.yml | sed -e "s/{{ \(.*\) }}/${\1:?}/g" > /tmp/a

Any suggestions?

Body:
You can use Perl for that:

perl -pE 's:{{\s*(\S+?)\s*}}:$ENV{$1} // die "$1 not set":ge'

If your Perl is older than 5.10, you need to be more verbose:

perl -pe 's%{{\s*(\S+?)\s*}}%exists $ENV{$1} ? $ENV{$1} : die "$1 not set"%ge'


问:
XPATH: Get row containing String and goto link on this row
Below fields are in table rows of a web page. I want to basically click the "Download certificate" link but only on the row that contains "15 Jun 2017". Can anyone advise an xpath that will only goto this row

```<code>TestTraining1-5375  Test_training1.zip  15 Jun 2017
00:00:00
UA-1-5375
UA-2-5375
Download certificate

TestTraining1-5375  Test_training1.zip  16 Jun 2017
00:00:00
UA-1-5375
UA-2-5375
Download certificate
</code>```

So i can get either using

```<code>//*[contains(text(),'Download certificate')]@href

</code>```

but is there a way of getting the specific row. Not sure how to do the "and" operator in xpath

HTML code here https://prnt.sc/frx1nv

答:
In your case the node that holds the text Download Certificate is the  itself.

The following HTML example has the same example:

```<code><html>
<body>
<a id="12" href="http://google.com">
<i class="fa-download">some</i>
" Download"
</a>
</body>
</html>
</code>```

With the following robot script:

```<code>*** Settings ***
Library    Selenium2Library
*** Test Cases ***

TC
    Open Browser    http://localhost:8090/textnode.html    Chrome

    ${var1}    Get Text    xpath=//a
    ${var2}    Execute Javascript    return document.getElementById('12').childNodes[2].nodeValue;

    [Teardown]    Close Browser
</code>```

You get the following result:

```<code>${var1} = some " Download"
${var2} = " Download"
</code>```

Body:
Below fields are in table rows of a web page. I want to basically click the "Download certificate" link but only on the row that contains "15 Jun 2017". Can anyone advise an xpath that will only goto this row

TestTraining1-5375  Test_training1.zip  15 Jun 2017
00:00:00
UA-1-5375
UA-2-5375
Download certificate

TestTraining1-5375  Test_training1.zip  16 Jun 2017
00:00:00
UA-1-5375
UA-2-5375
Download certificate

So i can get either using

//*[contains(text(),'Download certificate')]@href

but is there a way of getting the specific row. Not sure how to do the "and" operator in xpath

HTML code here https://prnt.sc/frx1nv

Body:
In your case the node that holds the text Download Certificate is the <a> itself.

The following HTML example has the same example:

<html>
<body>
<a id="12" href="http://google.com">
<i class="fa-download">some</i>
" Download"
</a>
</body>
</html>

With the following robot script:

*** Settings ***
Library    Selenium2Library
*** Test Cases ***

TC
    Open Browser    http://localhost:8090/textnode.html    Chrome

    ${var1}    Get Text    xpath=//a
    ${var2}    Execute Javascript    return document.getElementById('12').childNodes[2].nodeValue;

    [Teardown]    Close Browser

You get the following result:

${var1} = some " Download"
${var2} = " Download"


问:
Process returned an error (exit code -3) in cake execution
While executing the cake script for test projects i'm getting,

```<code>    An error occurred when executing task 'test'.
    Error: System.Exception: DotCover: Process returned an error (exit code -3).
       at Submission#0.<.ctor>b__29(Exception exception)
       at Cake.Core.DefaultExecutionStrategy.HandleErrors(Action`1 action, Exception exception)
       at Cake.Core.CakeEngine.HandleErrors(IExecutionStrategy strategy, Action`1 errorHandler, Exception exception)
       at Cake.Core.CakeEngine.ExecuteTask(ICakeContext context, IExecutionStrategy strategy, Stopwatch stopWatch, CakeTask task, CakeReport report)
       at Cake.Core.CakeEngine.RunTarget(ICakeContext context, IExecutionStrategy strategy, String target)
       at Cake.Scripting.BuildScriptHost.RunTarget(String target)
       at Submission#0.<.ctor>b__31()
       at Cake.Core.ActionTask.Execute(ICakeContext context)
       at Cake.Core.DefaultExecutionStrategy.Execute(CakeTask task, ICakeContext context)
       at Cake.Core.CakeEngine.ExecuteTask(ICakeContext context, IExecutionStrategy strategy, Stopwatch stopWatch, CakeTask task, CakeReport report)
       at Cake.Core.CakeEngine.RunTarget(ICakeContext context, IExecutionStrategy strategy, String target)
       at Cake.Scripting.BuildScriptHost.RunTarget(String target)
       at Submission#0..ctor(Session session, Object& submissionResult)
       at Submission#0.<Factory>(Session session)
       at Roslyn.Scripting.CommonScriptEngine.Execute[T](String code, String path, DiagnosticBag diagnostics, Session session, Boolean isInteractive)
       at Roslyn.Scripting.Session.Execute(String code)
       at Cake.Core.Scripting.ScriptRunner.Run(IScriptHost host, FilePath scriptPath, IDictionary`2 arguments)
       at Cake.Commands.BuildCommand.Execute(CakeOptions options)
       at Cake.CakeApplication.Run(CakeOptions options)
       at Cake.Program.Main()
</code>```

How can i solve this problem?

答:
Return code -3 from dotcover.exe indicates that the exit code in the application being analysed isn't equal to 0. (plain English, your Unit Tests are failing). See this link.

To verify if tests are failing, try running unit tests separately without DotCover alias.

To continue even thoug tests are failing, see error handling in Cake

Body:
While executing the cake script for test projects i'm getting,

    An error occurred when executing task 'test'.
    Error: System.Exception: DotCover: Process returned an error (exit code -3).
       at Submission#0.<.ctor>b__29(Exception exception)
       at Cake.Core.DefaultExecutionStrategy.HandleErrors(Action`1 action, Exception exception)
       at Cake.Core.CakeEngine.HandleErrors(IExecutionStrategy strategy, Action`1 errorHandler, Exception exception)
       at Cake.Core.CakeEngine.ExecuteTask(ICakeContext context, IExecutionStrategy strategy, Stopwatch stopWatch, CakeTask task, CakeReport report)
       at Cake.Core.CakeEngine.RunTarget(ICakeContext context, IExecutionStrategy strategy, String target)
       at Cake.Scripting.BuildScriptHost.RunTarget(String target)
       at Submission#0.<.ctor>b__31()
       at Cake.Core.ActionTask.Execute(ICakeContext context)
       at Cake.Core.DefaultExecutionStrategy.Execute(CakeTask task, ICakeContext context)
       at Cake.Core.CakeEngine.ExecuteTask(ICakeContext context, IExecutionStrategy strategy, Stopwatch stopWatch, CakeTask task, CakeReport report)
       at Cake.Core.CakeEngine.RunTarget(ICakeContext context, IExecutionStrategy strategy, String target)
       at Cake.Scripting.BuildScriptHost.RunTarget(String target)
       at Submission#0..ctor(Session session, Object& submissionResult)
       at Submission#0.<Factory>(Session session)
       at Roslyn.Scripting.CommonScriptEngine.Execute[T](String code, String path, DiagnosticBag diagnostics, Session session, Boolean isInteractive)
       at Roslyn.Scripting.Session.Execute(String code)
       at Cake.Core.Scripting.ScriptRunner.Run(IScriptHost host, FilePath scriptPath, IDictionary`2 arguments)
       at Cake.Commands.BuildCommand.Execute(CakeOptions options)
       at Cake.CakeApplication.Run(CakeOptions options)
       at Cake.Program.Main()

How can i solve this problem?


问:
Use data from database in url with htaccess
I have a custom link stored in a MySQL database and I want that link use instead of the default get-link with htaccess.

Example: If a visitor will read a blog, the url is www.domain.com/blog.php?post_link=2017-07-05/First-Post

Is there any way to use the post_link from the database instead the url now?
I've read something about it here: SO Item, but that don't work...

Please help!

Before: www.domain.com/blog.php?post_link=2017-07-05/First-Post

After: www.domain.com/blog/2017-07-05/First-Post

This is my database

This is my code in blog.php

PS: It is SEO only..

答:
```<code>RewriteEngine on
RewriteRule ^([0-9]+)/(.+)$ /blog.php?post_link=$1&First-Post=$2 [NC,QSA]
</code>```

I have not tested it yet i hope it will work. and give you the desired results.

here is the answer in details

Body:
RewriteEngine on
RewriteRule ^([0-9]+)/(.+)$ /blog.php?post_link=$1&First-Post=$2 [NC,QSA]

I have not tested it yet i hope it will work. and give you the desired results.

here is the answer in details


问:
2D linear interpolation: data and interpolated points
Consider this y(x) function:

where we can generate these scattered points in a file: dataset_1D.dat:

```<code># x   y
0   0
1   1
2   0
3   -9
4   -32
</code>```

The following is a 1D interpolation code for these points:

Load this scattered points

Create a x_mesh

Perform a 1D interpolation

Code:

```<code>import numpy as np
from scipy.interpolate import interp2d, interp1d, interpnd
import matplotlib.pyplot as plt

# Load the data:
x, y  = np.loadtxt('./dataset_1D.dat', skiprows = 1).T

# Create the function Y_inter for interpolation:
Y_inter = interp1d(x,y)

# Create the x_mesh:
x_mesh = np.linspace(0, 4, num=10)
print x_mesh

# We calculate the y-interpolated of this x_mesh :
Y_interpolated = Y_inter(x_mesh)
print Y_interpolated

# plot:

plt.plot(x_mesh, Y_interpolated, "k+")
plt.plot(x, y, 'ro')
plt.legend(['Linear 1D interpolation', 'data'], loc='lower left',  prop={'size':12})
plt.xlim(-0.1, 4.2)
plt.grid()
plt.ylabel('y')
plt.xlabel('x')
plt.show()
</code>```

This plots the following:

Now, consider this z(x,y) function:

where we can generate these scattered points in a file: dataset_2D.dat :

```<code># x    y    z
0   0   0
1   1   0
2   2   -4
3   3   -18
4   4   -48
</code>```

In this case we would have to perform a 2D interpolation:

```<code>import numpy as np
from scipy.interpolate import interp1d, interp2d, interpnd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# Load the data:
x, y, z  = np.loadtxt('./dataset_2D.dat', skiprows = 1).T

# Create the function Z_inter for interpolation:
Z_inter = interp2d(x, y, z)

# Create the x_mesh and y_mesh :
x_mesh = np.linspace(1.0, 4, num=10)
y_mesh = np.linspace(1.0, 4, num=10)
print x_mesh
print y_mesh

# We calculate the z-interpolated of this x_mesh and y_mesh :
Z_interpolated = Z_inter(x_mesh, y_mesh)
print Z_interpolated
print type(Z_interpolated)
print Z_interpolated.shape

# plot:
fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(x, y, z, c='r', marker='o')
plt.legend(['data'], loc='lower left',  prop={'size':12})
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')

plt.show()
</code>```

This plots the following:

where the scattered data is shown again in red dots, to be consistent with the 2D plot.

I do not know how to interpret the  Z_interpolated result:

According to the printing lines for the above code,
Z_interpolated is a n-dimensional numpy array, of shape (10,10). In other words, a 2D matrix with 10 rows and 10 columns.

I would have expected an interpolated z[i] value for each value of x_mesh[i] and y_mesh[i] Why I do not receive this ?

How could I plot also in the 3D plot the interpolated data (just like the black crosses in the 2D plot)?

答:
Interpretation of Z_interpolated: your 1-D x_mesh and y_mesh defines a mesh on which to interpolate. Your 2-D interpolation return z is therefore a 2D array with shape (len(y), len(x)) which matches np.meshgrid(x_mesh, y_mesh). As you can see, your z[i, i], instead of z[i], is the expected value for x_mesh[i] and y_mesh[i]. And it just has a lot more, all values on the mesh.

A potential plot to show all interpolated data:

```<code>from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import interp2d

# Your original function
x = y = np.arange(0, 5, 0.1)
xx, yy = np.meshgrid(x, y)
zz = 2 * (xx ** 2) - (xx ** 3) - (yy ** 2)

# Your scattered points
x = y = np.arange(0, 5)
z = [0, 0, -4, -18, -48]

# Your interpolation
Z_inter = interp2d(x, y, z)
x_mesh = y_mesh = np.linspace(1.0, 4, num=10)
Z_interpolated = Z_inter(x_mesh, y_mesh)

fig = plt.figure()
ax = fig.gca(projection='3d')
# Plot your original function
ax.plot_surface(xx, yy, zz, color='b', alpha=0.5)
# Plot your initial scattered points
ax.scatter(x, y, z, color='r', marker='o')
# Plot your interpolation data
X_real_mesh, Y_real_mesh = np.meshgrid(x_mesh, y_mesh)
ax.scatter(X_real_mesh, Y_real_mesh, Z_interpolated, color='g', marker='^')
plt.show()
</code>```

Body:
Consider this y(x) function:

where we can generate these scattered points in a file: dataset_1D.dat:

# x   y
0   0
1   1
2   0
3   -9
4   -32

The following is a 1D interpolation code for these points:

Load this scattered points

Create a x_mesh

Perform a 1D interpolation

Code:

import numpy as np
from scipy.interpolate import interp2d, interp1d, interpnd
import matplotlib.pyplot as plt

# Load the data:
x, y  = np.loadtxt('./dataset_1D.dat', skiprows = 1).T

# Create the function Y_inter for interpolation:
Y_inter = interp1d(x,y)

# Create the x_mesh:
x_mesh = np.linspace(0, 4, num=10)
print x_mesh

# We calculate the y-interpolated of this x_mesh :
Y_interpolated = Y_inter(x_mesh)
print Y_interpolated

# plot:

plt.plot(x_mesh, Y_interpolated, "k+")
plt.plot(x, y, 'ro')
plt.legend(['Linear 1D interpolation', 'data'], loc='lower left',  prop={'size':12})
plt.xlim(-0.1, 4.2)
plt.grid()
plt.ylabel('y')
plt.xlabel('x')
plt.show()

This plots the following:

Now, consider this z(x,y) function:

where we can generate these scattered points in a file: dataset_2D.dat :

# x    y    z
0   0   0
1   1   0
2   2   -4
3   3   -18
4   4   -48

In this case we would have to perform a 2D interpolation:

import numpy as np
from scipy.interpolate import interp1d, interp2d, interpnd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# Load the data:
x, y, z  = np.loadtxt('./dataset_2D.dat', skiprows = 1).T

# Create the function Z_inter for interpolation:
Z_inter = interp2d(x, y, z)

# Create the x_mesh and y_mesh :
x_mesh = np.linspace(1.0, 4, num=10)
y_mesh = np.linspace(1.0, 4, num=10)
print x_mesh
print y_mesh

# We calculate the z-interpolated of this x_mesh and y_mesh :
Z_interpolated = Z_inter(x_mesh, y_mesh)
print Z_interpolated
print type(Z_interpolated)
print Z_interpolated.shape

# plot:
fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(x, y, z, c='r', marker='o')
plt.legend(['data'], loc='lower left',  prop={'size':12})
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')

plt.show()

This plots the following:

where the scattered data is shown again in red dots, to be consistent with the 2D plot.

I do not know how to interpret the  Z_interpolated result:

According to the printing lines for the above code,
Z_interpolated is a n-dimensional numpy array, of shape (10,10). In other words, a 2D matrix with 10 rows and 10 columns.

I would have expected an interpolated z[i] value for each value of x_mesh[i] and y_mesh[i] Why I do not receive this ?

How could I plot also in the 3D plot the interpolated data (just like the black crosses in the 2D plot)?

Body:
Interpretation of Z_interpolated: your 1-D x_mesh and y_mesh defines a mesh on which to interpolate. Your 2-D interpolation return z is therefore a 2D array with shape (len(y), len(x)) which matches np.meshgrid(x_mesh, y_mesh). As you can see, your z[i, i], instead of z[i], is the expected value for x_mesh[i] and y_mesh[i]. And it just has a lot more, all values on the mesh.

A potential plot to show all interpolated data:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import interp2d

# Your original function
x = y = np.arange(0, 5, 0.1)
xx, yy = np.meshgrid(x, y)
zz = 2 * (xx ** 2) - (xx ** 3) - (yy ** 2)

# Your scattered points
x = y = np.arange(0, 5)
z = [0, 0, -4, -18, -48]

# Your interpolation
Z_inter = interp2d(x, y, z)
x_mesh = y_mesh = np.linspace(1.0, 4, num=10)
Z_interpolated = Z_inter(x_mesh, y_mesh)

fig = plt.figure()
ax = fig.gca(projection='3d')
# Plot your original function
ax.plot_surface(xx, yy, zz, color='b', alpha=0.5)
# Plot your initial scattered points
ax.scatter(x, y, z, color='r', marker='o')
# Plot your interpolation data
X_real_mesh, Y_real_mesh = np.meshgrid(x_mesh, y_mesh)
ax.scatter(X_real_mesh, Y_real_mesh, Z_interpolated, color='g', marker='^')
plt.show()


答:
You can use a capital register to append to a register. First clear a register by either doing :let @a='' or qaq. Then execute your command.

```<code>:g/^/+d A
</code>```

Now your results are in the "a register. e.g. "ap.

Assuming you are pasting this all at the bottom this could look like the following all together:

```<code>:let @a=''
:g/^/+d A
:$pu a
</code>```

Note: this is equivalent to :g/^/+m$

For more help see:

```<code>:h :let-@
:h :d
:h quote_alpha
</code>```

Title: How to paste multiple lines in Vim?

Body:
QUESTION:

I am deleting/copying every other line with :g/^/+d
However, when I try pasting all of those lines only the last line gets pasted. How do I paste every single line that I deleted/copied?

RESOLVED:

Thanks everyone! With your help I was able to finish my video (I work on a Youtube channel called Vim Girl where I make guided Vim Golf challenges.) Here's the link if you're interested: https://youtu.be/S9o5bHUAbP0

Body:
You can use a capital register to append to a register. First clear a register by either doing :let @a='' or qaq. Then execute your command.

:g/^/+d A

Now your results are in the "a register. e.g. "ap.

Assuming you are pasting this all at the bottom this could look like the following all together:

:let @a=''
:g/^/+d A
:$pu a

Note: this is equivalent to :g/^/+m$

For more help see:

:h :let-@
:h :d
:h quote_alpha


问:
How to encode bytes to utf8 in lua?
The string which is decompressed by zlib and been printed to log is in the format of below.

```<code> {\x22uid\x22:\x22CE57134D17B57E873D7E7434E0E21783\x22.............2\x5Cu0000\x5Cu0000\x22,\x22http://tgs.7477.com/adiframe/ky/01/index.html\x5Cu0000\x5Cu0000\x22,\x22http://s.csbew.com/acookie.html\x5Cu0000\x5Cu0000\x22],\x22ver\x22:\x221\x22}\x0A200
</code>```

How to encode the decompressed str so that it displays without something like '\xxx \u000' in lua?

答:
Try this unescape function to get characters from the hexadecimal representation:

```<code>    function unescape (s)
        s = string.gsub(s or '', "\\x(%x%x)", function (h) return string.char(tonumber(h,16)) end)
        return s
    end

    local str = [[{\x22uid\x22:\x22CE57134D17B57E873D7E7434E0E21783\x22.............2\x5Cu0000\x5Cu0000\x22,\x22http://tgs.7477.com/adiframe/ky/01/index.html\x5Cu0000\x5Cu0000\x22,\x22http://s.csbew.com/acookie.html\x5Cu0000\x5Cu0000\x22],\x22ver\x22:\x221\x22}\x0A200 ]]
    print( unescape(str) )
</code>```

Result:

```<code> {"uid":"CE57134D17B57E873D7E7434E0E21783".............2\u0000\u0000","http://tgs.7477.com/adiframe/ky/01/index.html\u0000\u0000","http://s.csbew.com/acookie.html\u0000\u0000"],"ver":"1"}
200
</code>```

Title: How to encode bytes to utf8 in lua?

Body:
The string which is decompressed by zlib and been printed to log is in the format of below.

 {\x22uid\x22:\x22CE57134D17B57E873D7E7434E0E21783\x22.............2\x5Cu0000\x5Cu0000\x22,\x22http://tgs.7477.com/adiframe/ky/01/index.html\x5Cu0000\x5Cu0000\x22,\x22http://s.csbew.com/acookie.html\x5Cu0000\x5Cu0000\x22],\x22ver\x22:\x221\x22}\x0A200

How to encode the decompressed str so that it displays without something like '\xxx \u000' in lua?

Body:
Try this unescape function to get characters from the hexadecimal representation:

    function unescape (s)
        s = string.gsub(s or '', "\\x(%x%x)", function (h) return string.char(tonumber(h,16)) end)
        return s
    end

    local str = [[{\x22uid\x22:\x22CE57134D17B57E873D7E7434E0E21783\x22.............2\x5Cu0000\x5Cu0000\x22,\x22http://tgs.7477.com/adiframe/ky/01/index.html\x5Cu0000\x5Cu0000\x22,\x22http://s.csbew.com/acookie.html\x5Cu0000\x5Cu0000\x22],\x22ver\x22:\x221\x22}\x0A200 ]]
    print( unescape(str) )

Result:

 {"uid":"CE57134D17B57E873D7E7434E0E21783".............2\u0000\u0000","http://tgs.7477.com/adiframe/ky/01/index.html\u0000\u0000","http://s.csbew.com/acookie.html\u0000\u0000"],"ver":"1"}
200


问:
Dynamically generate table using Jquery
I use JQuery version 1.8.4 and jquery-ui-1.9.2

I have this array:

```<code>window.mapData.Layers = [{id:1,Title:water}{id:2,Title:land}{id:4,Title:data}{id:1,Title:info}]
</code>```

I try to create table with some text and two buttons.

Each row in table have to display title the property of object from Layers array
and two buttons edit and delete.Each button have to sent as parameter the id of the property to handler when it clicked.

Here is the code:

```<code>(function () {
    var content = $('<table>')
    $(window.mapData.Layers).each(function (i, j) {
        content += '<tr><td>' + j.Title + '</td><td>' + $('<button/>')
    .text('Edit').onClick('eventHandler').params('j.id') +'</td>'+'<td>'+$('<button/>').text('Delete').onClick('eventHandler').params('j.id')+'</td>'+'</td></tr>'})

        $('#vectorLayerslist').append(content);
    }())
</code>```

Here is result that I get:

```<code>water   [object Object] [object Object]
land    [object Object] [object Object]
data    [object Object] [object Object]
info    [object Object] [object Object]
</code>```

But it's not works.As you can see above it's generate only text but not buttons.
Any idea why buttons not generated? If there is any more elegant way to achieve my task?

答:
Build the table as string, then append the string once.

Make use of jQuery's event propagation for dynamically created elements.

var Layers = [{id:1,Title:'water'},{id:2,Title:'land'},{id:4,Title:'data'},{id:5,Title:'info'}];

var vectorLayersList = $('#vectorLayerslist');

// build the table
var content = '
';
    content += '

';
    content += 'Title	';
    content += 'Actions	';
    content += '

';
$.each(Layers, function () {
    // we'll store the ID in HTML5 data-attribute for later
    content += '
';
    content += '' + this.Title + '	';
    // give classes to your buttons for later
    content += '<button type="button" class="edit">Edit</button>	';
    content += '<button type="button" class="delete">Delete</button>	';
    content += '
';
});
content += '

';

// append the table once
vectorLayersList.append(content);

// attach event handlers
vectorLayersList.on('click', '.edit', function () {
    var id = $(this).closest('tr').data('id');
    console.log('editing ' + id);
});

vectorLayersList.on('click', '.delete', function () {
    var id = $(this).closest('tr').data('id');
    console.log('deleting ' + id);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="vectorLayerslist"></div></code>```

Title: Dynamically generate table using Jquery

Body:
I use JQuery version 1.8.4 and jquery-ui-1.9.2

I have this array:

window.mapData.Layers = [{id:1,Title:water}{id:2,Title:land}{id:4,Title:data}{id:1,Title:info}]

I try to create table with some text and two buttons.

Each row in table have to display title the property of object from Layers array
and two buttons edit and delete.Each button have to sent as parameter the id of the property to handler when it clicked.

Here is the code:

(function () {
    var content = $('
')
    $(window.mapData.Layers).each(function (i, j) {
        content += '
' + j.Title + '	' + $('<button/>')
    .text('Edit').onClick('eventHandler').params('j.id') +'	'+''+$('<button/>').text('Delete').onClick('eventHandler').params('j.id')+'	'+'
'})

        $('#vectorLayerslist').append(content);
    }())

Here is result that I get:

water   [object Object] [object Object]
land    [object Object] [object Object]
data    [object Object] [object Object]
info    [object Object] [object Object]

But it's not works.As you can see above it's generate only text but not buttons.
Any idea why buttons not generated? If there is any more elegant way to achieve my task?

Body:
Build the table as string, then append the string once.

Make use of jQuery's event propagation for dynamically created elements.

var Layers = [{id:1,Title:'water'},{id:2,Title:'land'},{id:4,Title:'data'},{id:5,Title:'info'}];

var vectorLayersList = $('#vectorLayerslist');

// build the table
var content = '<table>';
    content += '<thead><tr>';
    content += '<th>Title</th>';
    content += '<th colspan="2">Actions</th>';
    content += '</tr></thead><tbody>';
$.each(Layers, function () {
    // we'll store the ID in HTML5 data-attribute for later
    content += '<tr data-id="' + this.id + '">';
    content += '<td>' + this.Title + '</td>';
    // give classes to your buttons for later
    content += '<td><button type="button" class="edit">Edit</button></td>';
    content += '<td><button type="button" class="delete">Delete</button></td>';
    content += '</tr>';
});
content += '</tbody></table>';

// append the table once
vectorLayersList.append(content);

// attach event handlers
vectorLayersList.on('click', '.edit', function () {
    var id = $(this).closest('tr').data('id');
    console.log('editing ' + id);
});

vectorLayersList.on('click', '.delete', function () {
    var id = $(this).closest('tr').data('id');
    console.log('deleting ' + id);
});

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

<div id="vectorLayerslist"></div>


答:
I can see two solutions here.

First: you can process those GET parameters on the server where the twitter.js is hosted, so that it will dynamically change the js file. For example, you file is:

```<code>var handle = {{ handle }};
</code>```

And your server somehow processes the file, replacing that twitter.js template file dependent on what request was sent.

The second option would be to set the global variables on the page where twitter.js is loaded, like this:

```<code><script type="text/javascript">
    window.twitter_js_handle = 'aplusk';
</script>
<script type="text/javascript" src="http://domain.com/twitter.js" />
</code>```

And in twitter.js:

```<code>var handle = window.twitter_js_handle || null;
</code>```

Title: In Javascript, is it possible to pass a variable into <script> "src" parameter?

Body: Is it possible in Javascript to pass a variable through the src parameter? ie.

Body:
I can see two solutions here.

First: you can process those GET parameters on the server where the twitter.js is hosted, so that it will dynamically change the js file. For example, you file is:

var handle = {{ handle }};

And your server somehow processes the file, replacing that twitter.js template file dependent on what request was sent.

The second option would be to set the global variables on the page where twitter.js is loaded, like this:

<script type="text/javascript">
    window.twitter_js_handle = 'aplusk';
</script>
<script type="text/javascript" src="http://domain.com/twitter.js" />

And in twitter.js:

var handle = window.twitter_js_handle || null;


问:
Cannot get the foreign key constraint from another table to display in SQL-Server
I have 3 tables and the schema setup is like this:

tenant object: tenant id, first name, last name, phone, email, apartment id

apartment object: apartment id, address, square footage, monthly utility fee, monthly parking fee, last cleaning date

contract object: contract id, apartment id, tenant id, start date, end date, monthly rent

Here is my script:

```<code>CREATE TABLE [dbo].[Contract]
(
    [ContractId] INT IDENTITY (1, 1) NOT NULL,
    [StartDate]        DATETIME NULL,
    [EndDate]     DATETIME NULL,
    [MonthlyRent]    FLOAT NULL,
    [AptId] INT NOT NULL,
    [TenantId] INT NOT NULL,
    PRIMARY KEY CLUSTERED ([ContractId] ASC),
    CONSTRAINT [FK_dbo.Contract_dbo.Apartment_AptId] FOREIGN KEY ([AptId])
        REFERENCES [dbo].[Apartment] ([AptId]) ON DELETE CASCADE,
    CONSTRAINT [FK_dbo.Contract_dbo.Tenant_TenantId] FOREIGN KEY ([TenantId])
        REFERENCES [dbo].[Tenant] ([TenantId]) ON DELETE CASCADE
)
</code>```

It complains when I am trying to add the foreign key constraint for the Apartment table. I know why it is because the Tenant Table already holds the Apartment foreign key constraint when I am trying to include it into the Contract table. But I still need to include the AptId column in the Contract table and populate it with the correct Ids. Is there a way to do that without having to do an inner join of sort?

答:
The issue which you seem to be running into is a cyclical or circular reference.

On delete cascade will delete all references to the given record as a foreign key. Case in point, if you delete a record in the apartment table, all tenant records referencing that apartment will be deleted. The issue which you seem to have is that you will have two correct "paths" or ways in which a contract record can be deleted, and a third path which is causing the trouble:

A record in the apartment table gets deleted

A record in the tenant table gets deleted.

A record in the apartment table gets deleted, which in turn will delete the contracts for the given tenant (this is the troublesome piece).

Your question asks for a way to keep the FK in place (in terms of not requiring a join), without running into this issue. You can do that with the following modification to your create table script:

I commented out your apartment_id field and replaced it with an identical one albeit without the "on delete cascade" clause. Since that was the issue, you can still keep the FK without running into a circular reference.

```<code>CREATE TABLE [dbo].[Contract]
(
    [ContractId] INT IDENTITY (1, 1) NOT NULL,
    [StartDate]        DATETIME NULL,
    [EndDate]     DATETIME NULL,
    [MonthlyRent]    FLOAT NULL,
    [AptId] INT NOT NULL,
    [TenantId] INT NOT NULL,
    PRIMARY KEY CLUSTERED ([ContractId] ASC),
    /*CONSTRAINT [FK_dbo.Contract_dbo.Apartment_AptId] FOREIGN KEY ([AptId])
        REFERENCES [dbo].[Apartment] ([AptId]) ON DELETE CASCADE,*/
    CONSTRAINT [FK_dbo.Contract_dbo.Apartment_AptId] FOREIGN KEY ([AptId])
            REFERENCES [dbo].[Apartment] ([AptId]),
    CONSTRAINT [FK_dbo.Contract_dbo.Tenant_TenantId] FOREIGN KEY ([TenantId])
        REFERENCES [dbo].[Tenant] ([TenantId]) ON DELETE CASCADE
)
</code>```

Give it a run and it should work just fine for you.

Body:
I have 3 tables and the schema setup is like this:

tenant object: tenant id, first name, last name, phone, email, apartment id

apartment object: apartment id, address, square footage, monthly utility fee, monthly parking fee, last cleaning date

contract object: contract id, apartment id, tenant id, start date, end date, monthly rent

Here is my script:

CREATE TABLE [dbo].[Contract]
(
    [ContractId] INT IDENTITY (1, 1) NOT NULL,
    [StartDate]        DATETIME NULL,
    [EndDate]     DATETIME NULL,
    [MonthlyRent]    FLOAT NULL,
    [AptId] INT NOT NULL,
    [TenantId] INT NOT NULL,
    PRIMARY KEY CLUSTERED ([ContractId] ASC),
    CONSTRAINT [FK_dbo.Contract_dbo.Apartment_AptId] FOREIGN KEY ([AptId])
        REFERENCES [dbo].[Apartment] ([AptId]) ON DELETE CASCADE,
    CONSTRAINT [FK_dbo.Contract_dbo.Tenant_TenantId] FOREIGN KEY ([TenantId])
        REFERENCES [dbo].[Tenant] ([TenantId]) ON DELETE CASCADE
)

It complains when I am trying to add the foreign key constraint for the Apartment table. I know why it is because the Tenant Table already holds the Apartment foreign key constraint when I am trying to include it into the Contract table. But I still need to include the AptId column in the Contract table and populate it with the correct Ids. Is there a way to do that without having to do an inner join of sort?

Body:
The issue which you seem to be running into is a cyclical or circular reference.

On delete cascade will delete all references to the given record as a foreign key. Case in point, if you delete a record in the apartment table, all tenant records referencing that apartment will be deleted. The issue which you seem to have is that you will have two correct "paths" or ways in which a contract record can be deleted, and a third path which is causing the trouble:

A record in the apartment table gets deleted

A record in the tenant table gets deleted.

A record in the apartment table gets deleted, which in turn will delete the contracts for the given tenant (this is the troublesome piece).

Your question asks for a way to keep the FK in place (in terms of not requiring a join), without running into this issue. You can do that with the following modification to your create table script:

I commented out your apartment_id field and replaced it with an identical one albeit without the "on delete cascade" clause. Since that was the issue, you can still keep the FK without running into a circular reference.

CREATE TABLE [dbo].[Contract]
(
    [ContractId] INT IDENTITY (1, 1) NOT NULL,
    [StartDate]        DATETIME NULL,
    [EndDate]     DATETIME NULL,
    [MonthlyRent]    FLOAT NULL,
    [AptId] INT NOT NULL,
    [TenantId] INT NOT NULL,
    PRIMARY KEY CLUSTERED ([ContractId] ASC),
    /*CONSTRAINT [FK_dbo.Contract_dbo.Apartment_AptId] FOREIGN KEY ([AptId])
        REFERENCES [dbo].[Apartment] ([AptId]) ON DELETE CASCADE,*/
    CONSTRAINT [FK_dbo.Contract_dbo.Apartment_AptId] FOREIGN KEY ([AptId])
            REFERENCES [dbo].[Apartment] ([AptId]),
    CONSTRAINT [FK_dbo.Contract_dbo.Tenant_TenantId] FOREIGN KEY ([TenantId])
        REFERENCES [dbo].[Tenant] ([TenantId]) ON DELETE CASCADE
)

Give it a run and it should work just fine for you.