问:
In angular2 I only want to add the addthis plugin to a specific route e.g. my /blog url but when I add a the script library it doesnt work
In Angular2 I only want to add the addthis plugin to a specific route e.g. my /blog url but when I add a the script library it doesn't work.

It only seems to work on the index.html and not on a specific view like blog.html

答:
Here you go:
I implemented it for my use case following ng-addthis but adding a few extra checks for Angular SSR.

```<code>/**
 * https://stackoverflow.com/questions/35538552/in-angular2-i-only-want-to-add-the-addthis-plugin-to-a-specific-route-e-g-my-b
 * Reinitiate add this.
 */

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Subscriber } from 'rxjs/Subscriber';

@Injectable()
export class AddThisService {
    constructor(){}
    private removeScript(){
        let element     = null;
        let divElements = null;
        let divElement  = null;

        element = document.getElementById('addthis-js');
        if (element) {
            element.parentNode.removeChild(element);
        }

        divElement = document.getElementById('_atssh');
        if (divElement) {
            divElement.style.display = "none";
        }

        divElements = document.getElementsByClassName('addthis-smartlayers');
        while (divElements.length > 0) {
            divElements[0].parentNode.removeChild(divElements[0]);
        }

        divElements = document.getElementsByClassName('addthis-smartlayers-desktop');
        while (divElements.length > 0) {
            divElements[0].parentNode.removeChild(divElements[0]);
        }

        divElements = document.getElementsByClassName('addthis-smartlayers-mobile');
        while (divElements.length > 0) {
            divElements[0].parentNode.removeChild(divElements[0]);
        }

        return true;
    }
    showLayers() {
        var divElements = null;
        var divElement  = null;
        console.log('what here..');

        divElement = document.getElementById('_atssh');
        if (divElement) {
            divElement.style.display = "block";
        }

        divElements = document.getElementsByClassName('addthis-smartlayers');
        for (var i = 0; i < divElements.length; i++) {
            divElements[0].style.display = "block";
        }

        divElements = document.getElementsByClassName('addthis-smartlayers-desktop');
        for (var i = 0; i < divElements.length; i++) {
            divElements[0].style.display = "block";
        }

        divElements = document.getElementsByClassName('addthis-smartlayers-mobile');
        for (var i = 0; i < divElements.length; i++) {
            divElements[0].style.display = "block";
        }

        return true;
    }

    hideLayers () {
            var divElements = null;
            var divElement  = null;

            divElement = document.getElementById('_atssh');
            if (divElement) {
                divElement.style.display = "none";
            }

            divElements = document.getElementsByClassName('addthis-smartlayers');
            for (var i = 0; i < divElements.length; i++) {
                divElements[0].style.display = "none";
            }

            divElements = document.getElementsByClassName('addthis-smartlayers-desktop');
            for (var i = 0; i < divElements.length; i++) {
                divElements[0].style.display = "none";
            }

            divElements = document.getElementsByClassName('addthis-smartlayers-mobile');
            for (var i = 0; i < divElements.length; i++) {
                divElements[0].style.display = "none";
            }

        return true;
    }

    private loadProject(key: string, hideLayers:boolean) {
        return Observable.create((observer: Subscriber<any>) => {
            switch (true) {
                case (!document || !window):
                /**
                 * For Angular Universal
                 */
                    observer.error('Cannot render it on Server');
                    observer.complete();
                case ((document.getElementById('addthis-js') != null)):

                    if (hideLayers) {
                        this.hideLayers();
                    } else {
                        this.showLayers();
                    }
                    if ((<any>window).addthis.layers && (<any>window).addthis.layers.refresh) {
                        (<any>window).addthis.layers.refresh();
                    }
                    observer.next(true);
                    observer.complete();
                    break;

                case (!key):
                    observer.error('no-project');
                    observer.complete();
                    break;

                default :
                    var script    = document.createElement('script');
                    script.type   = 'text/javascript';
                    script.id     = 'addthis-js';
                    script.async  = true;
                    script.src    = 'https://s7.addthis.com/js/300/addthis_widget.js#pubid=' + key;
                    script.onload = (ev: Event) =>{
                        if (hideLayers) {
                            this.hideLayers();
                        } else {
                            this.showLayers();
                        }
                        (<any>window).addthis.init();
                        observer.next(true);
                        observer.complete();
                    };

                    var first = document.getElementsByTagName('script')[0];
                    first.parentNode.insertBefore(script, first);
            }
        });
    }
    /**
     *
     * @param accountKey eg. ra-13245612346
     * @param hideLayers eg. true for hiding in a particular state and true for showing in another.
     */
    initAddThis(accountKey:string, hideLayers:boolean):Observable<any> {
        return this.loadProject(accountKey, hideLayers);
    };
}
</code>```

Then inject the service in your providers section of the main module and use it in ngAfterViewInit hook, like below:

```<code>ngAfterViewInit() {
    //Called after ngAfterContentInit when the component's view has been initialized. Applies to components only.
    //Add 'implements AfterViewInit' to the class.
    this._addThis.initAddThis('ra-123456asdf', false).subscribe();
}
</code>```

You can also use isPlatformBrowser method for checking platform before calling initAddThis method if you are using Angular Universal.

Body:
Here you go:
I implemented it for my use case following ng-addthis but adding a few extra checks for Angular SSR.

/**
 * https://stackoverflow.com/questions/35538552/in-angular2-i-only-want-to-add-the-addthis-plugin-to-a-specific-route-e-g-my-b
 * Reinitiate add this.
 */

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Subscriber } from 'rxjs/Subscriber';

@Injectable()
export class AddThisService {
    constructor(){}
    private removeScript(){
        let element     = null;
        let divElements = null;
        let divElement  = null;

        element = document.getElementById('addthis-js');
        if (element) {
            element.parentNode.removeChild(element);
        }

        divElement = document.getElementById('_atssh');
        if (divElement) {
            divElement.style.display = "none";
        }

        divElements = document.getElementsByClassName('addthis-smartlayers');
        while (divElements.length > 0) {
            divElements[0].parentNode.removeChild(divElements[0]);
        }

        divElements = document.getElementsByClassName('addthis-smartlayers-desktop');
        while (divElements.length > 0) {
            divElements[0].parentNode.removeChild(divElements[0]);
        }

        divElements = document.getElementsByClassName('addthis-smartlayers-mobile');
        while (divElements.length > 0) {
            divElements[0].parentNode.removeChild(divElements[0]);
        }

        return true;
    }
    showLayers() {
        var divElements = null;
        var divElement  = null;
        console.log('what here..');

        divElement = document.getElementById('_atssh');
        if (divElement) {
            divElement.style.display = "block";
        }

        divElements = document.getElementsByClassName('addthis-smartlayers');
        for (var i = 0; i < divElements.length; i++) {
            divElements[0].style.display = "block";
        }

        divElements = document.getElementsByClassName('addthis-smartlayers-desktop');
        for (var i = 0; i < divElements.length; i++) {
            divElements[0].style.display = "block";
        }

        divElements = document.getElementsByClassName('addthis-smartlayers-mobile');
        for (var i = 0; i < divElements.length; i++) {
            divElements[0].style.display = "block";
        }

        return true;
    }

    hideLayers () {
            var divElements = null;
            var divElement  = null;

            divElement = document.getElementById('_atssh');
            if (divElement) {
                divElement.style.display = "none";
            }

            divElements = document.getElementsByClassName('addthis-smartlayers');
            for (var i = 0; i < divElements.length; i++) {
                divElements[0].style.display = "none";
            }

            divElements = document.getElementsByClassName('addthis-smartlayers-desktop');
            for (var i = 0; i < divElements.length; i++) {
                divElements[0].style.display = "none";
            }

            divElements = document.getElementsByClassName('addthis-smartlayers-mobile');
            for (var i = 0; i < divElements.length; i++) {
                divElements[0].style.display = "none";
            }

        return true;
    }

    private loadProject(key: string, hideLayers:boolean) {
        return Observable.create((observer: Subscriber<any>) => {
            switch (true) {
                case (!document || !window):
                /**
                 * For Angular Universal
                 */
                    observer.error('Cannot render it on Server');
                    observer.complete();
                case ((document.getElementById('addthis-js') != null)):

                    if (hideLayers) {
                        this.hideLayers();
                    } else {
                        this.showLayers();
                    }
                    if ((<any>window).addthis.layers && (<any>window).addthis.layers.refresh) {
                        (<any>window).addthis.layers.refresh();
                    }
                    observer.next(true);
                    observer.complete();
                    break;

                case (!key):
                    observer.error('no-project');
                    observer.complete();
                    break;

                default :
                    var script    = document.createElement('script');
                    script.type   = 'text/javascript';
                    script.id     = 'addthis-js';
                    script.async  = true;
                    script.src    = 'https://s7.addthis.com/js/300/addthis_widget.js#pubid=' + key;
                    script.onload = (ev: Event) =>{
                        if (hideLayers) {
                            this.hideLayers();
                        } else {
                            this.showLayers();
                        }
                        (<any>window).addthis.init();
                        observer.next(true);
                        observer.complete();
                    };

                    var first = document.getElementsByTagName('script')[0];
                    first.parentNode.insertBefore(script, first);
            }
        });
    }
    /**
     *
     * @param accountKey eg. ra-13245612346
     * @param hideLayers eg. true for hiding in a particular state and true for showing in another.
     */
    initAddThis(accountKey:string, hideLayers:boolean):Observable<any> {
        return this.loadProject(accountKey, hideLayers);
    };
}

Then inject the service in your providers section of the main module and use it in ngAfterViewInit hook, like below:

ngAfterViewInit() {
    //Called after ngAfterContentInit when the component's view has been initialized. Applies to components only.
    //Add 'implements AfterViewInit' to the class.
    this._addThis.initAddThis('ra-123456asdf', false).subscribe();
}

You can also use isPlatformBrowser method for checking platform before calling initAddThis method if you are using Angular Universal.


来源: stackexchange

问:
Install PEAR on project local?
How to install pear on project local?
Only install system global (and copy manually to project local) ?</p>

答: See this page of the manual : Installation of a local PEAR copy on a shared host</p>

ContentLicense: CC BY-SA 2.5

Title: Install PEAR on project local?


问:
How to create a tkinter error message box
I am wanting to create a simple message box in Tkinter that appears and displays the exact error message.  Could anyone direct me to how this might be
 achieved in tkinter, I have not been able to find much on this topic.

E.g:

```<code>traceback.format_exc().replace(':', '-')
ctypes.windll.user32.MessageBoxW(0, "Error", "Have you checked your fridge?"d, 1)
                                                             ^
#'SyntaxError: invalid syntax'
</code>```

I am wanting to add this with pyinstaller.  I suppose pyinstaller creates a text file and you can see in cmd before it closes, but it would be nice if a message box appear with exact traceerror.

答:
This login system which will pop up messagebox when you provide wrong data for entry messagebox should be entered into the entry if not the messagebox will pop up prompting you an error as occured

```<code>from tkinter import *
from tkinter import messagebox

def top():
    if entry1.get() == "messagebox":
       log.destroy()
       root.deiconify()
    else:
       messagebox.showerror("error", "try again")
       messagebox.showinfo("my message","this is an example of showinfo\nmessagebox")
       messagebox.showwarning("warning", "show warning example in tkinter" )

root = Tk()
root.geometry("400x400")

log = Toplevel(root)
log.geometry("200x200")

label1 = Label(log, text="password")
entry1 = Entry(log)
button1 = Button(log, text="login", command=top)

label1.pack()
entry1.pack()
button1.pack(side="bottom")

lab = Label(root, text="welcome bro").pack()

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

ContentLicense: CC BY-SA 3.0

Body:
I am wanting to create a simple message box in Tkinter that appears and displays the exact error message.  Could anyone direct me to how this might be
 achieved in tkinter, I have not been able to find much on this topic.

E.g:

traceback.format_exc().replace(':', '-')
ctypes.windll.user32.MessageBoxW(0, "Error", "Have you checked your fridge?"d, 1)
                                                             ^
#'SyntaxError: invalid syntax'

I am wanting to add this with pyinstaller.  I suppose pyinstaller creates a text file and you can see in cmd before it closes, but it would be nice if a message box appear with exact traceerror.

Body:
This login system which will pop up messagebox when you provide wrong data for entry messagebox should be entered into the entry if not the messagebox will pop up prompting you an error as occured

from tkinter import *
from tkinter import messagebox

def top():
    if entry1.get() == "messagebox":
       log.destroy()
       root.deiconify()
    else:
       messagebox.showerror("error", "try again")
       messagebox.showinfo("my message","this is an example of showinfo\nmessagebox")
       messagebox.showwarning("warning", "show warning example in tkinter" )

root = Tk()
root.geometry("400x400")

log = Toplevel(root)
log.geometry("200x200")

label1 = Label(log, text="password")
entry1 = Entry(log)
button1 = Button(log, text="login", command=top)

label1.pack()
entry1.pack()
button1.pack(side="bottom")

lab = Label(root, text="welcome bro").pack()

root.withdraw()
root.mainloop()


问:
Which cmake property should hold privately linked shared libraries for imported targets?
Consider importing a target with find_package( foo REQUIRED ) that provides a shared library. Target foo itself depends on another shared library bar.dll, which is only used in its implementation and not visible in its headers. But as a client of foo I also have to deploy bar.dll in order to run my code.

So which property of the imported target foo should give me the information that I also have to deploy bar?

Should it be in LINK_INTERFACE_LIBRARIES, IMPORTED_LINK_INTERFACE_LIBRARIES, LINK_LIBRARIES, IMPORTED_LINK_DEPENDENT_LIBRARIES or something else?

Thank you for your time.

答:
Assuming you're on a "modern" version of cmake (3.anything), then you are looking for IMPORTED_LINK_DEPENDENT_LIBRARIES.

LINK_INTERFACE_LIBRARIES and IMPORTED_LINK_INTERFACE_LIBRARIES are both deprecated, so don't consider them.

LINK_LIBRARIES is for building a target; since you're importing a library with find_package, it shouldn't be of much use.

INTERFACE_LINK_LIBRARIES, on an imported target, tells you which libraries are dependencies in the interface (visible in the headers).


问:
How to get parameter from URL(Routing) Angular 2?
I tried to do that in ngOnInit() like:

ngOnInit() {
    this.route.queryParams
      .filter(params => params.type)
      .subscribe(params => {
        this.tab = params.type;
        this.setHeader();
      });
  }
```

<p>My URL is:</p>

<pre class="lang-none prettyprint-override"><code>http://localhost:4200/s/6/t/p/create/1
</code>```

Routing is:

{path: ':Id/t/p/create/:type', component: CalendarComponent},
```

答:
try that  :

this.route.snapshot.params["page"]
```

<p>the page is the query param so the route must be like that</p>

<pre class="lang-ts prettyprint-override"><code>const routes: Routes = [
  {
    path: 'page/:page',
    component: OrdersComponent,
    data: {
      title: 'Orders'
    }
  }
]
</code>```

don't forget the add the route into the constructor

constructor(private route: ActivatedRoute) { }
```

<p>and the import </p>

<pre class="lang-ts prettyprint-override"><code>import {ActivatedRoute} from "@angular/router";
</code>```

Body:
I tried to do that in ngOnInit() like:

ngOnInit() {
    this.route.queryParams
      .filter(params => params.type)
      .subscribe(params => {
        this.tab = params.type;
        this.setHeader();
      });
  }

My URL is:

http://localhost:4200/s/6/t/p/create/1

Routing is:

{path: ':Id/t/p/create/:type', component: CalendarComponent},

Body:
try that  :

this.route.snapshot.params["page"]

the page is the query param so the route must be like that

const routes: Routes = [
  {
    path: 'page/:page',
    component: OrdersComponent,
    data: {
      title: 'Orders'
    }
  }
]

don't forget the add the route into the constructor

constructor(private route: ActivatedRoute) { }

and the import

import {ActivatedRoute} from "@angular/router";

ContentLicense: CC BY-SA 4.0


问:
How to create 2d array with numpy random.choice for every rows?
I'm trying to create a 2d array (which is a six column and lots of rows) with numpy random choice with unique values between 1 and 50 for every row not all of the array

```<code>np.sort(np.random.choice(np.arange(1,50),size=(100,6),replace=False))
</code>```

But this raises an error.

```<code>ValueError: Cannot take a larger sample than population when 'replace=False'
</code>```

Is it possible to make this with an one liner without a loop

Edit

Okey i get the answer.

These are the results with jupyter %time cellmagic

```<code>#@James' solution
np.stack([np.random.choice(np.arange(1,50),size=6,replace=False) for i in range(1_000_000)])
Wall time: 25.1 s

#@Divakar's solution
np.random.rand(1_000_000, 50).argpartition(6,axis=1)[:,:6]+1
Wall time: 1.36 s

#@CoryKramer's solution
np.array([np.random.choice(np.arange(1, 50), size=6, replace=False) for _ in range(1_000_000)])
Wall time: 25.5 s
</code>```

I changed dtypes of np.empty and np.random.randint on @Paul Panzer's solution because it was not working on my pc.

```<code>3.6.0 |Anaconda custom (64-bit)| (default, Dec 23 2016, 11:57:41) [MSC v.1900 64 bit (AMD64)]
</code>```

Fastest one is

```<code>def pp(n):
    draw = np.empty((n, 6), dtype=np.int64)
    # generating random numbers is expensive, so draw a large one and
    # make six out of one
    draw[:, 0] = np.random.randint(0, 50*49*48*47*46*45, (n,),dtype=np.uint64)
    draw[:, 1:] = np.arange(50, 45, -1)
    draw = np.floor_divide.accumulate(draw, axis=-1)
    draw[:, :-1] -= draw[:, 1:] * np.arange(50, 45, -1)
    # map the shorter ranges (:49, :48, :47) to the non-occupied
    # positions; this amounts to incrementing for each number on the
    # left that is not larger. the nasty bit: if due to incrementing
    # new numbers on the left are "overtaken" then for them we also
    # need to increment.
    for i in range(1, 6):
        coll = np.sum(draw[:, :i] <= draw[:, i, None], axis=-1)
        collidx = np.flatnonzero(coll)
        if collidx.size == 0:
            continue
        coll = coll[collidx]
        tot = coll
        while True:
            draw[collidx, i] += coll
            coll = np.sum(draw[collidx, :i] <= draw[collidx, i, None],  axis=-1)
            relidx = np.flatnonzero(coll > tot)
            if relidx.size == 0:
                break
            coll, tot = coll[relidx]-tot[relidx], coll[relidx]
            collidx = collidx[relidx]

    return draw + 1

#@Paul Panzer' solution
pp(1_000_000)
Wall time: 557 ms
</code>```

Thank you all.

Body:
I'm trying to create a 2d array (which is a six column and lots of rows) with numpy random choice with unique values between 1 and 50 for every row not all of the array

np.sort(np.random.choice(np.arange(1,50),size=(100,6),replace=False))

But this raises an error.

ValueError: Cannot take a larger sample than population when 'replace=False'

Is it possible to make this with an one liner without a loop

Edit

Okey i get the answer.

These are the results with jupyter %time cellmagic

#@James' solution
np.stack([np.random.choice(np.arange(1,50),size=6,replace=False) for i in range(1_000_000)])
Wall time: 25.1 s

#@Divakar's solution
np.random.rand(1_000_000, 50).argpartition(6,axis=1)[:,:6]+1
Wall time: 1.36 s

#@CoryKramer's solution
np.array([np.random.choice(np.arange(1, 50), size=6, replace=False) for _ in range(1_000_000)])
Wall time: 25.5 s

I changed dtypes of np.empty and np.random.randint on @Paul Panzer's solution because it was not working on my pc.

3.6.0 |Anaconda custom (64-bit)| (default, Dec 23 2016, 11:57:41) [MSC v.1900 64 bit (AMD64)]

Fastest one is

def pp(n):
    draw = np.empty((n, 6), dtype=np.int64)
    # generating random numbers is expensive, so draw a large one and
    # make six out of one
    draw[:, 0] = np.random.randint(0, 50*49*48*47*46*45, (n,),dtype=np.uint64)
    draw[:, 1:] = np.arange(50, 45, -1)
    draw = np.floor_divide.accumulate(draw, axis=-1)
    draw[:, :-1] -= draw[:, 1:] * np.arange(50, 45, -1)
    # map the shorter ranges (:49, :48, :47) to the non-occupied
    # positions; this amounts to incrementing for each number on the
    # left that is not larger. the nasty bit: if due to incrementing
    # new numbers on the left are "overtaken" then for them we also
    # need to increment.
    for i in range(1, 6):
        coll = np.sum(draw[:, :i] <= draw[:, i, None], axis=-1)
        collidx = np.flatnonzero(coll)
        if collidx.size == 0:
            continue
        coll = coll[collidx]
        tot = coll
        while True:
            draw[collidx, i] += coll
            coll = np.sum(draw[collidx, :i] <= draw[collidx, i, None],  axis=-1)
            relidx = np.flatnonzero(coll > tot)
            if relidx.size == 0:
                break
            coll, tot = coll[relidx]-tot[relidx], coll[relidx]
            collidx = collidx[relidx]

    return draw + 1

#@Paul Panzer' solution
pp(1_000_000)
Wall time: 557 ms

Thank you all.

Body:
Here's a vectorized approach with rand+argsort/argpartition trick from here -

np.random.rand(rows, 50).argpartition(6,axis=1)[:,:6]+1

Sample run -

In [41]: rows = 10

In [42]: np.random.rand(rows, 50).argpartition(6,axis=1)[:,:6]+1
Out[42]:
array([[ 1,  9,  3, 26, 14, 44],
       [32, 20, 27, 13, 25, 45],
       [40, 12, 47, 16, 10, 29],
       [ 6, 36, 32, 16, 18,  4],
       [42, 46, 24,  9,  1, 31],
       [15, 25, 47, 42, 34, 24],
       [ 7, 16, 49, 31, 40, 20],
       [28, 17, 47, 36,  8, 44],
       [ 7, 42, 14,  4, 17, 35],
       [39, 19, 37,  7,  8, 36]])

Just to prove the random-ness -

In [56]: rows = 1000000

In [57]: out = np.random.rand(rows, 50).argpartition(6,axis=1)[:,:6]+1

In [58]: np.bincount(out.ravel())[1:]
Out[58]:
array([120048, 120026, 119942, 119838, 119885, 119669, 119965, 119491,
       120280, 120108, 120293, 119399, 119917, 119974, 120195, 119796,
       119887, 119505, 120235, 119857, 119499, 120560, 119891, 119693,
       120081, 120369, 120011, 119714, 120218, 120581, 120111, 119867,
       119791, 120265, 120457, 120048, 119813, 119702, 120266, 120445,
       120016, 120190, 119576, 119737, 120153, 120215, 120144, 120196,
       120218, 119863])

Timings on one million rows of data -

In [43]: rows = 1000000

In [44]: %timeit np.random.rand(rows, 50).argpartition(6,axis=1)[:,:6]+1
1 loop, best of 3: 1.07 s per loop


问:
transform json to key/value file in bash
I have a JSON which looks like this:

```<code>{
    "lorem": "ipsum",
    "dolor": "sid",
    "data": {
        "key1": "value1",
        "key2": "value2"
    }
}
</code>```

and I want an output which is ini like where I only need the content of 'data' (which is always flat, no branches). The output should look like this:

```<code>key1=value1
key2=value2
</code>```

I can use jq (just don't get it running) but have to use a bash script for it. Can anyone help?

答:
This will work in BASH.

```<code>#!/bin/bash

all_keys=$( cat input.txt );

while read key
do
    grep "$key" ./text.txt | awk -F':' '{ print $1"="$2}' | tr -d '[", ]'
done <<< "$all_keys"
</code>```

Assuming you values are in text.txt and that you have your keys in input.txt.

Regards!

Body:
I have a JSON which looks like this:

{
    "lorem": "ipsum",
    "dolor": "sid",
    "data": {
        "key1": "value1",
        "key2": "value2"
    }
}

and I want an output which is ini like where I only need the content of 'data' (which is always flat, no branches). The output should look like this:

key1=value1
key2=value2

I can use jq (just don't get it running) but have to use a bash script for it. Can anyone help?

Body:
This will work in BASH.

#!/bin/bash

all_keys=$( cat input.txt );

while read key
do
    grep "$key" ./text.txt | awk -F':' '{ print $1"="$2}' | tr -d '[", ]'
done <<< "$all_keys"

Assuming you values are in text.txt and that you have your keys in input.txt.

Regards!


问:
TypeError: execv() arg 2 must contain only strings (subprocess and unicode)
I have this Python2.7 script which works if LANG != 'C':

```<code># -*- coding: utf-8 -*-
from __future__ import absolute_import, division, unicode_literals, print_function

import os
import subprocess

import sys

print('LANG: {}'.format(os.environ['LANG']))
print('sys.getdefaultencoding(): {}'.format(sys.getdefaultencoding()))
print('sys.getfilesystemencoding(): {}'.format(sys.getfilesystemencoding()))
subprocess.check_call(['echo', 'Umlauts üöä'])
</code>```

Call on linux shell:

```<code>user@host:~$ python src/execv-arg-2-must-contain-only-strings.py
LANG: de_DE.UTF-8
sys.getdefaultencoding(): ascii
sys.getfilesystemencoding(): UTF-8
Umlauts üöä
</code>```

But this fails:

```<code>user@host:~$ LANG=C python src/execv-arg-2-must-contain-only-strings.py
LANG: C
sys.getdefaultencoding(): ascii
sys.getfilesystemencoding(): ANSI_X3.4-1968
Traceback (most recent call last):
  File "src/execv-arg-2-must-contain-only-strings.py", line 12, in <module>
    subprocess.check_call(['echo', 'Umlauts üöä'])
  File "/usr/lib/python2.7/subprocess.py", line 536, in check_call
    retcode = call(*popenargs, **kwargs)
  File "/usr/lib/python2.7/subprocess.py", line 523, in call
    return Popen(*popenargs, **kwargs).wait()
  File "/usr/lib/python2.7/subprocess.py", line 711, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1343, in _execute_child
    raise child_exception
TypeError: execv() arg 2 must contain only strings
</code>```

What can I do to make this script work on Python2.7 with LANG=C?

答:
I didn't post it as an answer as I don't have means of checking its correctness atm. but in principle, if you want to send data as a subprocess/shell argument you have to match the encoding of the said data (and then decode it back in the receiving subprocess) or Python won't know how to pack the argument.

So, if you're working with a utf-8 literal (as defined in your encoding header) and you want to send it to a subprocess, you should first decode it to native unicode object, then encode it to whatever is the system's encoding of the current environment, e.g.:

```<code>literal_argument = "Umlauts üöä"  # string literal
unicode_argument = literal_argument.decode("utf-8")  # unicode
encoded_argument = unicode_argument.encode(sys.getdefaultencoding())  # sys encoded

subprocess.check_call(['echo', encoded_argument])
</code>```

While safer, it can still break on non-standard shells. Where possible use a STDIN pipe of your subprocess to pass data that is not suitable for your current shell as an argument - then you don't have to worry about different code pages as long as both processes agree on what encoding to use.

Body:
I have this Python2.7 script which works if LANG != 'C':

# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, unicode_literals, print_function

import os
import subprocess

import sys

print('LANG: {}'.format(os.environ['LANG']))
print('sys.getdefaultencoding(): {}'.format(sys.getdefaultencoding()))
print('sys.getfilesystemencoding(): {}'.format(sys.getfilesystemencoding()))
subprocess.check_call(['echo', 'Umlauts üöä'])

Call on linux shell:

user@host:~$ python src/execv-arg-2-must-contain-only-strings.py
LANG: de_DE.UTF-8
sys.getdefaultencoding(): ascii
sys.getfilesystemencoding(): UTF-8
Umlauts üöä

But this fails:

user@host:~$ LANG=C python src/execv-arg-2-must-contain-only-strings.py
LANG: C
sys.getdefaultencoding(): ascii
sys.getfilesystemencoding(): ANSI_X3.4-1968
Traceback (most recent call last):
  File "src/execv-arg-2-must-contain-only-strings.py", line 12, in <module>
    subprocess.check_call(['echo', 'Umlauts üöä'])
  File "/usr/lib/python2.7/subprocess.py", line 536, in check_call
    retcode = call(*popenargs, **kwargs)
  File "/usr/lib/python2.7/subprocess.py", line 523, in call
    return Popen(*popenargs, **kwargs).wait()
  File "/usr/lib/python2.7/subprocess.py", line 711, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1343, in _execute_child
    raise child_exception
TypeError: execv() arg 2 must contain only strings

What can I do to make this script work on Python2.7 with LANG=C?

Body:
I didn't post it as an answer as I don't have means of checking its correctness atm. but in principle, if you want to send data as a subprocess/shell argument you have to match the encoding of the said data (and then decode it back in the receiving subprocess) or Python won't know how to pack the argument.

So, if you're working with a utf-8 literal (as defined in your encoding header) and you want to send it to a subprocess, you should first decode it to native unicode object, then encode it to whatever is the system's encoding of the current environment, e.g.:

literal_argument = "Umlauts üöä"  # string literal
unicode_argument = literal_argument.decode("utf-8")  # unicode
encoded_argument = unicode_argument.encode(sys.getdefaultencoding())  # sys encoded

subprocess.check_call(['echo', encoded_argument])

While safer, it can still break on non-standard shells. Where possible use a STDIN pipe of your subprocess to pass data that is not suitable for your current shell as an argument - then you don't have to worry about different code pages as long as both processes agree on what encoding to use.


问:
Separating string by semicolon into xml elements using xslt
I have transformated xml:

```<code><import>
    <issue>
        <article>
            <languageVersion>
                <title>some title</title>
                <keywords>keyword1; keyword2; keyword3</keywords>
            </languageVersion>
        </article>
        <article>
            <languageVersion>
                <title>some title</title>
                <keywords>keyword1; keyword2; keyword3</keywords>
            </languageVersion>
        </article>
    </issue>
</import>
</code>```

And now I want to separate all words in tag  by semicolon using xslt transformation, so the target xml would be like this:

```<code><import>
    <issue>
        <article>
            <languageVersion>
                <title>some title</title>
                <keywords>
                    <keyword>keyword1</keyword>
                    <keyword>keyword2</keyword>
                    <keyword>keyword3</keyword>
                </keywords>
            </languageVersion>
        </article>
        <article>
            <languageVersion>
                <title>some title</title>
                <keywords>
                    <keyword>keyword1</keyword>
                    <keyword>keyword2</keyword>
                    <keyword>keyword3</keyword>
                </keywords>
            </languageVersion>
        </article>
        <article>
    </issue>
</import>
</code>```

How can I do this using XSLT transformation? I tried already already using code from there but unfortunatelly the code was destroying rest of xml elements:

```<code><xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes" indent="yes"/>
    <xsl:strip-space elements="*"/>
    <xsl:template match="keywords">
        <keywords>
            <xsl:apply-templates/>
        </keywords>
    </xsl:template>
    <xsl:template match="keywords" name="split">
        <xsl:param name="pText" select="."/>
        <xsl:param name="pItemElementName" select="'keyword'"/>
        <xsl:if test="string-length($pText) > 0">
            <xsl:variable name="vNextItem" select=
      "substring-before(concat($pText, ';'), ';')"/>
            <xsl:element name="{$pItemElementName}">
                <xsl:value-of select="$vNextItem"/>
            </xsl:element>
            <xsl:call-template name="split">
                <xsl:with-param name="pText" select="substring-after($pText, ';')"/>
                <xsl:with-param name="pItemElementName" select="$pItemElementName"/>
            </xsl:call-template>
        </xsl:if>
    </xsl:template>
</xsl:stylesheet>
</code>```

答:
You have two templates matching keywords which is considered an error in XSLT if they have the same priority. According to the spec...

An XSLT processor may signal the error; if it does not signal the
  error, it must recover by choosing, from amongst the matching template
  rules that are left, the one that occurs last in the stylesheet.

So, in your case, it is only the second template that is being used.

However, all you need to do is remove the "match" on the the second template to make it just a named template, and change the first template to call the named template directly. You should also add the identity template, to take care of existing elements, and then your job will be done

Try this XSLT

```<code><xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="keywords">
        <xsl:copy>
            <xsl:call-template name="split" />
        </xsl:copy>
    </xsl:template>

    <xsl:template name="split">
        <xsl:param name="pText" select="."/>
        <xsl:param name="pItemElementName" select="'keyword'"/>
        <xsl:if test="string-length($pText) > 0">
            <xsl:variable name="vNextItem" select=
      "substring-before(concat($pText, ';'), ';')"/>
            <xsl:element name="{$pItemElementName}">
                <xsl:value-of select="$vNextItem"/>
            </xsl:element>
            <xsl:call-template name="split">
                <xsl:with-param name="pText" select="substring-after($pText, ';')"/>
                <xsl:with-param name="pItemElementName" select="$pItemElementName"/>
            </xsl:call-template>
        </xsl:if>
    </xsl:template>
</xsl:stylesheet>
</code>```

Body:
I have transformated xml:

<import>
    <issue>

            <languageVersion>
                <title>some title</title>
                <keywords>keyword1; keyword2; keyword3</keywords>
            </languageVersion>

            <languageVersion>
                <title>some title</title>
                <keywords>keyword1; keyword2; keyword3</keywords>
            </languageVersion>

    </issue>
</import>

And now I want to separate all words in tag  by semicolon using xslt transformation, so the target xml would be like this:

<import>
    <issue>

            <languageVersion>
                <title>some title</title>
                <keywords>
                    <keyword>keyword1</keyword>
                    <keyword>keyword2</keyword>
                    <keyword>keyword3</keyword>
                </keywords>
            </languageVersion>

            <languageVersion>
                <title>some title</title>
                <keywords>
                    <keyword>keyword1</keyword>
                    <keyword>keyword2</keyword>
                    <keyword>keyword3</keyword>
                </keywords>
            </languageVersion>

    </issue>
</import>

How can I do this using XSLT transformation? I tried already already using code from there but unfortunatelly the code was destroying rest of xml elements:

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes" indent="yes"/>
    <xsl:strip-space elements="*"/>
    <xsl:template match="keywords">
        <keywords>
            <xsl:apply-templates/>
        </keywords>
    </xsl:template>
    <xsl:template match="keywords" name="split">
        <xsl:param name="pText" select="."/>
        <xsl:param name="pItemElementName" select="'keyword'"/>
        <xsl:if test="string-length($pText) > 0">
            <xsl:variable name="vNextItem" select=
      "substring-before(concat($pText, ';'), ';')"/>
            <xsl:element name="{$pItemElementName}">
                <xsl:value-of select="$vNextItem"/>
            </xsl:element>
            <xsl:call-template name="split">
                <xsl:with-param name="pText" select="substring-after($pText, ';')"/>
                <xsl:with-param name="pItemElementName" select="$pItemElementName"/>
            </xsl:call-template>
        </xsl:if>
    </xsl:template>
</xsl:stylesheet>

Body:
You have two templates matching keywords which is considered an error in XSLT if they have the same priority. According to the spec...

An XSLT processor may signal the error; if it does not signal the
  error, it must recover by choosing, from amongst the matching template
  rules that are left, the one that occurs last in the stylesheet.

So, in your case, it is only the second template that is being used.

However, all you need to do is remove the "match" on the the second template to make it just a named template, and change the first template to call the named template directly. You should also add the identity template, to take care of existing elements, and then your job will be done

Try this XSLT

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="keywords">
        <xsl:copy>
            <xsl:call-template name="split" />
        </xsl:copy>
    </xsl:template>

    <xsl:template name="split">
        <xsl:param name="pText" select="."/>
        <xsl:param name="pItemElementName" select="'keyword'"/>
        <xsl:if test="string-length($pText) > 0">
            <xsl:variable name="vNextItem" select=
      "substring-before(concat($pText, ';'), ';')"/>
            <xsl:element name="{$pItemElementName}">
                <xsl:value-of select="$vNextItem"/>
            </xsl:element>
            <xsl:call-template name="split">
                <xsl:with-param name="pText" select="substring-after($pText, ';')"/>
                <xsl:with-param name="pItemElementName" select="$pItemElementName"/>
            </xsl:call-template>
        </xsl:if>
    </xsl:template>
</xsl:stylesheet>


问:
JIT optimization in scenario combining inline and non-mutable boolean module property
In the following program,

```<code>module Program

let condition = System.DateTime.Now.Millisecond % 2 = 0

let inline reliesOnCondition (x:int) =
    if condition then
        printfn "%i" x

[<EntryPoint>]
let main args =
    reliesOnConditional System.DateTime.Now.Second
    0
</code>```

will the JIT optimize away the expression reliesOnCondition System.DateTime.Now.Second if condition turns out to be false upon module loading?

答: The upvoted answer is incorrect, a property accessor indirection does not in general prevent the JIT optimizer from omitting dead code.  Most simple ones get inlined, their compile time values are considered.  Which means that it will not optimize away the expression since the value of condition is only known at run time.  The fact that the code is jitted after the condition value is already known doesn't change this, the optimizer must be able to determine the value statically.  Only a literal will suffice here, you'd get one with conditional compilation (#if in C#).  Check this answer for more background info on the optimizer.

Body:
In the following program,

module Program

let condition = System.DateTime.Now.Millisecond % 2 = 0

let inline reliesOnCondition (x:int) =
    if condition then
        printfn "%i" x

[<EntryPoint>]
let main args =
    reliesOnConditional System.DateTime.Now.Second
    0

will the JIT optimize away the expression reliesOnCondition System.DateTime.Now.Second if condition turns out to be false upon module loading?


问:
Sort array from Axios React
If I sort array I cant use map.

```<code>var arrQuestByDate = new Array();
action.payload.data.forEach(function(item){
  if(typeof(arrQuestByDate[item.date])==='undefined'){
    arrQuestByDate[item.date]= new Array();
  }
  arrQuestByDate[item.date].push(item);
  console.log(arrQuestByDate[item.date].length) //this output good value
})
console.log(arrQuestByDate.length) //this output 0
</code>```

I dont know why my array length is 0

答:
You can use groupBy function from lodash.
If you don't want to use external library, this code shoudl work</p>

```<code>var quotestByDate = action.payload.data
    .reduce( function(acc, quote) {
        if (!acc[quote.date]) {
            acc[quote.date] = [];
        }
        acc[quote.date].push(quote);
        return acc;
    }, {});

console.log(Object.keys(quotestByDate).length);
</code>```

Title: Sort array from Axios React

Body:
If I sort array I cant use map.

var arrQuestByDate = new Array();
action.payload.data.forEach(function(item){
  if(typeof(arrQuestByDate[item.date])==='undefined'){
    arrQuestByDate[item.date]= new Array();
  }
  arrQuestByDate[item.date].push(item);
  console.log(arrQuestByDate[item.date].length) //this output good value
})
console.log(arrQuestByDate.length) //this output 0

I dont know why my array length is 0

Body:
You can use groupBy function from lodash.
If you don't want to use external library, this code shoudl work

var quotestByDate = action.payload.data
    .reduce( function(acc, quote) {
        if (!acc[quote.date]) {
            acc[quote.date] = [];
        }
        acc[quote.date].push(quote);
        return acc;
    }, {});

console.log(Object.keys(quotestByDate).length);


问:
How to close bs modal programmatically?
I'm customizing OpenCart 3.

By clicking a button in front-page footer, a modal panel opens which includes an iframe, like this:

```<code><footer>
    <div class="container">
        <div class="content">
            <i class="fa fa-plus-circle" aria-hidden="true" data-toggle="modal" data-target="#myModal"></i>
            <div class="modal fade bd-example-modal-lg" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-body">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><i class="fa fa-times-circle" aria-hidden="true"></i></button>
                            <iframe width="100%" height="{{ img_h }}" src="{{ addnewpro }}"></iframe>
                        </div>
                    </div>
                </div>
            </div>
        </div>
</code>```

iframe contains a php page for entering a new product which locates in admin panel.

So far everything is OK! The problem is I can't find a way to close the opened modal (#myModal) after entering the new product and saving it. I tried many different approaches including session, etc.

I Created Session after adding product in php page:

```<code>$this->session->data['newprosaved'] = 'saved';
</code>```

I checked session in footer's php page:

```<code>if (isset($this->session->data['newprosaved'])) {
     $data['saved'] = $this->session->data['newprosaved'];
     unset($this->session->data['newprosaved']);
}
</code>```

Then tried to access it in footer.twig:

```<code><script type="text/javascript"><!--
$(document).ready(function() {
    if ('{{ saved }}'  == 'saved' && $('#myModal').hasClass('in')) {
        $('#myModal').modal('hide');

        $('#myModal').remove();
    }
});
</script>
</code>```

But it doesn't work!

Is there any other method to do it?

答:
Unfortunately the answer was easy, although it wasted some few hours of my time.

I created a session after saving the item:

```<code>$this->session->data['newprosaved'] = 'saved';
</code>```

Then revoked it on php page load (inside iframe):

```<code>if (isset($this->session->data['newprosaved'])) {
    $data['newprosaved'] = $this->session->data['newprosaved'];
    unset($this->session->data['newprosaved']);
}
</code>```

I added a javascript code to iframe:

```<code>if ('{{ newprosaved }}' == 'saved') {
    window.parent.closeModal();
}
</code>```

Then javascript closeModal funtion to parent page:

```<code>window.closeModal = function(){
        $('#myModal').modal('hide');
};
</code>```

Title: How to close bs modal programmatically?

Body:
I'm customizing OpenCart 3.

By clicking a button in front-page footer, a modal panel opens which includes an iframe, like this:

                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"></button>

iframe contains a php page for entering a new product which locates in admin panel.

So far everything is OK! The problem is I can't find a way to close the opened modal (#myModal) after entering the new product and saving it. I tried many different approaches including session, etc.

I Created Session after adding product in php page:

$this->session->data['newprosaved'] = 'saved';

I checked session in footer's php page:

if (isset($this->session->data['newprosaved'])) {
     $data['saved'] = $this->session->data['newprosaved'];
     unset($this->session->data['newprosaved']);
}

Then tried to access it in footer.twig:

But it doesn't work!

Is there any other method to do it?

Body:
Unfortunately the answer was easy, although it wasted some few hours of my time.

I created a session after saving the item:

$this->session->data['newprosaved'] = 'saved';

Then revoked it on php page load (inside iframe):

if (isset($this->session->data['newprosaved'])) {
    $data['newprosaved'] = $this->session->data['newprosaved'];
    unset($this->session->data['newprosaved']);
}

I added a javascript code to iframe:

if ('{{ newprosaved }}' == 'saved') {
    window.parent.closeModal();
}

Then javascript closeModal funtion to parent page:

window.closeModal = function(){
        $('#myModal').modal('hide');
};


问:
JQuery JSTree - add a ToolTip
Is there a way to add a Tooltip to a JSTree node?  I would like to display extra information when the user hovers over an element.

I'm pretty dense when it comes to JQuery so there may be an obvious answer to this.

Edit:
Thanks to zzzz below, I am able to get a simple hover box to pop up.  I still cannot apply a fancy JQuery Tooltip to it despite putting the tree's div within a fieldset as the instructions within the Tooltip page would suggest.

答:
Use the "a_attr" or "li_attr" to add a title, depending on which element you want the title to be on, as documented here:
https://www.jstree.com/docs/json/

If using the "create_node" function, then do it like this:

```<code>$("#my_tree").jstree("create_node",
    "my_node",
    "inside", {
        "attr": {
            "id": "my_node"
        },
        "li_attr": { //or a_attr if you prefer
            "title": "my tooltip text",
            "class": "show_tooltip"
        },
        "text": "my node text"
    });
</code>```

The above will show a tooltip in the browser. If you want to use a custom tooltip (e.g. Bootstrap), then you can simply call $(".show_tooltip").tooltip();

Title: JQuery JSTree - add a ToolTip

Body:
Use the "a_attr" or "li_attr" to add a title, depending on which element you want the title to be on, as documented here:
https://www.jstree.com/docs/json/

If using the "create_node" function, then do it like this:

$("#my_tree").jstree("create_node",
    "my_node",
    "inside", {
        "attr": {
            "id": "my_node"
        },
        "li_attr": { //or a_attr if you prefer
            "title": "my tooltip text",
            "class": "show_tooltip"
        },
        "text": "my node text"
    });

The above will show a tooltip in the browser. If you want to use a custom tooltip (e.g. Bootstrap), then you can simply call $(".show_tooltip").tooltip();


问:
Dynamical / expanding entries for Datagrid
I'm trying to create a datagrid which has a entries which have properties coming from a json. The problem is that a lot of the properties should be dynamically generated based on the information that is in the json.

The first thing I tried was to make a very long list of all possible properties with their own getters & seters. But it's a very long list and it felt like there should be an automated solution for this problem. This is included at the end of Datagrid Entry View Model. So I am able to bind to Number when:

```<code>Number = obj.NUMBER;
</code>```

After that I researched into dynamic types and expandoObjects. I learned that apperently it's not possible to bind WPF to an expandoObject's expanded properties. So I cannot bind to expando.Number

```<code>expando.Number = obj.NUMBER
</code>```

I also tried to follow this example in which helper classes are created to help with the binding, but I can't seem to get it to work. When I run my solution I get an error saying that the property "Numberz" doesn't exist. So I cannot bind to Numberz:

```<code>AddProperty("Numberz", typeof(string));
SetPropertyValue("Numberz", obj.NUMBER);
</code>```

At moment I'm out of ideas, so if anybody here could help, I would be very grateful. Maybe a few last notes. I'm not a very experienced programmer and I'm trying to work through an MVVM-pattern.

Datagrid entry view model

public class DatagridEntryViewModel : ICustomTypeProvider, INotifyPropertyChanged
    {
        #region Fields

```<code>    /// <summary>
    /// Custom Type provider implementation - delegated through static methods.
    /// </summary>
    private readonly CustomTypeHelper<DatagridEntryViewModel> _helper = new CustomTypeHelper<DatagridEntryViewModel>();

    #endregion

    #region Constructor

    public DatagridEntryViewModel(ExitCoil model)
    {
        _helper.PropertyChanged += (s, e) => PropertyChanged(this, e);

        dynamic Json = JObject.Parse(model.JsonCoilData);
        //CreationDatePost = Json.CREATION_DATE_S_POST;
        ////Number = Json.NUMBER;
        //CreationDatePost = Json.CREATION_DATE_S_POST;
        ////LeverageOrder = Json.LEVERAGE_ORDER;
        //Client = Json.CLIENT;
        //Skinned = Json.SKINNED;

        dynamic expando = new ExpandoObject();
        dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(Json.ToString());
        //AddProperty("Numberz", typeof(string));
        //SetPropertyValue("Numberz", obj.NUMBER);
        //expando.AddItem("Number");
        //expando[0] = obj.NUMBER;
        //Number = expando.Number;

        Model = model;

        //var settings = new JsonSerializerSettings();
        //settings.Converters.Add(new Models.DynamicJsonConverter());
        //var serializer = JsonSerializer.Create(settings);
        //JsonReader reader = new JsonTextReader(new StringReader(JsonString));

        //var Data = serializer.Deserialize<DynamicObject>(reader);
    }

    #endregion

    #region Model & proxy

    private ExitCoil _model;
    public ExitCoil Model
    {
        set { _model = value; }
    }

    #endregion

    #region Public Methods

    // Methods to support dynamic properties.
    public static void AddProperty(string name)
    {
        CustomTypeHelper<DatagridEntryViewModel>.AddProperty(name);
    }

    public static void AddProperty(string name, Type propertyType)
    {
        CustomTypeHelper<DatagridEntryViewModel>.AddProperty(name, propertyType);
    }

    public static void AddProperty(string name, Type propertyType, List<Attribute> attributes)
    {
        CustomTypeHelper<DatagridEntryViewModel>.AddProperty(name, propertyType, attributes);
    }

    public void SetPropertyValue(string propertyName, object value)
    {
        _helper.SetPropertyValue(propertyName, value);
    }

    public object GetPropertyValue(string propertyName)
    {
        return _helper.GetPropertyValue(propertyName);
    }

    public PropertyInfo[] GetProperties()
    {
        return _helper.GetProperties();
    }

    Type ICustomTypeProvider.GetCustomType()
    {
        return _helper.GetCustomType();
    }

    public event PropertyChangedEventHandler PropertyChanged = delegate { };
    private void RaisePropertyChanged([CallerMemberName] string propertyName = "")
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    #endregion

    #region Properties

    //public string Number { get; private set; }

    //public string CreationDatePost { get; private set; }

    //public string LeverageOrder { get; private set; }

    public string Client { get; private set; }

    //public int OrderZnTop { get; private set; }

    //public int OrderZnBottom { get; private set; }

    //public string OrderAspect { get; private set; }

    //public string OderSideTrimming { get; private set; }

    //public string OrderPassivation { get; private set; }

    //public string OrderOilType { get; private set; }

    //public string OrderOilQuantity { get; private set; }

    #endregion

}
</code>```

Datagrid view model

```<code>public class DatagridViewModel : MainViewModelBase
    {
        #region Singleton

        public static DatagridViewModel Instance = new DatagridViewModel();

        #endregion

        #region Fields

        private ObservableCollection<DatagridEntryViewModel> _coilEntries = new ObservableCollection<DatagridEntryViewModel>();
        private readonly IViewManager _viewManager;
        private readonly IDockManager _dockManager;

        #endregion

        #region Properties

        public ObservableCollection<DatagridEntryViewModel> CoilEntries
        {
            get { return _coilEntries; }
            set
            {
                _coilEntries = value;
                RaisePropertyChanged(() => CoilEntries);
            }
        }

        public ProductionExitCoilReport Report { get; set; }

        #endregion

        #region Constructor

        public DatagridViewModel()
        {
            _viewManager = Globals.Container.Resolve<IViewManager>();
            _dockManager = Globals.Container.Resolve<IDockManager>();

            getReport();

            foreach (var Coil in Report.Coils)
            {
                CoilEntries.Add(new DatagridEntryViewModel(Coil));
            }
        }

        #endregion

        #region Methods

        public void getReport()
        {
            var proxy = new Proxy<IReportService>();
            proxy.Open();
            var LijnId = new LijnIdentificatie { Department = "HDG", Firm = "LIE", LineNumber = "05" };
            var Periode = new Period { FromDate = new DateTime(2017 - 11 - 10), FromShift = 1, ToDate = new DateTime(2017 - 11 - 10), ToShift = 1 };
            var request = new ProductionReportRequest() { LijnIdentificatie = LijnId, Period = Periode };
            Report = proxy.Service.GetProductionExitCoilReport(request);

        }

        #endregion
    }
</code>```

Datagrid XAML

```<code><DataGrid x:Class="Promo.Presentation.Views.CoilGrid"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:mc="http://schemas.openxmlformats.org/marukp-compatibility/2006"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:local="clr-namespace:Promo.Presentation.Views"
            xmlns:components="clr-namespace:Promo.Presentation.Components"
            xmlns:Data="clr-namespace:Promo.Presentation.ViewModels"
            AutoGenerateColumns="False"
            GridLinesVisibility="none"
            Background="White"
            Height="Auto"
            Width="Auto"
            MinWidth="500"
            MinHeight="500"
            DataContext="{x:Static Data:DatagridViewModel.Instance}"
            ItemsSource="{Binding CoilEntries}"
            IsReadOnly="True"
            HeadersVisibility="Column"
            Padding="10"
          >

    <DataGrid.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="../Styles/Colors.xaml"/>
                <ResourceDictionary Source="../Styles/Datagrid.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </DataGrid.Resources>

    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Numberz}" Header="Rolnummer" MaxWidth="125"/>
        <DataGridTextColumn Binding="{Binding CreationDatePost}" Header="Post" MaxWidth="200"/>
        <DataGridTextColumn Binding="{Binding LeverageOrder}" Header="Leverage order" MaxWidth="200"/>
        <DataGridTextColumn Binding="{Binding Client}" Header="Client" MaxWidth="400"/>
        <DataGridTextColumn Binding="{Binding OrderZnTop}" Header="Order zinc top" MaxWidth="200"/>
        <DataGridTextColumn Binding="{Binding OrderZnBottom}" Header="Order zinc bottom" MaxWidth="200"/>
        <DataGridTextColumn Binding="{Binding OrderAspect}" Header="Order aspect" MaxWidth="125"/>
        <DataGridCheckBoxColumn Binding="{Binding OrderSideTrimming, Converter={local:StringToBoolConverter}}" Header="Order Side Trimming" MaxWidth="200"/>
        <DataGridTextColumn Binding="{Binding OrderPassivation}" Header="Order Passivation" MaxWidth="200"/>

        <DataGridCheckBoxColumn Binding="{Binding Skinned, Converter={local:StringToBoolConverter}}" Header="Skinned" MaxWidth="200"/>
    </DataGrid.Columns>

</DataGrid>
</code>```

Part of the Json

{"NUMBER":"G571015110          ","CREATION_DATE_S_POST":"2017-05-11T00:00:00""LEVERAGE_ORDER":"FD72BIGA5W/8","CLIENT":"ARCELORMITTAL BELGIUM SA          "}

答:
If you have a json with all of the properties then Visual Studio can generate class for you! no need to create them your self. I worked on a similar scenario in the past, this has been done before.

To paste a class generated from json click in your .cs file where you want to generate the code, then click on Edit in the Visual Studio menu, next select Paste Special and then select Paste JSON As Classes.

This should make it a bit easier for you.

Body:
I'm trying to create a datagrid which has a entries which have properties coming from a json. The problem is that a lot of the properties should be dynamically generated based on the information that is in the json.

The first thing I tried was to make a very long list of all possible properties with their own getters & seters. But it's a very long list and it felt like there should be an automated solution for this problem. This is included at the end of Datagrid Entry View Model. So I am able to bind to Number when:

Number = obj.NUMBER;

After that I researched into dynamic types and expandoObjects. I learned that apperently it's not possible to bind WPF to an expandoObject's expanded properties. So I cannot bind to expando.Number

expando.Number = obj.NUMBER

I also tried to follow this example in which helper classes are created to help with the binding, but I can't seem to get it to work. When I run my solution I get an error saying that the property "Numberz" doesn't exist. So I cannot bind to Numberz:

AddProperty("Numberz", typeof(string));
SetPropertyValue("Numberz", obj.NUMBER);

At moment I'm out of ideas, so if anybody here could help, I would be very grateful. Maybe a few last notes. I'm not a very experienced programmer and I'm trying to work through an MVVM-pattern.

Datagrid entry view model

public class DatagridEntryViewModel : ICustomTypeProvider, INotifyPropertyChanged
    {
        #region Fields

    ///
    /// Custom Type provider implementation - delegated through static methods.
    ///
    private readonly CustomTypeHelper<DatagridEntryViewModel> _helper = new CustomTypeHelper<DatagridEntryViewModel>();

    #endregion

    #region Constructor

    public DatagridEntryViewModel(ExitCoil model)
    {
        _helper.PropertyChanged += (s, e) => PropertyChanged(this, e);

        dynamic Json = JObject.Parse(model.JsonCoilData);
        //CreationDatePost = Json.CREATION_DATE_S_POST;
        ////Number = Json.NUMBER;
        //CreationDatePost = Json.CREATION_DATE_S_POST;
        ////LeverageOrder = Json.LEVERAGE_ORDER;
        //Client = Json.CLIENT;
        //Skinned = Json.SKINNED;

        dynamic expando = new ExpandoObject();
        dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(Json.ToString());
        //AddProperty("Numberz", typeof(string));
        //SetPropertyValue("Numberz", obj.NUMBER);
        //expando.AddItem("Number");
        //expando[0] = obj.NUMBER;
        //Number = expando.Number;

        Model = model;

        //var settings = new JsonSerializerSettings();
        //settings.Converters.Add(new Models.DynamicJsonConverter());
        //var serializer = JsonSerializer.Create(settings);
        //JsonReader reader = new JsonTextReader(new StringReader(JsonString));

        //var Data = serializer.Deserialize<DynamicObject>(reader);
    }

    #endregion

    #region Model & proxy

    private ExitCoil _model;
    public ExitCoil Model
    {
        set { _model = value; }
    }

    #endregion

    #region Public Methods

    // Methods to support dynamic properties.
    public static void AddProperty(string name)
    {
        CustomTypeHelper<DatagridEntryViewModel>.AddProperty(name);
    }

    public static void AddProperty(string name, Type propertyType)
    {
        CustomTypeHelper<DatagridEntryViewModel>.AddProperty(name, propertyType);
    }

    public static void AddProperty(string name, Type propertyType, List<Attribute> attributes)
    {
        CustomTypeHelper<DatagridEntryViewModel>.AddProperty(name, propertyType, attributes);
    }

    public void SetPropertyValue(string propertyName, object value)
    {
        _helper.SetPropertyValue(propertyName, value);
    }

    public object GetPropertyValue(string propertyName)
    {
        return _helper.GetPropertyValue(propertyName);
    }

    public PropertyInfo[] GetProperties()
    {
        return _helper.GetProperties();
    }

    Type ICustomTypeProvider.GetCustomType()
    {
        return _helper.GetCustomType();
    }

    public event PropertyChangedEventHandler PropertyChanged = delegate { };
    private void RaisePropertyChanged([CallerMemberName] string propertyName = "")
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    #endregion

    #region Properties

    //public string Number { get; private set; }

    //public string CreationDatePost { get; private set; }

    //public string LeverageOrder { get; private set; }

    public string Client { get; private set; }

    //public int OrderZnTop { get; private set; }

    //public int OrderZnBottom { get; private set; }

    //public string OrderAspect { get; private set; }

    //public string OderSideTrimming { get; private set; }

    //public string OrderPassivation { get; private set; }

    //public string OrderOilType { get; private set; }

    //public string OrderOilQuantity { get; private set; }

    #endregion

}

Datagrid view model

public class DatagridViewModel : MainViewModelBase
    {
        #region Singleton

        public static DatagridViewModel Instance = new DatagridViewModel();

        #endregion

        #region Fields

        private ObservableCollection<DatagridEntryViewModel> _coilEntries = new ObservableCollection<DatagridEntryViewModel>();
        private readonly IViewManager _viewManager;
        private readonly IDockManager _dockManager;

        #endregion

        #region Properties

        public ObservableCollection<DatagridEntryViewModel> CoilEntries
        {
            get { return _coilEntries; }
            set
            {
                _coilEntries = value;
                RaisePropertyChanged(() => CoilEntries);
            }
        }

        public ProductionExitCoilReport Report { get; set; }

        #endregion

        #region Constructor

        public DatagridViewModel()
        {
            _viewManager = Globals.Container.Resolve<IViewManager>();
            _dockManager = Globals.Container.Resolve<IDockManager>();

            getReport();

            foreach (var Coil in Report.Coils)
            {
                CoilEntries.Add(new DatagridEntryViewModel(Coil));
            }
        }

        #endregion

        #region Methods

        public void getReport()
        {
            var proxy = new Proxy<IReportService>();
            proxy.Open();
            var LijnId = new LijnIdentificatie { Department = "HDG", Firm = "LIE", LineNumber = "05" };
            var Periode = new Period { FromDate = new DateTime(2017 - 11 - 10), FromShift = 1, ToDate = new DateTime(2017 - 11 - 10), ToShift = 1 };
            var request = new ProductionReportRequest() { LijnIdentificatie = LijnId, Period = Periode };
            Report = proxy.Service.GetProductionExitCoilReport(request);

        }

        #endregion
    }

Datagrid XAML

<DataGrid x:Class="Promo.Presentation.Views.CoilGrid"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:mc="http://schemas.openxmlformats.org/marukp-compatibility/2006"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:local="clr-namespace:Promo.Presentation.Views"
            xmlns:components="clr-namespace:Promo.Presentation.Components"
            xmlns:Data="clr-namespace:Promo.Presentation.ViewModels"
            AutoGenerateColumns="False"
            GridLinesVisibility="none"
            Background="White"
            Height="Auto"
            Width="Auto"
            MinWidth="500"
            MinHeight="500"
            DataContext="{x:Static Data:DatagridViewModel.Instance}"
            ItemsSource="{Binding CoilEntries}"
            IsReadOnly="True"
            HeadersVisibility="Column"
            Padding="10"
          >

    <DataGrid.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="../Styles/Colors.xaml"/>
                <ResourceDictionary Source="../Styles/Datagrid.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </DataGrid.Resources>

    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Numberz}" Header="Rolnummer" MaxWidth="125"/>
        <DataGridTextColumn Binding="{Binding CreationDatePost}" Header="Post" MaxWidth="200"/>
        <DataGridTextColumn Binding="{Binding LeverageOrder}" Header="Leverage order" MaxWidth="200"/>
        <DataGridTextColumn Binding="{Binding Client}" Header="Client" MaxWidth="400"/>
        <DataGridTextColumn Binding="{Binding OrderZnTop}" Header="Order zinc top" MaxWidth="200"/>
        <DataGridTextColumn Binding="{Binding OrderZnBottom}" Header="Order zinc bottom" MaxWidth="200"/>
        <DataGridTextColumn Binding="{Binding OrderAspect}" Header="Order aspect" MaxWidth="125"/>
        <DataGridCheckBoxColumn Binding="{Binding OrderSideTrimming, Converter={local:StringToBoolConverter}}" Header="Order Side Trimming" MaxWidth="200"/>
        <DataGridTextColumn Binding="{Binding OrderPassivation}" Header="Order Passivation" MaxWidth="200"/>

        <DataGridCheckBoxColumn Binding="{Binding Skinned, Converter={local:StringToBoolConverter}}" Header="Skinned" MaxWidth="200"/>
    </DataGrid.Columns>

</DataGrid>

Part of the Json

{"NUMBER":"G571015110          ","CREATION_DATE_S_POST":"2017-05-11T00:00:00""LEVERAGE_ORDER":"FD72BIGA5W/8","CLIENT":"ARCELORMITTAL BELGIUM SA          "}


问:
Optimization - Limits and simple constraint
I have a rather simple optimization question and while I'm fairly decent with R, optimization is something I haven't done a lot.

```<code>my.function <- function(parameters){
  x <- parameters[1]
  y <- parameters[2]
  z <- parameters[3]
  ((10*x^2) - ((y/2) * (z/4)))^2
}

result <- optim(c(7,10,18),fn = my.function, method = 'L-BFGS-B',
      lower = c(2,7,7),
      upper = c(15,20,20))

result$par
#[1]  2.205169 19.546621 19.902243
</code>```

This is a made up version of the problem I'm working on, so please forgive it if its purpose makes no sense.  I have limits in place using the 'L-BFGS-B' method but I need to add a constraint and I'm unsure how to do it.  My rules that I'm trying to implement are as follows:

x must be between 2 and 15

y must be between 7 and 20

z must be between 7 and 20

z <= y

It's the last one I don't know how to implement.  Any help would be appreciated.  Thank you.

答:
Add a large number to the objective function if the constraint is violated, i.e. change the last line of my.function to:

```<code>((10*x^2) - ((y/2) * (z/4)))^2 + ifelse(y > z, 10^5, 0)
</code>```

The result in this case is the following which does satisfy the constraint. Also, since the objective is non-negative its value cannot be less than 0 so we have achieved the minimum to numeric tolerance.

```<code>result$par
## [1]  2.223537 19.776462 20.000000

result$value
## [1] 1.256682e-11
</code>```

Body:
I have a rather simple optimization question and while I'm fairly decent with R, optimization is something I haven't done a lot.

my.function <- function(parameters){
  x <- parameters[1]
  y <- parameters[2]
  z <- parameters[3]
  ((10*x^2) - ((y/2) * (z/4)))^2
}

result <- optim(c(7,10,18),fn = my.function, method = 'L-BFGS-B',
      lower = c(2,7,7),
      upper = c(15,20,20))

result$par
#[1]  2.205169 19.546621 19.902243

This is a made up version of the problem I'm working on, so please forgive it if its purpose makes no sense.  I have limits in place using the 'L-BFGS-B' method but I need to add a constraint and I'm unsure how to do it.  My rules that I'm trying to implement are as follows:

x must be between 2 and 15

y must be between 7 and 20

z must be between 7 and 20

z <= y

It's the last one I don't know how to implement.  Any help would be appreciated.  Thank you.

Body:
Add a large number to the objective function if the constraint is violated, i.e. change the last line of my.function to:

((10*x^2) - ((y/2) * (z/4)))^2 + ifelse(y > z, 10^5, 0)

The result in this case is the following which does satisfy the constraint. Also, since the objective is non-negative its value cannot be less than 0 so we have achieved the minimum to numeric tolerance.

result$par
## [1]  2.223537 19.776462 20.000000

result$value
## [1] 1.256682e-11


问:
Selenium implicit and explicit wait, timeout exception element not found
I am new to selenium (but experienced java developer).

I am using something like below:

```<code>WebElement searchBasket = pDriver.findElement(By.xpath("//a[contains(.,'Search&Baskets')]"));
WebElement searchproduct = pDriver.findElement(By.xpath("//a[contains(.,'Search a product')]"));

//if search an agreement is not show up, then click on other menu, then click it back
pWait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[contains(.,'Search&Baskets')]")));
pDriver.findElement(By.xpath("//a[contains(.,'Search&Baskets')]")).click();

// click on search an agreement
try {
    pWait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[contains(.,'Search&Baskets')]")));
    action = new Actions(pDriver);
    action.moveToElement(searchBasket).build().perform();

    pWait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[contains(.,'Search a product')]")));
    searchproduct.click();
} catch (TimeoutException e) {
}
</code>```

where pWait is:

```<code>WebDriverWait wait = new WebDriverWait(driver, 15);
</code>```

however when I run the test case I get below error:

```<code>Unable to locate element: {"method":"xpath","selector":"//a[contains(.,'Search&Baskets')]"}
Command duration or timeout: 4 milliseconds
</code>```

I thought it should have wait atleast 15 seconds before throwing this exception. From the log above it looks like it threw exception only in 4ms.
and i could see on console that as soon as it hit that line, it threw exception.

I have implicit waiting set as 0 and using explicit wait.

Am i missing anything here.

Also, in explicit and implicit wait, is it upto that much time OR exact that much time,
example if I set implicit wait as 10 sec, then does it mean wait for exact 10 sec OR wait upto 10 sec (if element found then proceed, even if element founf on 6th second)

is above same for explicit wait as well?

Please help

答:
Let us analyze what is happening in our code.

We have defined two WebElements searchBasket and searchproduct as follows :

```<code>WebElement searchBasket = pDriver.findElement(By.xpath("//a[contains(.,'Search&Baskets')]"));
WebElement searchproduct = pDriver.findElement(By.xpath("//a[contains(.,'Search a product')]"));
</code>```

We havn't tried to use those WebElements in our code at immediate basis, so had No Impact.

Next, we tried WebDriverWait for an WebElement as follows :

```<code>pWait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[contains(.,'Search&Baskets')]")));
</code>```

Again we didn't capture the return type of the result, so had No Impact.

Now, within the try{} block we have again tried WebDriverWait:

```<code>pWait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[contains(.,'Search&Baskets')]")));
</code>```

But again we havn't captured/acted on the return type of the result. That's why moving ahead when we did :

```<code>action.moveToElement(searchBasket).build().perform();
</code>```

searchBasket referred to the WebElement which we have stored earlier as :

```<code>WebElement searchBasket = pDriver.findElement(By.xpath("//a[contains(.,'Search&Baskets')]"));
</code>```

As this first search result (which was without WebDriverWait) may not have returned any WebElement at all and have returned Null.

Finally, the most important factor for the error Unable to locate element: {"method":"xpath","selector":"//a[contains(.,'Search&Baskets')]"} is, the
WebDriverWait instance was wait. Instead of using wait we have always tried to use pWait

So for all these reasons, WebDriverWait was never implemented properly in our code.

Mixing up ImplicitWait & ExplicitWait

The Selenium Documentation clearly mentions the following :

WARNING: Do not mix implicit and explicit waits. Doing so can cause unpredictable wait times. For example setting an implicit wait of 10 seconds and an explicit wait of 15 seconds, could cause a timeout to occur after 20 seconds.

Body:
I am new to selenium (but experienced java developer).

I am using something like below:

WebElement searchBasket = pDriver.findElement(By.xpath("//a[contains(.,'Search&Baskets')]"));
WebElement searchproduct = pDriver.findElement(By.xpath("//a[contains(.,'Search a product')]"));

//if search an agreement is not show up, then click on other menu, then click it back
pWait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[contains(.,'Search&Baskets')]")));
pDriver.findElement(By.xpath("//a[contains(.,'Search&Baskets')]")).click();

// click on search an agreement
try {
    pWait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[contains(.,'Search&Baskets')]")));
    action = new Actions(pDriver);
    action.moveToElement(searchBasket).build().perform();

    pWait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[contains(.,'Search a product')]")));
    searchproduct.click();
} catch (TimeoutException e) {
}

where pWait is:

WebDriverWait wait = new WebDriverWait(driver, 15);

however when I run the test case I get below error:

Unable to locate element: {"method":"xpath","selector":"//a[contains(.,'Search&Baskets')]"}
Command duration or timeout: 4 milliseconds

I thought it should have wait atleast 15 seconds before throwing this exception. From the log above it looks like it threw exception only in 4ms.
and i could see on console that as soon as it hit that line, it threw exception.

I have implicit waiting set as 0 and using explicit wait.

Am i missing anything here.

Also, in explicit and implicit wait, is it upto that much time OR exact that much time,
example if I set implicit wait as 10 sec, then does it mean wait for exact 10 sec OR wait upto 10 sec (if element found then proceed, even if element founf on 6th second)

is above same for explicit wait as well?

Please help

Body:
Let us analyze what is happening in our code.

We have defined two WebElements searchBasket and searchproduct as follows :

WebElement searchBasket = pDriver.findElement(By.xpath("//a[contains(.,'Search&Baskets')]"));
WebElement searchproduct = pDriver.findElement(By.xpath("//a[contains(.,'Search a product')]"));

We havn't tried to use those WebElements in our code at immediate basis, so had No Impact.

Next, we tried WebDriverWait for an WebElement as follows :

pWait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[contains(.,'Search&Baskets')]")));

Again we didn't capture the return type of the result, so had No Impact.

Now, within the try{} block we have again tried WebDriverWait:

pWait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[contains(.,'Search&Baskets')]")));

But again we havn't captured/acted on the return type of the result. That's why moving ahead when we did :

action.moveToElement(searchBasket).build().perform();

searchBasket referred to the WebElement which we have stored earlier as :

WebElement searchBasket = pDriver.findElement(By.xpath("//a[contains(.,'Search&Baskets')]"));

As this first search result (which was without WebDriverWait) may not have returned any WebElement at all and have returned Null.

Finally, the most important factor for the error Unable to locate element: {"method":"xpath","selector":"//a[contains(.,'Search&Baskets')]"} is, the
WebDriverWait instance was wait. Instead of using wait we have always tried to use pWait

So for all these reasons, WebDriverWait was never implemented properly in our code.

Mixing up ImplicitWait & ExplicitWait

The Selenium Documentation clearly mentions the following :

WARNING: Do not mix implicit and explicit waits. Doing so can cause unpredictable wait times. For example setting an implicit wait of 10 seconds and an explicit wait of 15 seconds, could cause a timeout to occur after 20 seconds.


问:
error: [Errno 2] No such file or directory: '/Library/Frameworks/Tcl.framework/Versions/8.5/Tcl'

 I made a tkinter app on my mac which runs well, when I run it from the terminal. Now, I want to make an executable version of it, but I get this error message after python setup.py build:

```<code>error: [Errno 2] No such file or directory: '/Library/Frameworks/Tcl.framework/Versions/8.5/Tcl'
</code>```

setup.py:

```<code>import cx_Freeze, sys
import os
import os
os.environ['TCL_LIBRARY'] = "/System/Library/tcl/8.4"
base = None

if sys.platform == 'Win32':
base = "Win32GUI"

executables = [cx_Freeze.Executable("multiframe.py", base=base)]

cx_Freeze.setup(
    name="cu",
    options = {"build_exe": {"packages":["tkinter"]}},
    version= "0.01",
    description = "dasdasd",
    executables = executables
    )
</code>```

I know that something is wrong with the tcl import but I have tcl in Python3.6 folder on windows but I don't in mac

答:
In your options statement, you tell the system to import the "tkinter" package.  "tkinter" is Python 3. "Tkinter" is for Python 2. If you are running Python 2 on your Mac, you need to use "Tkinter" instead of "tkinter" for a package. And, of course, you'll need to make sure your "cu" app runs on Python 2.

Also, the line

```<code>os.environ['TCL_LIBRARY'] = "/System/Library/tcl/8.4"
</code>```

points to an old version of Tcl.  Probably doesn't matter. But the later Python 2.7 and Python 3 both come with 8.5.  You should probably upgrade your Mac to Python 3 to be the same as your Windows machine, so that your code will run in both places. Otherwise you may need little tweaks in your code to get the same code to run on both.

Body:
 I made a tkinter app on my mac which runs well, when I run it from the terminal. Now, I want to make an executable version of it, but I get this error message after python setup.py build:

error: [Errno 2] No such file or directory: '/Library/Frameworks/Tcl.framework/Versions/8.5/Tcl'

setup.py:

import cx_Freeze, sys
import os
import os
os.environ['TCL_LIBRARY'] = "/System/Library/tcl/8.4"
base = None

if sys.platform == 'Win32':
base = "Win32GUI"

executables = [cx_Freeze.Executable("multiframe.py", base=base)]

cx_Freeze.setup(
    name="cu",
    options = {"build_exe": {"packages":["tkinter"]}},
    version= "0.01",
    description = "dasdasd",
    executables = executables
    )

I know that something is wrong with the tcl import but I have tcl in Python3.6 folder on windows but I don't in mac

Body:
In your options statement, you tell the system to import the "tkinter" package.  "tkinter" is Python 3. "Tkinter" is for Python 2. If you are running Python 2 on your Mac, you need to use "Tkinter" instead of "tkinter" for a package. And, of course, you'll need to make sure your "cu" app runs on Python 2.

Also, the line

os.environ['TCL_LIBRARY'] = "/System/Library/tcl/8.4"

points to an old version of Tcl.  Probably doesn't matter. But the later Python 2.7 and Python 3 both come with 8.5.  You should probably upgrade your Mac to Python 3 to be the same as your Windows machine, so that your code will run in both places. Otherwise you may need little tweaks in your code to get the same code to run on both.


问:
Any Windows API for detecting MTP devices?
I'm looking for detection of MTP devices through Windows API, not just the enumeration of already connected devices.</p>

答:
For a start, consider looking at:

Windows Portable Devices

Windows Portable Devices Development Kits and Downloads

Portable Devices COM API Sample


问:
Creating overlapping elements
I'm trying to display a span overlapping a canvas element along the canvas' left border.

```<code><!doctype html />
<html>
  <head>
    <title>Z-Index</title>
  </head>

  <body>
    <div id="timeline_wrapper"></div>
    <script type="text/javascript">

        var canvas = document.createElement('canvas');
        canvas.setAttribute('width', 500);
        canvas.setAttribute('height', 500);
        canvas.setAttribute('style', 'border: 1px solid; position: absolute; top: 8px; left: 8px; z-index: 0;');
        document.getElementById("timeline_wrapper").appendChild(canvas);

        // draw back button
        var back = document.createElement('div');
        back.setAttribute('width', 50);
        back.setAttribute('height', 500);
        back.setAttribute('style', 'background-color: #336699; position: absolute; left: 8px; top: 8px; z-index: 1');
        document.getElementById("timeline_wrapper").appendChild(back);

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

No matter what I've tried, the back element doesn't show up at all.
Apart from the back element being positioned at 50, 50 from top, left, does someone know what I'm doing wrong?

Cheers,
Joshua

答:
Is this what you are trying to do?

```<code><!doctype html />
<html>
  <head>
    <title>Z-Index</title>
  </head>

  <body>
    <div id="timeline_wrapper"></div>
    <script type="text/javascript">

        var canvas = document.createElement('canvas');
        canvas.setAttribute('style', 'border: 1px solid; position: fixed; top: 8px; left: 8px; z-index: 0; width: 500px; height: 500px;');
        document.getElementById("timeline_wrapper").appendChild(canvas);

        // draw back button
        var back = document.createElement('div');
        back.setAttribute('style', 'background-color: 336699; position: absolute; left: 8px; top: 8px; z-index: 1; width: 50px; height: 500px;');
        document.getElementById("timeline_wrapper").appendChild(back);

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

(I moved the width and height into the css, it isn't a dom attribute)

Title: Creating overlapping elements

Body:
I'm trying to display a span overlapping a canvas element along the canvas' left border.

<!doctype html />

    <title>Z-Index</title>

No matter what I've tried, the back element doesn't show up at all.
Apart from the back element being positioned at 50, 50 from top, left, does someone know what I'm doing wrong?

Cheers,
Joshua

Body:
Is this what you are trying to do?

<!doctype html />
<html>
  <head>
    <title>Z-Index</title>
  </head>

  <body>
    <div id="timeline_wrapper"></div>
    <script type="text/javascript">

        var canvas = document.createElement('canvas');
        canvas.setAttribute('style', 'border: 1px solid; position: fixed; top: 8px; left: 8px; z-index: 0; width: 500px; height: 500px;');
        document.getElementById("timeline_wrapper").appendChild(canvas);

        // draw back button
        var back = document.createElement('div');
        back.setAttribute('style', 'background-color: 336699; position: absolute; left: 8px; top: 8px; z-index: 1; width: 50px; height: 500px;');
        document.getElementById("timeline_wrapper").appendChild(back);

    </script>
  </body>
</html>

(I moved the width and height into the css, it isn't a dom attribute)


问:
How can you trace execution of an embedded system emulted in QEMU?
I've built  OpenWrt for x86 and I'm using QEMU to run it virtually.I'm trying to debug this system in real time.  I need to see things like network traffic flowing etc.

I can attach gdb remotely and execute (mostly) step by step with break points. I really want trace points though. I don't want to pause execution and loose network flow. When I tried setting trace points using tstart, I see the message "Target does not support this command". I did a bit of reading of the gdb documentation and from what I can tell the gdb stub that runs to intercept normal execution in QEMU does not support trace points.

From here I started looking at other tools and ran across PANDA (https://github.com/panda-re/panda). As I understand PANDA will capture a complete system trace in a log and allow for replay. I think this tool is supposed to do what I need, but I cannot seem to replay the results. I see the logs, I just can't replay them.

Now, I'm a bit stuck on what other tools/options I might have to actually trace a running embedded system. Are there any good tools you can recommend? Or perhaps another method I've missed?

答:
In OpenWrt it is possible to build with ftrace. Ftrace has much of the functionality I required but not all.

To build with ftrace, the option for ftrace must be selected in the build menu. Additionally there are a variety of tracer options that must also be enabled.

The trace-cmd (ftrace) is located in menuconfig/Development

Tracing support is under menuconfig/Global build settings/Compile the kernel with tracing support and includes: Trace system calls, Trace process context switches and events, and Function tracer (Function graph tracer, Enable/disable function tracing dynamically, and Function profiler)

I'm also planning to build a custom GDB stub to do this a little bit better as I also want to see the data passed to the functions not just the function calls.


问:
Firestore Offline Promise Handling?
I have been scouring the firestore docs and the angularfire2 docs looking for any information regarding how firebase/angularfire handles it's write promises when my progressive web app is offline.

The problem is that all of my promises returned from the batch writes are not being resolved (or rejected), so should I be assuming that all promises made offline will be resolved? If so, am I correct in saying I should rather be handling redirects and success messages before the promise is resolved?

Besides my unresolved firebase promises, the offline mode seems to work well. It correctly changes data in various places throughout many collections and documents, and the changes are displayed correctly in the web app.

Once returning to online mode, the relevant changes are made to the database and my pending promises all seem to get resolved at once.

Is this expected behaviour? And if it is what would the correct way about handling success/error messages and redirects be (if they were previously handled in the promise then and catch)

答: Firestore promises (and completion handlers on other platforms) indeed resolve/reject when the write operation has been committed/rejected on the server. So what you see is indeed the expected behavior. </p>

Title: Firestore Offline Promise Handling?