问:
Why does Run All cause a crash in VS2012 unit testing but running one by one doesn't?
We just "upgraded" from Visual Studio 2008 to Visual Studio 2012. We updated our unit tests and now they pass when running them individually but when I try to Run All, I got the following error:

```<code>The active Test Run was aborted because the execution process exited unexpectedly. To investigate further, enable local crash dumps either
at the machine level or for process vstest.executionengine.appcontainer.x86.exe. Go to more details: [http://go.microsoft.com/fwlink/?linkid=232477][1]
</code>```

So I went to the link and followed the instructions to add the registry key to enable local crash dumps. The error message then changed to:

```<code>The active Test Run was aborted because the execution process exited unexpectedly. Check the execution process logs for more information.
If the logs are not enabled, then enable the logs and try again.
</code>```

Apparently it noticed the changes that I made in the registry to enable crash. However, when I looked in %LOCALAPPDATA%\CrashDumps, no files were being created.

If I run one test at a time (or even a few tests at a time), I can get them all to pass. The problem is only with Run All.

Has anyone else encountered similar problems? If so, how did you solve them?

Essentially the same question was asked on MSDN, but the answer was something like "click the link to the crash dump". That answer doesn't help me because I don't see any link to the crash dump and I am unable to get the crash dump to be generated.

This question on StackOverflow is also similar, and ended up resulting in a bug being logged on Microsoft Connect (which looks to be deferred for some reason), but my problem might be different because my code has nothing to do with "async tasks" (I don't think).

EDIT: The problem went away, seemingly on its own, but the problem was likely an exception that wasn't being caught in the unit test code, as some of the answers below suggest. However, I'm still confused as to why the problem only appeared with Run All, and not when running smaller groups of tests or Debug All.

答: Just had the same problem. Closing and reopening visual studio fixed it for me.</p>

Body:
We just "upgraded" from Visual Studio 2008 to Visual Studio 2012. We updated our unit tests and now they pass when running them individually but when I try to Run All, I got the following error:

The active Test Run was aborted because the execution process exited unexpectedly. To investigate further, enable local crash dumps either
at the machine level or for process vstest.executionengine.appcontainer.x86.exe. Go to more details: [http://go.microsoft.com/fwlink/?linkid=232477][1]

So I went to the link and followed the instructions to add the registry key to enable local crash dumps. The error message then changed to:

The active Test Run was aborted because the execution process exited unexpectedly. Check the execution process logs for more information.
If the logs are not enabled, then enable the logs and try again.

Apparently it noticed the changes that I made in the registry to enable crash. However, when I looked in %LOCALAPPDATA%\CrashDumps, no files were being created.

If I run one test at a time (or even a few tests at a time), I can get them all to pass. The problem is only with Run All.

Has anyone else encountered similar problems? If so, how did you solve them?

Essentially the same question was asked on MSDN, but the answer was something like "click the link to the crash dump". That answer doesn't help me because I don't see any link to the crash dump and I am unable to get the crash dump to be generated.

This question on StackOverflow is also similar, and ended up resulting in a bug being logged on Microsoft Connect (which looks to be deferred for some reason), but my problem might be different because my code has nothing to do with "async tasks" (I don't think).

EDIT: The problem went away, seemingly on its own, but the problem was likely an exception that wasn't being caught in the unit test code, as some of the answers below suggest. However, I'm still confused as to why the problem only appeared with Run All, and not when running smaller groups of tests or Debug All.


来源: stackexchange

问:
How to format a perl oneliner?
If I have a perl one liner running it from the command line: e.g

```<code>perl -MData::Dumper -MJSON=decode_json -e 'my @array = @{decode_json($data)}; foreach my $i (@array) { etc }'
</code>```

How could I format it so that it is more readable i.e. add new lines? If I do something like:

Ma

The command breaks when I add the new lines like that to format the code

答:
This is funny: You want to have a one-liner, which, for readability, should span several lines. This sounds like a contradicition.

What you can do is to drop the -e switch and make a HERE document:

```<code>perl -MData::Dumper -MJSON=decode_json <<ENDOFPERL
  # Your multi-line one-liner goes here
ENDOFPERL
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to format a perl oneliner?

Body:
If I have a perl one liner running it from the command line: e.g

perl -MData::Dumper -MJSON=decode_json -e 'my @array = @{decode_json($data)}; foreach my $i (@array) { etc }'

How could I format it so that it is more readable i.e. add new lines? If I do something like:

Ma

The command breaks when I add the new lines like that to format the code

Body:
This is funny: You want to have a one-liner, which, for readability, should span several lines. This sounds like a contradicition.

What you can do is to drop the -e switch and make a HERE document:

perl -MData::Dumper -MJSON=decode_json <<ENDOFPERL
  # Your multi-line one-liner goes here
ENDOFPERL


问:
How to write a script in ruby that adds the playtime of movies up
I have various folders with .avi and .mkv files in it.

I would like to write a script in ruby to count all these files and extract their playtime to see how much time I have spent watching movies.

I am new to programming, so I have no idea how to access the metadata in these files.

Any help on how to do this?

答:
I have never used it, but there is a gem called rvideo, which allows you to get video file metadata (it uses ffmpeg underneath).

According to the documentation to get the video file duration you'd just have to run:

```<code>RVideo::Inspector.new(:file => "some_file.avi").duration
</code>```

Couple that with Dir.glob, and you're pretty much set.

ContentLicense: CC BY-SA 2.5

Body:
I have never used it, but there is a gem called rvideo, which allows you to get video file metadata (it uses ffmpeg underneath).

According to the documentation to get the video file duration you'd just have to run:

RVideo::Inspector.new(:file => "some_file.avi").duration

Couple that with Dir.glob, and you're pretty much set.


问:
Extract local hour from timestamp with time zone
I'm trying to extract the local hour from a timestamp with time zone, but as I am new to working with this data type, I get unexpected results.

I was expecting 22 as output for every row below.

```<code>with my_data as(
   select to_timestamp_tz(ts, 'yyyy-mm-dd hh24:mi:ss tzh:tzm') as tsz
     from (select '2017-12-07 22:23:24 +' || lpad(level, 2, '0') || ':00' as ts
             from dual connect by level <= 10
          )
)
select dbtimezone
      ,sessiontimezone
      ,tsz
      ,extract(hour from tsz)
  from my_data;
</code>```

Why does this happen, and what do I need to do to extract the local hour from a timestamp with time zone?

答:
Check documentation of EXTRACT(datetime):

When extracting from a datetime with a time zone value, the value returned is in UTC.

Use TO_CHAR(tsz, 'HH24') or EXTRACT(hour from cast(tsz as timestamp)) if you like to get local hours.

Body:
I'm trying to extract the local hour from a timestamp with time zone, but as I am new to working with this data type, I get unexpected results.

I was expecting 22 as output for every row below.

with my_data as(
   select to_timestamp_tz(ts, 'yyyy-mm-dd hh24:mi:ss tzh:tzm') as tsz
     from (select '2017-12-07 22:23:24 +' || lpad(level, 2, '0') || ':00' as ts
             from dual connect by level <= 10
          )
)
select dbtimezone
      ,sessiontimezone
      ,tsz
      ,extract(hour from tsz)
  from my_data;

Why does this happen, and what do I need to do to extract the local hour from a timestamp with time zone?


问:
Dynamic Coroutine name
How can I make the name of the Coroutine dynamic?
I use this to make targets die automatically after a few seconds:

```<code>void InitiateKill(int i)
{
   //i is the number of the target
   StartCoroutine(TargetDie(i, timeAlive/1000));
   //some other stuff
}
</code>```

When the target is killed before this timer ends, I obviously get an error because it can't kill the target again.

That's why I want to stop the coroutine of that specific target, but I don't know how.

I tried:

```<code>Coroutine b[i] = StartCoroutine(TargetDie(i, timeAlive/1000));
</code>```

But that gives a syntax error. b[i] can't be used for Coroutines.

How to do this the proper way?

Update:

This is (the relevant part of) my TargetDie function:

```<code>IEnumerator TargetDie(int i, float delayTime)
{
    yield return new WaitForSeconds(delayTime);
    Destroy(targets[i]);
}
</code>```

When the player kills the target, I do:

```<code>void Damage(int i)
{
   // at this time, the first Coroutine, started in InitiateKill, should stop, because otherwise it tries to destroy the target twice
   StartCoroutine(TargetDie(i, 0));
}
</code>```

答:
So most simple way, move the coroutine on the object itself.

```<code>public class DieScript: MonoBehaviour
{
    private Manager manager;
    public void StartDeathProcess(Manager manager)
    {
        this.manager = manager;
        StartCoroutine(DieAsync(manager));
    }
    private IEnumerator DieAsync(Manager manager)
    {
        yield return new WaitForSeconds(timer);
        Destroy(this.gameObject);
    }
    public void Dmaage() // This is register as listener for death of the object
    {
         this.manager.PropagateDeath(this);
         Destroy(this.gameObject);
    }
}

public class Manager:MonoBehaviour
{
    private List<DieScript> die;
    void InitiateKill(int i)
    {
        die[i].StartDeathProcess(this);
    }
}
</code>```

Trying to keep the control on the controller is about to bring more pain than solution.

You could have a list of IEnumerator to keep track of the running coroutines. But you still need a message from the object to inform the controller that it is dead. So you are missing this part.
You need a script on the target so the controller knows about this type.
Controller runs the coroutine with a reference to that script asking each frame are you dying. When the target is meant to die, it sets a boolean to inform. Using Destroy keeps the object until end of frame so it would work out.

But this is doom to fail later on. It is kinda against programming concept to have a controller doing everything. You should see it more as a bypass for information.

Title: Dynamic Coroutine name

Body:
How can I make the name of the Coroutine dynamic?
I use this to make targets die automatically after a few seconds:

void InitiateKill(int i)
{
   //i is the number of the target
   StartCoroutine(TargetDie(i, timeAlive/1000));
   //some other stuff
}

When the target is killed before this timer ends, I obviously get an error because it can't kill the target again.

That's why I want to stop the coroutine of that specific target, but I don't know how.

I tried:

Coroutine b[i] = StartCoroutine(TargetDie(i, timeAlive/1000));

But that gives a syntax error. b[i] can't be used for Coroutines.

How to do this the proper way?

Update:

This is (the relevant part of) my TargetDie function:

IEnumerator TargetDie(int i, float delayTime)
{
    yield return new WaitForSeconds(delayTime);
    Destroy(targets[i]);
}

When the player kills the target, I do:

void Damage(int i)
{
   // at this time, the first Coroutine, started in InitiateKill, should stop, because otherwise it tries to destroy the target twice
   StartCoroutine(TargetDie(i, 0));
}

Body:
So most simple way, move the coroutine on the object itself.

public class DieScript: MonoBehaviour
{
    private Manager manager;
    public void StartDeathProcess(Manager manager)
    {
        this.manager = manager;
        StartCoroutine(DieAsync(manager));
    }
    private IEnumerator DieAsync(Manager manager)
    {
        yield return new WaitForSeconds(timer);
        Destroy(this.gameObject);
    }
    public void Dmaage() // This is register as listener for death of the object
    {
         this.manager.PropagateDeath(this);
         Destroy(this.gameObject);
    }
}

public class Manager:MonoBehaviour
{
    private List<DieScript> die;
    void InitiateKill(int i)
    {
        die[i].StartDeathProcess(this);
    }
}

Trying to keep the control on the controller is about to bring more pain than solution.

You could have a list of IEnumerator to keep track of the running coroutines. But you still need a message from the object to inform the controller that it is dead. So you are missing this part.
You need a script on the target so the controller knows about this type.
Controller runs the coroutine with a reference to that script asking each frame are you dying. When the target is meant to die, it sets a boolean to inform. Using Destroy keeps the object until end of frame so it would work out.

But this is doom to fail later on. It is kinda against programming concept to have a controller doing everything. You should see it more as a bypass for information.


问:
NoClassDefFoundError on Calligraphy library
After adding compile 'com.android.support:support-v13:21.0.+' to build.gradle, I had some conflicts on building my app, so I had to add multiDexEnabled = true to defaultConfig inside build.gradle. Those conflict are gone, but i got another exception (on opening the app) for the missing calligraphy library:

```<code>java.lang.NoClassDefFoundError: uk.co.chrisjenx.calligraphy.R$attr
        at uk.co.chrisjenx.calligraphy.CalligraphyConfig$Builder.<init>(CalligraphyConfig.java:150)
        at com.taxiyaab.android.util.ApplicationClass.onCreate(ApplicationClass.java:120)
        at newapp.com.taxiyaab.taxiyaab.PassengerApplication.onCreate(PassengerApplication.java:68)
        at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1007)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4462)
        at android.app.ActivityThread.access$1500(ActivityThread.java:144)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1306)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:212)
        at android.app.ActivityThread.main(ActivityThread.java:5135)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
        at dalvik.system.NativeStart.main(Native Method)
</code>```

My latest sdk build tools version is 22.0.1. Has anybody faced this issue before?

答:
Yes,update to multidex 1.0.2
and add Mulitidex.install(this) to the class extending application</p>

Body:
After adding compile 'com.android.support:support-v13:21.0.+' to build.gradle, I had some conflicts on building my app, so I had to add multiDexEnabled = true to defaultConfig inside build.gradle. Those conflict are gone, but i got another exception (on opening the app) for the missing calligraphy library:

java.lang.NoClassDefFoundError: uk.co.chrisjenx.calligraphy.R$attr
        at uk.co.chrisjenx.calligraphy.CalligraphyConfig$Builder.<init>(CalligraphyConfig.java:150)
        at com.taxiyaab.android.util.ApplicationClass.onCreate(ApplicationClass.java:120)
        at newapp.com.taxiyaab.taxiyaab.PassengerApplication.onCreate(PassengerApplication.java:68)
        at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1007)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4462)
        at android.app.ActivityThread.access$1500(ActivityThread.java:144)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1306)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:212)
        at android.app.ActivityThread.main(ActivityThread.java:5135)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
        at dalvik.system.NativeStart.main(Native Method)

My latest sdk build tools version is 22.0.1. Has anybody faced this issue before?


问:
RxSwift UITableView binding when also using a UISearchController
In my view controller I have a UISearchController associated with the UITableView.  So all my normal table view datasource methods do the old

if isSearching {
    // use filteredTableData array
} else {
    // use SharedModel.shared.participants
}
```

I'm not clear on how I'd implement that using RxCocoa as I'm brand new to Rx.

答:
I solve this by declaring a decorator for an Observable and an extension for a UISearchBar (you could also declare it for the UISearchController):

```<code>//FIXME: Item can't be type constrained. Have to use optional casting.
class FilterableByTitleCollection<Item>: ObservableType {

    private let origin: Observable<Array<Item>>
    private let filteringStrategySource: Observable<TitlableModelFilteringStrategy> //FIXME: This is a strategy source

    init<Origin: ObservableType>(
        origin: Origin,
        filteringStrategySource: Observable<TitlableModelFilteringStrategy>) where Origin.E == Array<Item> {
        self.origin = origin.asObservable()
        self.filteringStrategySource = filteringStrategySource
    }

    typealias E = Array<Item>
    func subscribe<O:ObserverType>(_ observer: O) -> Disposable where O.E == Array<Item> {
        return Observable.combineLatest(
                origin,
                filteringStrategySource
            )
            .observeOn(ConcurrentDispatchQueueScheduler(qos: .userInitiated))
            .map{ origin, strategy in
                guard origin is Array<Titlable> else { assert(false); return origin }
                return origin.filter{ strategy.shouldInclude(item: $0 as! Titlable) }
            }
            .observeOn(MainScheduler.instance)
            .subscribe(observer)
    }

}
</code>```

...

```<code>extension UISearchBar {

    var titlableFilteringStrategy: Observable<TitlableModelFilteringStrategy> {
        return Observable<String?>.merge(
            [
                self.rx.text.asObservable(),
                self.rx.textDidEndEditing
                    .map{ [weak self] in
                        assert(self != nil)
                        return self?.text
                    },
                self.rx.cancelButtonClicked.map{ Optional<String>.some("") }
            ]
        ).distinctUntilChanged{ (old: String?, new: String?) -> Bool in
            old == new
        }.map{ TitlableModelFilteringStrategy(filteringPredicate: $0) }
    }

}
</code>```

...

```<code>struct TitlableModelFilteringStrategy {

    private let filteringPredicate: String
    init(filteringPredicate: String?) {
        self.filteringPredicate = filteringPredicate ?? ""
    }

    func shouldInclude(item: Titlable) -> Bool {
        return filteringPredicate.isEmpty ? true : item.title.localizedCaseInsensitiveContains(filteringPredicate)
    }

    func equals(to another: TitlableModelFilteringStrategy) -> Bool {
        return filteringPredicate == another.filteringPredicate
    }

}
</code>```

...

```<code>protocol Titlable {

    var title: String { get }

}
</code>```

Body:
In my view controller I have a UISearchController associated with the UITableView.  So all my normal table view datasource methods do the old

if isSearching {
    // use filteredTableData array
} else {
    // use SharedModel.shared.participants
}

I'm not clear on how I'd implement that using RxCocoa as I'm brand new to Rx.

Body:
I solve this by declaring a decorator for an Observable and an extension for a UISearchBar (you could also declare it for the UISearchController):

//FIXME: Item can't be type constrained. Have to use optional casting.
class FilterableByTitleCollection<Item>: ObservableType {

    private let origin: Observable<Array<Item>>
    private let filteringStrategySource: Observable<TitlableModelFilteringStrategy> //FIXME: This is a strategy source

    init<Origin: ObservableType>(
        origin: Origin,
        filteringStrategySource: Observable<TitlableModelFilteringStrategy>) where Origin.E == Array<Item> {
        self.origin = origin.asObservable()
        self.filteringStrategySource = filteringStrategySource
    }

    typealias E = Array<Item>
    func subscribe<O:ObserverType>(_ observer: O) -> Disposable where O.E == Array<Item> {
        return Observable.combineLatest(
                origin,
                filteringStrategySource
            )
            .observeOn(ConcurrentDispatchQueueScheduler(qos: .userInitiated))
            .map{ origin, strategy in
                guard origin is Array<Titlable> else { assert(false); return origin }
                return origin.filter{ strategy.shouldInclude(item: $0 as! Titlable) }
            }
            .observeOn(MainScheduler.instance)
            .subscribe(observer)
    }

}

...

extension UISearchBar {

    var titlableFilteringStrategy: Observable<TitlableModelFilteringStrategy> {
        return Observable<String?>.merge(
            [
                self.rx.text.asObservable(),
                self.rx.textDidEndEditing
                    .map{ [weak self] in
                        assert(self != nil)
                        return self?.text
                    },
                self.rx.cancelButtonClicked.map{ Optional<String>.some("") }
            ]
        ).distinctUntilChanged{ (old: String?, new: String?) -> Bool in
            old == new
        }.map{ TitlableModelFilteringStrategy(filteringPredicate: $0) }
    }

}

...

struct TitlableModelFilteringStrategy {

    private let filteringPredicate: String
    init(filteringPredicate: String?) {
        self.filteringPredicate = filteringPredicate ?? ""
    }

    func shouldInclude(item: Titlable) -> Bool {
        return filteringPredicate.isEmpty ? true : item.title.localizedCaseInsensitiveContains(filteringPredicate)
    }

    func equals(to another: TitlableModelFilteringStrategy) -> Bool {
        return filteringPredicate == another.filteringPredicate
    }

}

...

protocol Titlable {

    var title: String { get }

}


问:
Using Jupyter Lab with tmpnb
I am trying to use JupyterLab using tmpnb

I want to spawn many JupyterLab instances, just like the way tmpnb does for Jupyter Notebook.

I have created a new docker image by docker build -t jupyterlab2 . command using the following Dockerfile:

```<code>FROM jupyter/datascience-notebook
MAINTAINER apr
RUN pip install npm
RUN pip install jupyterlab
RUN jupyter serverextension enable --py jupyterlab
</code>```

After this I am running the following commands:

```<code>export TOKEN=$( head -c 30 /dev/urandom | xxd -p )

docker run --net=host -d -e CONFIGPROXY_AUTH_TOKEN=$TOKEN --name=proxy jupyter/configurable-http-proxy --default-target http://127.0.0.1:9999

docker run --net=host -d -e CONFIGPROXY_AUTH_TOKEN=$TOKEN --name=tmpnb -v /var/run/docker.sock:/docker.sock jupyter/tmpnb python orchestrate.py --allow_origin='*' --image='jupyterlab2' --pool-size=5 --container-user=root  --command='jupyter lab --allow-root LabApp.allow_origin="*"'
</code>```

When I visit the URL http://<ip-address>:8000, I get redirected to http://<ip>:8000/user/sTVKGwH01uoQ, but this shows 404.
I also tried visiting http://<ip>:8000/user/sTVKGwH01uoQ/lab but this too gives 404.

Logs for 1 instance are below:

```<code>Set username to: jovyan
usermod: no changes
Set jovyan GID to: 100
Execute the command: jupyter lab --allow-root --port 8888 --ip=0.0.0.0 --LabApp.allow_origin=*
[I 09:05:52.598 LabApp] Writing notebook server cookie secret to /home/jovyan/.local/share/jupyter/runtime/notebook_cookie_secret
[I 09:05:54.689 LabApp] JupyterLab alpha preview extension loaded from /opt/conda/lib/python3.6/site-packages/jupyterlab
[I 09:05:54.694 LabApp] Serving notebooks from local directory: /home/jovyan
[I 09:05:54.694 LabApp] 0 active kernels
[I 09:05:54.694 LabApp] The Jupyter Notebook is running at:
[I 09:05:54.694 LabApp] http://0.0.0.0:8888/?token=584fc5114d037ad23296ca8284ea1074b220d058018cb2c4
[I 09:05:54.694 LabApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[C 09:05:54.695 LabApp]

    Copy/paste this URL into your browser when you connect for the first time,
    to login with a token:
        http://0.0.0.0:8888/?token=584fc5114d037ad23296ca8284ea1074b220d058018cb2c4
[I 09:05:57.142 LabApp] 302 GET /user/1BhE9UZ2gg5o/ (172.17.0.1) 0.54ms
[W 09:05:57.144 LabApp] 404 GET /user/1BhE9UZ2gg5o (172.17.0.1) 1.45ms referer=None
[I 09:05:57.347 LabApp] 302 GET /user/1BhE9UZ2gg5o/ (172.17.0.1) 0.56ms
[W 09:05:57.350 LabApp] 404 GET /user/1BhE9UZ2gg5o (172.17.0.1) 1.44ms referer=None
[I 09:05:57.553 LabApp] 302 GET /user/1BhE9UZ2gg5o/ (172.17.0.1) 0.55ms
[W 09:05:57.556 LabApp] 404 GET /user/1BhE9UZ2gg5o (172.17.0.1) 1.41ms referer=None
[I 09:05:57.767 LabApp] 302 GET /user/1BhE9UZ2gg5o/ (172.17.0.1) 2.80ms
[W 09:05:57.773 LabApp] 404 GET /user/1BhE9UZ2gg5o (172.17.0.1) 3.44ms referer=None
[I 09:05:57.978 LabApp] 302 GET /user/1BhE9UZ2gg5o/ (172.17.0.1) 0.56ms
[W 09:05:57.981 LabApp] 404 GET /user/1BhE9UZ2gg5o (172.17.0.1) 1.46ms referer=None
[I 09:05:58.184 LabApp] 302 GET /user/1BhE9UZ2gg5o/ (172.17.0.1) 0.55ms
[W 09:05:58.187 LabApp] 404 GET /user/1BhE9UZ2gg5o (172.17.0.1) 1.42ms referer=None
[I 09:05:58.391 LabApp] 302 GET /user/1BhE9UZ2gg5o/ (172.17.0.1) 0.56ms
[W 09:05:58.394 LabApp] 404 GET /user/1BhE9UZ2gg5o (172.17.0.1) 2.05ms referer=None
[W 09:06:18.518 LabApp] 404 GET /user/1BhE9UZ2gg5o/tree (172.17.0.1) 1.61ms referer=http://52.71.15.52:8000/
[W 09:06:27.502 LabApp] 404 GET /user/1BhE9UZ2gg5o/lab (172.17.0.1) 2.51ms referer=None
[W 09:07:20.568 LabApp] 404 GET /user/1BhE9UZ2gg5o/lab (172.17.0.1) 2.28ms referer=None
</code>```

I looked at an issue related to JupyterHub, which looked very similar. The 404 error page is same for me too. I tried some random things with start.sh too, but no luck.

Is it even possible to run JupyterLab using tmpnb? If no, then what are the other tools that I can use the achieve the same purpose?

答:
The base URL must be set, otherwise the /user/... routes won't map to the right things. This is the --NotebookApp.base_url={base_path} part in the all of the example commands in the tmpnb README. These look like:

```<code>python orchestrate.py --command='jupyter notebook --no-browser \
    --port {port} --ip=0.0.0.0 --NotebookApp.base_url={base_path} \
    --NotebookApp.port_retries=0'
</code>```

So a JupyterLab equivalent would be:

```<code>python orchestrate.py --command='jupyter lab --no-browser \
    --port {port} --ip=0.0.0.0 --NotebookApp.base_url={base_path} \
    --NotebookApp.port_retries=0'
</code>```

All of those apply with jupyterlab as well, so probably the only arg you want to replace is notebook with lab. At the same time, you don't need to change the default command at all, because if the lab extension is installed, jupyterlab is available at the /lab URL when you start jupyter notebook. You can see this right now by replacing /tree with /lab on any existing tmpnb.org URL.

Title: Using Jupyter Lab with tmpnb

Body:
I am trying to use JupyterLab using tmpnb

I want to spawn many JupyterLab instances, just like the way tmpnb does for Jupyter Notebook.

I have created a new docker image by docker build -t jupyterlab2 . command using the following Dockerfile:

FROM jupyter/datascience-notebook
MAINTAINER apr
RUN pip install npm
RUN pip install jupyterlab
RUN jupyter serverextension enable --py jupyterlab

After this I am running the following commands:

export TOKEN=$( head -c 30 /dev/urandom | xxd -p )

docker run --net=host -d -e CONFIGPROXY_AUTH_TOKEN=$TOKEN --name=proxy jupyter/configurable-http-proxy --default-target http://127.0.0.1:9999

docker run --net=host -d -e CONFIGPROXY_AUTH_TOKEN=$TOKEN --name=tmpnb -v /var/run/docker.sock:/docker.sock jupyter/tmpnb python orchestrate.py --allow_origin='*' --image='jupyterlab2' --pool-size=5 --container-user=root  --command='jupyter lab --allow-root LabApp.allow_origin="*"'

When I visit the URL http://<ip-address>:8000, I get redirected to http://<ip>:8000/user/sTVKGwH01uoQ, but this shows 404.
I also tried visiting http://<ip>:8000/user/sTVKGwH01uoQ/lab but this too gives 404.

Logs for 1 instance are below:

Set username to: jovyan
usermod: no changes
Set jovyan GID to: 100
Execute the command: jupyter lab --allow-root --port 8888 --ip=0.0.0.0 --LabApp.allow_origin=*
[I 09:05:52.598 LabApp] Writing notebook server cookie secret to /home/jovyan/.local/share/jupyter/runtime/notebook_cookie_secret
[I 09:05:54.689 LabApp] JupyterLab alpha preview extension loaded from /opt/conda/lib/python3.6/site-packages/jupyterlab
[I 09:05:54.694 LabApp] Serving notebooks from local directory: /home/jovyan
[I 09:05:54.694 LabApp] 0 active kernels
[I 09:05:54.694 LabApp] The Jupyter Notebook is running at:
[I 09:05:54.694 LabApp] http://0.0.0.0:8888/?token=584fc5114d037ad23296ca8284ea1074b220d058018cb2c4
[I 09:05:54.694 LabApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[C 09:05:54.695 LabApp]

    Copy/paste this URL into your browser when you connect for the first time,
    to login with a token:
        http://0.0.0.0:8888/?token=584fc5114d037ad23296ca8284ea1074b220d058018cb2c4
[I 09:05:57.142 LabApp] 302 GET /user/1BhE9UZ2gg5o/ (172.17.0.1) 0.54ms
[W 09:05:57.144 LabApp] 404 GET /user/1BhE9UZ2gg5o (172.17.0.1) 1.45ms referer=None
[I 09:05:57.347 LabApp] 302 GET /user/1BhE9UZ2gg5o/ (172.17.0.1) 0.56ms
[W 09:05:57.350 LabApp] 404 GET /user/1BhE9UZ2gg5o (172.17.0.1) 1.44ms referer=None
[I 09:05:57.553 LabApp] 302 GET /user/1BhE9UZ2gg5o/ (172.17.0.1) 0.55ms
[W 09:05:57.556 LabApp] 404 GET /user/1BhE9UZ2gg5o (172.17.0.1) 1.41ms referer=None
[I 09:05:57.767 LabApp] 302 GET /user/1BhE9UZ2gg5o/ (172.17.0.1) 2.80ms
[W 09:05:57.773 LabApp] 404 GET /user/1BhE9UZ2gg5o (172.17.0.1) 3.44ms referer=None
[I 09:05:57.978 LabApp] 302 GET /user/1BhE9UZ2gg5o/ (172.17.0.1) 0.56ms
[W 09:05:57.981 LabApp] 404 GET /user/1BhE9UZ2gg5o (172.17.0.1) 1.46ms referer=None
[I 09:05:58.184 LabApp] 302 GET /user/1BhE9UZ2gg5o/ (172.17.0.1) 0.55ms
[W 09:05:58.187 LabApp] 404 GET /user/1BhE9UZ2gg5o (172.17.0.1) 1.42ms referer=None
[I 09:05:58.391 LabApp] 302 GET /user/1BhE9UZ2gg5o/ (172.17.0.1) 0.56ms
[W 09:05:58.394 LabApp] 404 GET /user/1BhE9UZ2gg5o (172.17.0.1) 2.05ms referer=None
[W 09:06:18.518 LabApp] 404 GET /user/1BhE9UZ2gg5o/tree (172.17.0.1) 1.61ms referer=http://52.71.15.52:8000/
[W 09:06:27.502 LabApp] 404 GET /user/1BhE9UZ2gg5o/lab (172.17.0.1) 2.51ms referer=None
[W 09:07:20.568 LabApp] 404 GET /user/1BhE9UZ2gg5o/lab (172.17.0.1) 2.28ms referer=None

I looked at an issue related to JupyterHub, which looked very similar. The 404 error page is same for me too. I tried some random things with start.sh too, but no luck.

Is it even possible to run JupyterLab using tmpnb? If no, then what are the other tools that I can use the achieve the same purpose?

Body:
The base URL must be set, otherwise the /user/... routes won't map to the right things. This is the --NotebookApp.base_url={base_path} part in the all of the example commands in the tmpnb README. These look like:

python orchestrate.py --command='jupyter notebook --no-browser \
    --port {port} --ip=0.0.0.0 --NotebookApp.base_url={base_path} \
    --NotebookApp.port_retries=0'

So a JupyterLab equivalent would be:

python orchestrate.py --command='jupyter lab --no-browser \
    --port {port} --ip=0.0.0.0 --NotebookApp.base_url={base_path} \
    --NotebookApp.port_retries=0'

All of those apply with jupyterlab as well, so probably the only arg you want to replace is notebook with lab. At the same time, you don't need to change the default command at all, because if the lab extension is installed, jupyterlab is available at the /lab URL when you start jupyter notebook. You can see this right now by replacing /tree with /lab on any existing tmpnb.org URL.


问:
How to add Logout from all other session
My scenario is there are two different users login with same user id and password.mean time one of the person change the password by giving the current password. And changed the password at same time the another user gives current password what he logged in was incorrect. So i wants to add logout from all other devices in my web application.how can i do that</p>

答:
There is of course more than one approach, my first idea would be to hook the sessions to the ServletContext. Something like

```<code>// this can be in some util class, let's call it SessionUtil
static final String SESSION_REGISTER = "session.register";
public static synchronized void registerSession(ServletRequest req, HttpSession ses, String userName) {
  ServletContext ctx = req.getServletContext();
  Map<String, List<HttpSession>> register = (Map<String, List<HttpSession>>) ctx.getAttribute(SESSION_REGISTER);
  if (register == null) {
    register = new HashMap<>();
    ctx.setAttribute(SESSION_REGISTER, register);
  }
  List<HttpSession> sessions = register.computeIfAbsent(userName, k -> new ArrayList<>());
  sessions.add(ses);
}
</code>```

Then, in your code, you need to register the user's session after login:

```<code>HttpSession ss = request.getSession();
if (isUser(name,password)) {
  ss.setAttribute("user",name)
  SessionUtil.registerSession(request, ss, name);
}
</code>```

Finally, you need a method (again in SessionUtil class) to invalidate all the user's sessions (except the current one):

```<code>public static synchronized void invalidateSessions(ServletRequest req, HttpSession current, String userName) {
  ServletContext ctx = req.getServletContext();
  Map<String, List<HttpSession>> register = (Map<String, List<HttpSession>>) ctx.getAttribute(SESSION_REGISTER);
  if (register != null) {
    List<HttpSession> sessions = register.get(userName);
    if (sessions != null) {
      for (HttpSession ses : sessions) {
        if (!ses.equals(current)) {
          ses.invalidate();
        }
      }
    }
  }
}
</code>```

Then you can call this method e.g. when the user changes his/her password.

Note #1: Not a very nice code, it misses some sanity checks and synchronized can be smaller chunks of code. It's just to give you an idea.

Note #2: The functionality of the registerSession(...) method can be done using the HttpSessionAttributeListener, but I've never used it yet, so cannot give an example.

Body:
There is of course more than one approach, my first idea would be to hook the sessions to the ServletContext. Something like

// this can be in some util class, let's call it SessionUtil
static final String SESSION_REGISTER = "session.register";
public static synchronized void registerSession(ServletRequest req, HttpSession ses, String userName) {
  ServletContext ctx = req.getServletContext();
  Map<String, List<HttpSession>> register = (Map<String, List<HttpSession>>) ctx.getAttribute(SESSION_REGISTER);
  if (register == null) {
    register = new HashMap<>();
    ctx.setAttribute(SESSION_REGISTER, register);
  }
  List<HttpSession> sessions = register.computeIfAbsent(userName, k -> new ArrayList<>());
  sessions.add(ses);
}

Then, in your code, you need to register the user's session after login:

HttpSession ss = request.getSession();
if (isUser(name,password)) {
  ss.setAttribute("user",name)
  SessionUtil.registerSession(request, ss, name);
}

Finally, you need a method (again in SessionUtil class) to invalidate all the user's sessions (except the current one):

public static synchronized void invalidateSessions(ServletRequest req, HttpSession current, String userName) {
  ServletContext ctx = req.getServletContext();
  Map<String, List<HttpSession>> register = (Map<String, List<HttpSession>>) ctx.getAttribute(SESSION_REGISTER);
  if (register != null) {
    List<HttpSession> sessions = register.get(userName);
    if (sessions != null) {
      for (HttpSession ses : sessions) {
        if (!ses.equals(current)) {
          ses.invalidate();
        }
      }
    }
  }
}

Then you can call this method e.g. when the user changes his/her password.

Note #1: Not a very nice code, it misses some sanity checks and synchronized can be smaller chunks of code. It's just to give you an idea.

Note #2: The functionality of the registerSession(...) method can be done using the HttpSessionAttributeListener, but I've never used it yet, so cannot give an example.


问:
How can I change the width of the Textbox in the header?
We are using Wix Toolset 3.11 to build an .msi. We use a banner that contains our company logo:

```<code><WixVariable Id="WixUIBannerBmp" Value="Banner.bmp"/>
</code>```

The Problem: Our logo has a width of 130px. In some Dialogs, the text in the header is too long and collides with the Logo:

Question: How can we limit the width of the textbox in the header so that the text will break into the next line?

答:
In your .wxl File add an UI-Element and set the width of the Description control for a dialog:

```<code><WixLocalization>
    [...]
    <UI Dialog="InstallDirDlg" Control="Description" Width="whatever, default 280"/>
</WixLocalization>
</code>```

Instead of the Description control you also can change the width of the Title control.

How to customize UI Dialogs in Wix to modify location/size of Labels

If you want your text to wrap in the control, be sure to set also the Height attribute large enough.  E.g. to double the height of the above control, set Height="30".

Body:
We are using Wix Toolset 3.11 to build an .msi. We use a banner that contains our company logo:

<WixVariable Id="WixUIBannerBmp" Value="Banner.bmp"/>

The Problem: Our logo has a width of 130px. In some Dialogs, the text in the header is too long and collides with the Logo:

Question: How can we limit the width of the textbox in the header so that the text will break into the next line?

Body:
In your .wxl File add an UI-Element and set the width of the Description control for a dialog:

<WixLocalization>
    [...]
    <UI Dialog="InstallDirDlg" Control="Description" Width="whatever, default 280"/>
</WixLocalization>

Instead of the Description control you also can change the width of the Title control.

How to customize UI Dialogs in Wix to modify location/size of Labels

If you want your text to wrap in the control, be sure to set also the Height attribute large enough.  E.g. to double the height of the above control, set Height="30".


问:
Should I set my TextView colours if my background colour is not set?
When I comes to specifying colours for an application, I recently came across @android:color. Is it recommended to try to always use predefined system colors?

I changed the colours of some of my labels to something brighter, so that they'll stand out against the black background. But then I start to wonder... would themes/skins (not familiar with those) and such cause the default background colour to be something other than black?

If so... what's the proper way to deal with colouring one's widgets?

答:
(Disclaimer: I don't know Android.  This is general UI design advice.)

If you set the foreground color, you should change the background color as well.  Otherwise, if someone's background is set to something wacky, your labels could wind up invisible -- or at the least, hard to see -- and you'll have defeated the purpose of using different colors.

I'd recommend you leave the colors as they are, unless you can change the background color as well.  Perhaps using a bold font or something would be a better idea.


问:
Dynatree or Fancytree for production?
I am looking for a javascript solution which can unordered list to a treeview with checkboxes.

So far the best one I have seen is Dynatree. However, looking at the page and the fiddle , I learned that there is a designated successor named Fancytree.

I am planning to implement the solution in a production environment.

Which is the best library to use?

答:
Dynatree is EOL. Last commit was on 19 Aug 2016.

I will support Dynatree for a while, but no new features will be added.
  It is recommended to migrate to Fancytree. It's easy: see also the migration hints.

Src

Title: Dynatree or Fancytree for production?


问:
Rearranging a sublist within a list
I am having a hard time rearanging a list of tuples of names, first and last. I want to sort the list by last name and if there are identical last names then the sublist of those names should be arranged by first name. The first part was pretty easy with sorted and key=get_key1 but I am having diffuculties to complete the second part of the problem.

A list like this:

```<code>[('Tom','Haim'),('Eli','Levi'),('Eli','Cohen'),('Moshe','Levi'),('Haim','Cohen'),('Dina','Ram'),('Tova','Ben'),('Ben','Levi'),('Gil','Cohen'),('Eli','Ram')]
</code>```

should come out like:

```<code>[('Tova', 'Ben'), ('Eli', 'Cohen'), ('Gil', 'Cohen'), ('Haim', 'Cohen'), ('Tom', 'Haim'), ('Ben', 'Levi'), ('Eli', 'Levi'), ('Moshe', 'Levi'), ('Dina', 'Ram'), ('Eli', 'Ram')]
</code>```

Best I got is:

```<code>[('Tova', 'Ben'), ('Eli', 'Cohen'), ('Haim', 'Cohen'), ('Gil', 'Cohen'), ('Tom', 'Haim'), ('Eli', 'Levi'), ('Moshe', 'Levi'), ('Ben', 'Levi'), ('Dina', 'Ram'), ('Eli', 'Ram')]
</code>```

Thank you

答:
If you return a tuple as a key it will first sort by the first element and then by the second. Since you want to sort by first last name then first name your key should return (last name, first name).

```<code>l = [('Tom','Haim'),('Eli','Levi'),('Eli','Cohen'),('Moshe','Levi'),('Haim','Cohen'),('Dina','Ram'),('Tova','Ben'),('Ben','Levi'),('Gil','Cohen'),('Eli','Ram')]

def get_key1(x):
    return (x[1], x[0])

print(sorted(l, key=get_key1))
</code>```

Title: Rearranging a sublist within a list

Body:
I am having a hard time rearanging a list of tuples of names, first and last. I want to sort the list by last name and if there are identical last names then the sublist of those names should be arranged by first name. The first part was pretty easy with sorted and key=get_key1 but I am having diffuculties to complete the second part of the problem.

A list like this:

[('Tom','Haim'),('Eli','Levi'),('Eli','Cohen'),('Moshe','Levi'),('Haim','Cohen'),('Dina','Ram'),('Tova','Ben'),('Ben','Levi'),('Gil','Cohen'),('Eli','Ram')]

should come out like:

[('Tova', 'Ben'), ('Eli', 'Cohen'), ('Gil', 'Cohen'), ('Haim', 'Cohen'), ('Tom', 'Haim'), ('Ben', 'Levi'), ('Eli', 'Levi'), ('Moshe', 'Levi'), ('Dina', 'Ram'), ('Eli', 'Ram')]

Best I got is:

[('Tova', 'Ben'), ('Eli', 'Cohen'), ('Haim', 'Cohen'), ('Gil', 'Cohen'), ('Tom', 'Haim'), ('Eli', 'Levi'), ('Moshe', 'Levi'), ('Ben', 'Levi'), ('Dina', 'Ram'), ('Eli', 'Ram')]

Thank you

Body:
If you return a tuple as a key it will first sort by the first element and then by the second. Since you want to sort by first last name then first name your key should return (last name, first name).

l = [('Tom','Haim'),('Eli','Levi'),('Eli','Cohen'),('Moshe','Levi'),('Haim','Cohen'),('Dina','Ram'),('Tova','Ben'),('Ben','Levi'),('Gil','Cohen'),('Eli','Ram')]

def get_key1(x):
    return (x[1], x[0])

print(sorted(l, key=get_key1))


问:
Convert html.slim views to html.erb - Rails, Slim, ERB
Trying to convert *.html.slim views to *.html.erb. I've looked at these two questions:

How can I convert html.slim to html.erb? - getting uninitialized constant when called from the console

How can I convert html.slim files to html or html.erb? - parser hits a NoMethodError: undefined method image_tag for nil:NilClass when it comes across the first = image_tag. I am not using any variables inside my call, the image tag points to and svg

I think the latter solution would work best, if the good people of Stack Overflow can help me figure out the image_tag issue.

My code (as requested):

```<code>page data-id="foo-page"
  .container
    = image_tag 'bar.svg'
</code>```

答:
I was using gitbash on windows, </p>

<p>and this worked for me, </p>

```<code>slimrb -e foo.html.slim foo.html.erb
</code>```

Body:
Trying to convert *.html.slim views to *.html.erb. I've looked at these two questions:

How can I convert html.slim to html.erb? - getting uninitialized constant when called from the console

How can I convert html.slim files to html or html.erb? - parser hits a NoMethodError: undefined method image_tag for nil:NilClass when it comes across the first = image_tag. I am not using any variables inside my call, the image tag points to and svg

I think the latter solution would work best, if the good people of Stack Overflow can help me figure out the image_tag issue.

My code (as requested):

page data-id="foo-page"
  .container
    = image_tag 'bar.svg'

Body:
I was using gitbash on windows,

and this worked for me,

slimrb -e foo.html.slim foo.html.erb


答:
As others already said, if your oneliner is too complex to fit into one line, you should use a script.

In some rare cases (and when the script is debugged and working), you can inline the perl script into your bash script as:

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

# bash function which prints the perl script
perlcode() {
cat - <<'PERLCODE'
use scrict;
use warnings;
# ... rest of your script
PERLCODE
}

#and use the inlined script as
perl <(perlcode)
</code>```

The above works because it uses the bash's process substitution mechanism, where first is executed the commands enclosed in the <(...commands...) and the stdout of result is acts as an temporary file.

So, the perl <(perlcode) first execute the perlcode bash function, (which just prints the perl source code), and in the next step the bash uses the result as

```<code>perl /dev/fd/63 #some temporary file descriptor
</code>```

e.g. exactly as perl /path/to/script. Such inlined perl script is works as ordinary perl script and for example could contain the __DATA__ section too.

You must use the quoted << 'HEREDOC' form to avoid variable expansion.

But really, only becasuse you can do something like the above, doesn't mean that you should. It is always much better to have a perl script in some file alone.

Title: How to format a perl oneliner?

Body:
If I have a perl one liner running it from the command line: e.g

perl -MData::Dumper -MJSON=decode_json -e 'my @array = @{decode_json($data)}; foreach my $i (@array) { etc }'

How could I format it so that it is more readable i.e. add new lines? If I do something like:

Ma

The command breaks when I add the new lines like that to format the code

Body:
As others already said, if your oneliner is too complex to fit into one line, you should use a script.

In some rare cases (and when the script is debugged and working), you can inline the perl script into your bash script as:

#!/bin/bash

# bash function which prints the perl script
perlcode() {
cat - <<'PERLCODE'
use scrict;
use warnings;
# ... rest of your script
PERLCODE
}

#and use the inlined script as
perl <(perlcode)

The above works because it uses the bash's process substitution mechanism, where first is executed the commands enclosed in the <(...commands...) and the stdout of result is acts as an temporary file.

So, the perl <(perlcode) first execute the perlcode bash function, (which just prints the perl source code), and in the next step the bash uses the result as

perl /dev/fd/63 #some temporary file descriptor

e.g. exactly as perl /path/to/script. Such inlined perl script is works as ordinary perl script and for example could contain the __DATA__ section too.

You must use the quoted << 'HEREDOC' form to avoid variable expansion.

But really, only becasuse you can do something like the above, doesn't mean that you should. It is always much better to have a perl script in some file alone.


问:
Find the the value of one field that matches the maximum value of data in another field
I'm trying to write a query that gets the value of one field that's associated with the maximum value of another field (or fields).  Let's say I have the following table of data:

```<code>OrderID CustomerID  OrderDate   LocationID
1       4           1/1/2001    1001
2       4           1/2/2001    1003
3       4           1/3/2001    1001
4       5           1/4/2001    1001
5       5           1/5/2001    1001
6       5           1/6/2001    1003
7       5           1/7/2001    1002
8       5           1/8/2001    1003
9       5           1/8/2001    1002
</code>```

Grouping by CustomerID, I want to get the maximum OrderDate and then the LocationID associated with whatever is the maximum OrderDate.  If there are several records that share the maximum order date, then take the LocationID associated with the maximum OrderID from among those records with the maximum date.

The final set of data should look like this:

```<code>CustomerID  OrderDate   LocationID
4           1/3/2001    1001
5           1/8/2001    1002
</code>```

I had been trying to write a query with lots of nested subqueries and ugly joins, but I'm not really getting anywhere.  What SQL do I need to write to help me get this result.

答:
```<code>with cte As
(
select *,
        row_number() over (partition by CustomerID
                           order by OrderDate desc, OrderId desc) as rn
from yourtable
)
select CustomerID, OrderDate,LocationID
from cte
where rn=1;
</code>```

Body:
I'm trying to write a query that gets the value of one field that's associated with the maximum value of another field (or fields).  Let's say I have the following table of data:

OrderID CustomerID  OrderDate   LocationID
1       4           1/1/2001    1001
2       4           1/2/2001    1003
3       4           1/3/2001    1001
4       5           1/4/2001    1001
5       5           1/5/2001    1001
6       5           1/6/2001    1003
7       5           1/7/2001    1002
8       5           1/8/2001    1003
9       5           1/8/2001    1002

Grouping by CustomerID, I want to get the maximum OrderDate and then the LocationID associated with whatever is the maximum OrderDate.  If there are several records that share the maximum order date, then take the LocationID associated with the maximum OrderID from among those records with the maximum date.

The final set of data should look like this:

CustomerID  OrderDate   LocationID
4           1/3/2001    1001
5           1/8/2001    1002

I had been trying to write a query with lots of nested subqueries and ugly joins, but I'm not really getting anywhere.  What SQL do I need to write to help me get this result.


问:
Prestashop order products sql
Where I can find Prestashop SQL query where they display the products that were bought in order.

Like this:

I'm creating a custom page that shows 100 orders in table. and if clicked on order its shows the products that were ordered. I made an sql query:

```<code>SELECT product_id, product_reference AS kood,product_name AS nimetus,product_quantity AS nr, pl.link_rewrite,psa.quantity as kogukogus,group_concat(ps.product_supplier_reference) as supp_ref, p.location AS asukoht,
         CONCAT(c.link_rewrite,'/',p.id_product,'-',pl.link_rewrite,'.html') link
        FROM ps_order_detail o
        LEFT JOIN ps_product_lang pl on o.product_id = pl.id_product
        LEFT JOIN ps_product p on p.id_product = pl.id_product
        LEFT JOIN ps_stock_available psa on p.id_product = psa.id_product
        LEFT JOIN ps_category_lang c on c.id_category = p.id_category_default
        LEFT JOIN ps_product_supplier ps on p.id_product = ps.id_product
        WHERE pl.id_lang=2 AND c.id_lang=2 AND id_order= '".$q."'
        GROUP BY product_id, kood,nimetus,nr,pl.link_rewrite, kogukogus,asukoht, link
</code>```

But when product has attributes it duplicates products.

In this case iButton has two colors black and red(attributes). In this order only one black iButton was bought with quantity of 20, but It shows three rows.

I tried to fix this, but that arised another problems with my sql query, that when it has no attribute it dosen't show anything.

```<code>SELECT product_id, product_reference AS kood,product_name AS nimetus,product_quantity AS nr, pl.link_rewrite,psa.quantity as kogukogus,group_concat(ps.product_supplier_reference) as supp_ref, p.location AS asukoht,
         CONCAT(c.link_rewrite,'/',p.id_product,'-',pl.link_rewrite,'.html') link
        FROM ps_order_detail o
        JOIN ps_product_lang pl on o.product_id = pl.id_product
        JOIN ps_product p on p.id_product = pl.id_product
        JOIN ps_stock_available psa on p.id_product = psa.id_product
        JOIN ps_category_lang c on c.id_category = p.id_category_default
        JOIN ps_product_supplier ps on p.id_product = ps.id_product
        LEFT JOIN ps_product_attribute pa on p.id_product=pa.id_product
        WHERE pl.id_lang=2 AND pa.id_product_attribute = psa.id_product_attribute AND pa.id_product_attribute =o.product_attribute_id  AND c.id_lang=2 AND id_order= '".$q."'
        GROUP BY product_id, kood,nimetus,nr,pl.link_rewrite, kogukogus,asukoht, link
</code>```

How can I fix this problem?

答:
Thanks for your answers, this is really silly but when removing kogukogus from group by and result as this:

```<code>SELECT product_id, product_reference AS kood,product_name AS nimetus,product_quantity AS nr, pl.link_rewrite,psa.quantity as kogukogus,group_concat(ps.product_supplier_reference) as supp_ref, p.location AS asukoht,
         CONCAT(c.link_rewrite,'/',p.id_product,'-',pl.link_rewrite,'.html') link
        FROM ps_order_detail o
        LEFT JOIN ps_product_lang pl on o.product_id = pl.id_product
        LEFT JOIN ps_product p on p.id_product = pl.id_product
        LEFT JOIN ps_stock_available psa on p.id_product = psa.id_product
        LEFT JOIN ps_category_lang c on c.id_category = p.id_category_default
        LEFT JOIN ps_product_supplier ps on p.id_product = ps.id_product
        WHERE pl.id_lang=2 AND c.id_lang=2 AND id_order= '".$q."'
        GROUP BY product_id, kood,nimetus,nr,pl.link_rewrite,asukoht, link
</code>```

I got it working somehow. Thanks you @kiks73, Your code didn't work, BUT when I was trying to add group by to you're code, I realized that the problem was with group by. So the bounty goes to you since no one answered anything serious

Title: Prestashop order products sql

Body:
Where I can find Prestashop SQL query where they display the products that were bought in order.

Like this:

I'm creating a custom page that shows 100 orders in table. and if clicked on order its shows the products that were ordered. I made an sql query:

SELECT product_id, product_reference AS kood,product_name AS nimetus,product_quantity AS nr, pl.link_rewrite,psa.quantity as kogukogus,group_concat(ps.product_supplier_reference) as supp_ref, p.location AS asukoht,
         CONCAT(c.link_rewrite,'/',p.id_product,'-',pl.link_rewrite,'.html') link
        FROM ps_order_detail o
        LEFT JOIN ps_product_lang pl on o.product_id = pl.id_product
        LEFT JOIN ps_product p on p.id_product = pl.id_product
        LEFT JOIN ps_stock_available psa on p.id_product = psa.id_product
        LEFT JOIN ps_category_lang c on c.id_category = p.id_category_default
        LEFT JOIN ps_product_supplier ps on p.id_product = ps.id_product
        WHERE pl.id_lang=2 AND c.id_lang=2 AND id_order= '".$q."'
        GROUP BY product_id, kood,nimetus,nr,pl.link_rewrite, kogukogus,asukoht, link

But when product has attributes it duplicates products.

In this case iButton has two colors black and red(attributes). In this order only one black iButton was bought with quantity of 20, but It shows three rows.

I tried to fix this, but that arised another problems with my sql query, that when it has no attribute it dosen't show anything.

SELECT product_id, product_reference AS kood,product_name AS nimetus,product_quantity AS nr, pl.link_rewrite,psa.quantity as kogukogus,group_concat(ps.product_supplier_reference) as supp_ref, p.location AS asukoht,
         CONCAT(c.link_rewrite,'/',p.id_product,'-',pl.link_rewrite,'.html') link
        FROM ps_order_detail o
        JOIN ps_product_lang pl on o.product_id = pl.id_product
        JOIN ps_product p on p.id_product = pl.id_product
        JOIN ps_stock_available psa on p.id_product = psa.id_product
        JOIN ps_category_lang c on c.id_category = p.id_category_default
        JOIN ps_product_supplier ps on p.id_product = ps.id_product
        LEFT JOIN ps_product_attribute pa on p.id_product=pa.id_product
        WHERE pl.id_lang=2 AND pa.id_product_attribute = psa.id_product_attribute AND pa.id_product_attribute =o.product_attribute_id  AND c.id_lang=2 AND id_order= '".$q."'
        GROUP BY product_id, kood,nimetus,nr,pl.link_rewrite, kogukogus,asukoht, link

How can I fix this problem?

Body:
Thanks for your answers, this is really silly but when removing kogukogus from group by and result as this:

SELECT product_id, product_reference AS kood,product_name AS nimetus,product_quantity AS nr, pl.link_rewrite,psa.quantity as kogukogus,group_concat(ps.product_supplier_reference) as supp_ref, p.location AS asukoht,
         CONCAT(c.link_rewrite,'/',p.id_product,'-',pl.link_rewrite,'.html') link
        FROM ps_order_detail o
        LEFT JOIN ps_product_lang pl on o.product_id = pl.id_product
        LEFT JOIN ps_product p on p.id_product = pl.id_product
        LEFT JOIN ps_stock_available psa on p.id_product = psa.id_product
        LEFT JOIN ps_category_lang c on c.id_category = p.id_category_default
        LEFT JOIN ps_product_supplier ps on p.id_product = ps.id_product
        WHERE pl.id_lang=2 AND c.id_lang=2 AND id_order= '".$q."'
        GROUP BY product_id, kood,nimetus,nr,pl.link_rewrite,asukoht, link

I got it working somehow. Thanks you @kiks73, Your code didn't work, BUT when I was trying to add group by to you're code, I realized that the problem was with group by. So the bounty goes to you since no one answered anything serious


问:
Printing dictionary in a While Loop
I have been looking around to see if anyone has actually done it but couldn't find it so hoping I can get some help here.

```<code>newDict = {'Jan':31, 'Feb':29, 'Mar':31, 'Apr':30, 'May':31, 'Jun':30, 'Jul':31, 'Aug':30}
</code>```

I created this dict and I want to use a while loop to output it this way:

```<code>Jan 31
Feb 29
Mar 31
Apr 30
May 31
Jun 30
Jul 31
Aug 30
</code>```

I am able to do it with a for loop, just curious how it can be done with a while loop.

答:
You can use iterator

Python 2.7

```<code>new_dict = {'Jan':31, 'Feb':29, 'Mar':31, 'Apr':30, 'May':31, 'Jun':30, 'Jul':31, 'Aug':30}
a = iter(new_dict.iteritems())
default = object()

while a:
    elem = next(a, default)
    # This check is to know whether iterator is exhausted or not.
    if elem is default:
        break
    print "{} {}".format(*elem)
</code>```

Python 3

```<code>new_dict = {'Jan':31, 'Feb':29, 'Mar':31, 'Apr':30, 'May':31, 'Jun':30, 'Jul':31, 'Aug':30}
a = iter(new_dict.items())
default = object()

while a:
    elem = next(a, default)
    # This check is to know whether iterator is exhausted or not.
    if elem is default:
        break
    print("{} {}".format(*elem))
</code>```

Title: Printing dictionary in a While Loop

Body:
I have been looking around to see if anyone has actually done it but couldn't find it so hoping I can get some help here.

newDict = {'Jan':31, 'Feb':29, 'Mar':31, 'Apr':30, 'May':31, 'Jun':30, 'Jul':31, 'Aug':30}

I created this dict and I want to use a while loop to output it this way:

Jan 31
Feb 29
Mar 31
Apr 30
May 31
Jun 30
Jul 31
Aug 30

I am able to do it with a for loop, just curious how it can be done with a while loop.

Body:
You can use iterator

Python 2.7

new_dict = {'Jan':31, 'Feb':29, 'Mar':31, 'Apr':30, 'May':31, 'Jun':30, 'Jul':31, 'Aug':30}
a = iter(new_dict.iteritems())
default = object()

while a:
    elem = next(a, default)
    # This check is to know whether iterator is exhausted or not.
    if elem is default:
        break
    print "{} {}".format(*elem)

Python 3

new_dict = {'Jan':31, 'Feb':29, 'Mar':31, 'Apr':30, 'May':31, 'Jun':30, 'Jul':31, 'Aug':30}
a = iter(new_dict.items())
default = object()

while a:
    elem = next(a, default)
    # This check is to know whether iterator is exhausted or not.
    if elem is default:
        break
    print("{} {}".format(*elem))


问:
Importing a database dump -- PSQL
I am trying to import an old .gz database dump into my database using the terminal. It is a Postgresql environment.

This is what i am doing:

psql test < 052710_1.gz

Responce:

ERROR:  syntax error at or near "test"
LINE 1: test
        ^

I also tried:

psql --dbname test < --file 052710_1.gz

psql -d test -U postgres -f 052710_1.gz

And they both gave me the same error.
I have tried using the .exe on the end of psql and it has the same issue.

I am running Postgresql 10.1

答:
For the case of version 10.1

try using the following command

pg_restore -d test < 052710_1.gz

Hope this works.

Title: Importing a database dump -- PSQL


问:
php ini setting not reflecting after upgrading apache2 to mpm_event in ubuntu
I have update my apache2 from mpm_prefork to mpm_event with php5_fpm. After updating this my php.ini in /etc/php5/fpm/php.ini still configuration not work. I have set max_execution_time to 60 but it is not work.

My configuration is

php : PHP 5.5.9-1ubuntu4.22 (fpm-fcgi)

Server OS : Ubuntu 14.04 (64 bit)

apache2 version : Apache/2.4.7 (Ubuntu)

Loaded Configuration File : /etc/php5/fpm/php.ini

答:
You need to reload php-fpm in order for php.ini changes to take effect. Look for something like

```<code>/etc/init.d/php-fpm
</code>```

or

```<code>/etc/init.d/php7.0-fpm
</code>```

and run the reload command like

```<code>sudo /etc/init.d/php7.0-fpm reload
</code>```

You may not require to reload or restart Apache for php.ini changes anymore.

Body:
You need to reload php-fpm in order for php.ini changes to take effect. Look for something like

/etc/init.d/php-fpm

or

/etc/init.d/php7.0-fpm

and run the reload command like

sudo /etc/init.d/php7.0-fpm reload

You may not require to reload or restart Apache for php.ini changes anymore.


问:
pub/sub in angular between lazy loaded modules
I have defined a search service as follows.

```<code>import { Subject } from "rxjs/Subject";

export class SearchTextEmitter extends Subject<string>{
    constructor() {
        super();
    }
    emit(value) { super.next(value); }
}

export class SearchTextService {
   searchText = new SearchTextEmitter();
}
</code>```

I am publishing with emit and subscribing in a child component that is a lazy loaded child of the parent.

If the child component is declared, and included as a module, the search text is correctly propogated downwards.

```<code>export const routes: Routes = [
    {
        path: "",
        redirectTo: "dashboard",
        pathMatch: "full",
    },
    {
        path: "",
        component: FullLayoutComponent,
        data: {
            title: "Home"
        },
        children: [
            {
                path: "dashboard",
                component: ClearingDashboardComponent
...
}
</code>```

When the child module is lazy loaded as follows...

```<code>// instead of
// component: ClearingDashboardComponent

loadChildren: () => new Promise(resolve => {
    (require as any).ensure([],
        require => {
            resolve(require("./dashboard/dashboard.module").DashboardModule);
        },
        "dashboard");
})
</code>```

The events are no longer propogated down.

I suspect that a different service instance is actually being used.

How do I share the pub/sub downwards to the lazy loaded subsidiaries?

答: The problem you are facing here is because you are most likely importing the service on a shared component that is being lazy loaded. The problem is that it will create a new instance of the service and you’ll have unexpected behaviour with the events. You should import the service at a higher level, for instance at the app.module level. This way the service will for sure be a singleton and everything will work as expected :)</p>

Body:
I have defined a search service as follows.

import { Subject } from "rxjs/Subject";

export class SearchTextEmitter extends Subject<string>{
    constructor() {
        super();
    }
    emit(value) { super.next(value); }
}

export class SearchTextService {
   searchText = new SearchTextEmitter();
}

I am publishing with emit and subscribing in a child component that is a lazy loaded child of the parent.

If the child component is declared, and included as a module, the search text is correctly propogated downwards.

export const routes: Routes = [
    {
        path: "",
        redirectTo: "dashboard",
        pathMatch: "full",
    },
    {
        path: "",
        component: FullLayoutComponent,
        data: {
            title: "Home"
        },
        children: [
            {
                path: "dashboard",
                component: ClearingDashboardComponent
...
}

When the child module is lazy loaded as follows...

// instead of
// component: ClearingDashboardComponent

loadChildren: () => new Promise(resolve => {
    (require as any).ensure([],
        require => {
            resolve(require("./dashboard/dashboard.module").DashboardModule);
        },
        "dashboard");
})

The events are no longer propogated down.

I suspect that a different service instance is actually being used.

How do I share the pub/sub downwards to the lazy loaded subsidiaries?


问:
Confusing comparison output
I am confused about the following:

```<code>>>> 1,2 == 1,2
(1, False, 2)
</code>```

The == operator should return only a bool (or at least I thought so).
I would have expected to have, (True, True) assuming that the line would have been processed like a,b = 1,2 but performing comparison instead of assignment. Or, to have an error. But definitely not (1, False, 2).

Can anyone explain what is going on here?

答:
@alec_djinn

comparison operator work If the values of two operands are equal, then the condition becomes true.

you are trying to compare wrong data type 1,2 is not valid.

try '1,2' == '1,2' will give you correct results.

1,2 is not single argument.

Title: Confusing comparison output

Body:
I am confused about the following:

>>> 1,2 == 1,2
(1, False, 2)

The == operator should return only a bool (or at least I thought so).
I would have expected to have, (True, True) assuming that the line would have been processed like a,b = 1,2 but performing comparison instead of assignment. Or, to have an error. But definitely not (1, False, 2).

Can anyone explain what is going on here?


问:
Does xdmp:database-backup-validate also checks for disk size?
I have a scenario where I want to check whether enough disk space is available or not before scheduling full backup in MarkLogic. I am aware that there is a validation phase.Here all backup directories are checked, that they exist and are writable, whether there is disk space available or not ? Is this the API that can externally do the same thing ?</p>

答:
Yes, that is part of what does from my understanding. It is used in the core of the backup code as part of the backup process defined HERE.

If you are wondering what some of the things are that are checked by the function, here is a snippet of status strings returned in one of the elements (I found by analysing the admin code used to register a forest backup). You can see the various errors that may be returned from the tests specifically related to the target backup directory:

```<code>"non-existent"
"in-use"
"corrupt"
"no-access"
"no-space"
"is-install-dir"
"is-data-dir"
"is-public-data-dir"
"bad-path-separator"
</code>```

Body:
Yes, that is part of what does from my understanding. It is used in the core of the backup code as part of the backup process defined HERE.

If you are wondering what some of the things are that are checked by the function, here is a snippet of status strings returned in one of the elements (I found by analysing the admin code used to register a forest backup). You can see the various errors that may be returned from the tests specifically related to the target backup directory:

"non-existent"
"in-use"
"corrupt"
"no-access"
"no-space"
"is-install-dir"
"is-data-dir"
"is-public-data-dir"
"bad-path-separator"


问:
Alamofire/Moya SSL request fails with ATS failed system trust. System Trust failed for X
I'm trying to make a https request with SSL and a self signed certificate through Alamofire with RxMoya, but it keeps giving me ATS failed system trust.
I've searched in many places for solutions, but I can't figure this out yet. I had a .crt certificate and converted to .der and put it on my main bundle Here's the Stacktrace:

```<code>     2017-12-07 13:01:05.918360+0100 SmartBackpackerApp[86030:5429201] ATS failed system trust
2017-12-07 13:01:05.919271+0100 SmartBackpackerApp[86030:5429201] System Trust failed for [4:0x60000016b4c0]
2017-12-07 13:01:05.920438+0100 SmartBackpackerApp[86030:5429201] TIC SSL Trust Error [4:0x60000016b4c0]: 3:0
2017-12-07 13:01:05.921390+0100 SmartBackpackerApp[86030:5429201] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9802)
2017-12-07 13:01:05.922103+0100 SmartBackpackerApp[86030:5429201] Task <F73E31A0-8AC4-40B4-B80C-05182D3E5647>.<1> HTTP load failed (error code: -1200 [3:-9802])
2017-12-07 13:01:05.923528+0100 SmartBackpackerApp[86030:5429201] Task <F73E31A0-8AC4-40B4-B80C-05182D3E5647>.<1> finished with error - code: -1200
Moya_Logger: [07/12/2017 13:01:05] Response: Received empty network response for airlines("Easy Jet").
2017-12-07 13:01:05.945: SBAirlinesService.swift:39 (getAirlineInfo(name:)) -> Event error(underlying(Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." UserInfo={NSURLErrorFailingURLPeerTrustErrorKey=<SecTrustRef: 0x604000307980>, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9802, NSErrorPeerCertificateChainKey=(
    "<cert(0x7fca6a853800) s: api.smartbackpacker.com i: api.smartbackpacker.com>"
), NSUnderlyingError=0x600000656080 {Error Domain=kCFErrorDomainCFNetwork Code=-1200 "(null)" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, kCFStreamPropertySSLPeerTrust=<SecTrustRef: 0x604000307980>, _kCFNetworkCFStreamSSLErrorOriginalValue=-9802, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9802, kCFStreamPropertySSLPeerCertificates=(
    "<cert(0x7fca6a853800) s: api.smartbackpacker.com i: api.smartbackpacker.com>"
)}}, NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made., NSErrorFailingURLKey=https://api.smartbackpackerapp.com/v1/airlines?name=Easy%20Jet, NSErrorFailingURLStringKey=https://api.smartbackpackerapp.com/v1/airlines?name=Easy%20Jet, NSErrorClientCertificateStateKey=0}, nil))
</code>```

Here's the code I'm using to make the request :

```<code>let serverTrustPolicies = ["api.smartbackpackerapp.com": ServerTrustPolicy.pinCertificates(certificates: ServerTrustPolicy.certificates(), validateCertificateChain: false, validateHost: true)]
        self.manager = Manager(configuration: URLSessionConfiguration.default, serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies))
        self.manager.delegate.sessionDidReceiveChallenge = { [weak self] session, challenge in
            var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
            var credential: URLCredential?

            if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust, let trust = challenge.protectionSpace.serverTrust {
                disposition = URLSession.AuthChallengeDisposition.useCredential
                credential = URLCredential(trust: trust)
            } else {
                if challenge.previousFailureCount > 0 {
                    disposition = .cancelAuthenticationChallenge
                } else {
                    credential = self?.manager.session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)

                    if credential != nil {
                        disposition = .useCredential
                    }
                }
            }

            return (disposition, credential)
        }
    }

    provider = RxMoyaProvider<SBApi>(manager: self.manager, plugins: plugins)
    return provider.request(.airlines(name: name))
                    .debug()
                    .filterSuccessfulStatusCodes()
                    .mapObject(SBAirline.self)
                    .asObservable()
</code>```

In my Info.plist file:

```<code><key>NSAppTransportSecurity</key>
    <dict>
        <key>NSExceptionDomains</key>
        <dict>
            <key>https://api.smartbackpackerapp.com</key>
            <dict>
                <key>NSExceptionAllowsInsecureHTTPLoads</key>
                <true/>
                <key>NSExceptionRequiresForwardSecrecy</key>
                <false/>
                <key>NSIncludesSubdomains</key>
                <true/>
                <key>NSTemporaryExceptionMinimumTLSVersion</key>
                <string>TLSv1.1</string>
                <key>NSAllowsArbitraryLoads</key>
                <true/>
            </dict>
        </dict>
    </dict>
</code>```

答:
OMG, I had the wrong domain on the Info.plist, it is without the https://

Lost a few hours with this. :(

Body:
I'm trying to make a https request with SSL and a self signed certificate through Alamofire with RxMoya, but it keeps giving me ATS failed system trust.
I've searched in many places for solutions, but I can't figure this out yet. I had a .crt certificate and converted to .der and put it on my main bundle Here's the Stacktrace:

     2017-12-07 13:01:05.918360+0100 SmartBackpackerApp[86030:5429201] ATS failed system trust
2017-12-07 13:01:05.919271+0100 SmartBackpackerApp[86030:5429201] System Trust failed for [4:0x60000016b4c0]
2017-12-07 13:01:05.920438+0100 SmartBackpackerApp[86030:5429201] TIC SSL Trust Error [4:0x60000016b4c0]: 3:0
2017-12-07 13:01:05.921390+0100 SmartBackpackerApp[86030:5429201] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9802)
2017-12-07 13:01:05.922103+0100 SmartBackpackerApp[86030:5429201] Task <F73E31A0-8AC4-40B4-B80C-05182D3E5647>.<1> HTTP load failed (error code: -1200 [3:-9802])
2017-12-07 13:01:05.923528+0100 SmartBackpackerApp[86030:5429201] Task <F73E31A0-8AC4-40B4-B80C-05182D3E5647>.<1> finished with error - code: -1200
Moya_Logger: [07/12/2017 13:01:05] Response: Received empty network response for airlines("Easy Jet").
2017-12-07 13:01:05.945: SBAirlinesService.swift:39 (getAirlineInfo(name:)) -> Event error(underlying(Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." UserInfo={NSURLErrorFailingURLPeerTrustErrorKey=<SecTrustRef: 0x604000307980>, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9802, NSErrorPeerCertificateChainKey=(
    "<cert(0x7fca6a853800) s: api.smartbackpacker.com i: api.smartbackpacker.com>"
), NSUnderlyingError=0x600000656080 {Error Domain=kCFErrorDomainCFNetwork Code=-1200 "(null)" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, kCFStreamPropertySSLPeerTrust=<SecTrustRef: 0x604000307980>, _kCFNetworkCFStreamSSLErrorOriginalValue=-9802, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9802, kCFStreamPropertySSLPeerCertificates=(
    "<cert(0x7fca6a853800) s: api.smartbackpacker.com i: api.smartbackpacker.com>"
)}}, NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made., NSErrorFailingURLKey=https://api.smartbackpackerapp.com/v1/airlines?name=Easy%20Jet, NSErrorFailingURLStringKey=https://api.smartbackpackerapp.com/v1/airlines?name=Easy%20Jet, NSErrorClientCertificateStateKey=0}, nil))

Here's the code I'm using to make the request :

let serverTrustPolicies = ["api.smartbackpackerapp.com": ServerTrustPolicy.pinCertificates(certificates: ServerTrustPolicy.certificates(), validateCertificateChain: false, validateHost: true)]
        self.manager = Manager(configuration: URLSessionConfiguration.default, serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies))
        self.manager.delegate.sessionDidReceiveChallenge = { [weak self] session, challenge in
            var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
            var credential: URLCredential?

            if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust, let trust = challenge.protectionSpace.serverTrust {
                disposition = URLSession.AuthChallengeDisposition.useCredential
                credential = URLCredential(trust: trust)
            } else {
                if challenge.previousFailureCount > 0 {
                    disposition = .cancelAuthenticationChallenge
                } else {
                    credential = self?.manager.session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)

                    if credential != nil {
                        disposition = .useCredential
                    }
                }
            }

            return (disposition, credential)
        }
    }

    provider = RxMoyaProvider<SBApi>(manager: self.manager, plugins: plugins)
    return provider.request(.airlines(name: name))
                    .debug()
                    .filterSuccessfulStatusCodes()
                    .mapObject(SBAirline.self)
                    .asObservable()

In my Info.plist file:

<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSExceptionDomains</key>
        <dict>
            <key>https://api.smartbackpackerapp.com</key>
            <dict>
                <key>NSExceptionAllowsInsecureHTTPLoads</key>
                <true/>
                <key>NSExceptionRequiresForwardSecrecy</key>
                <false/>
                <key>NSIncludesSubdomains</key>
                <true/>
                <key>NSTemporaryExceptionMinimumTLSVersion</key>
                <string>TLSv1.1</string>
                <key>NSAllowsArbitraryLoads</key>
                <true/>
            </dict>
        </dict>
    </dict>


问:
ERROR 1288: The target table is not updatable in MySQL trigger
I am trying to run a small trigger with following query in Mysql :

```<code>create trigger sample_trigger after delete on my_network
  for each row
  begin
      update (select active from my_network_ref where id=old.rid limit 1) vnetr set vnetr.active=0;
  end;
</code>```

After running these trigger in MySQL Workbench , i ma getting following error

```<code>Operation failed: There was an error while applying the SQL script to the database.
ERROR 1288: The target table vnetr of the UPDATE is not updatable
SQL Statement:
CREATE DEFINER = CURRENT_USER TRIGGER `mam_db`.`sample_trigger ` AFTER DELETE ON `my_network` FOR EACH ROW
BEGIN
 update (select active from my_network_ref where id=old.rid limit 1) vnetr set vnetr.active=0;
END
</code>```

Any syntax error or structural problems ? Please help

答:
In MySQL, you cannot update a subquery.  Instead:

```<code>update my_network_ref
    set active = 0
where id = old.rid
limit 1;
</code>```

Normally, you would use order by when using limit.

Body:
I am trying to run a small trigger with following query in Mysql :

create trigger sample_trigger after delete on my_network
  for each row
  begin
      update (select active from my_network_ref where id=old.rid limit 1) vnetr set vnetr.active=0;
  end;

After running these trigger in MySQL Workbench , i ma getting following error

Operation failed: There was an error while applying the SQL script to the database.
ERROR 1288: The target table vnetr of the UPDATE is not updatable
SQL Statement:
CREATE DEFINER = CURRENT_USER TRIGGER `mam_db`.`sample_trigger ` AFTER DELETE ON `my_network` FOR EACH ROW
BEGIN
 update (select active from my_network_ref where id=old.rid limit 1) vnetr set vnetr.active=0;
END

Any syntax error or structural problems ? Please help

Body:
In MySQL, you cannot update a subquery.  Instead:

update my_network_ref
    set active = 0
where id = old.rid
limit 1;

Normally, you would use order by when using limit.


问:
How do I delete file that I have uploaded on Cloudinary using Jquery?
Can someone advise me how to delete a file in Cloudinary using Jquery?

I can't find any sample snippets to get started.

答:
There good documentation on deleting client side uploaded images.

There are a few caveats to note though:

This does not work with unsigned uploads.

You will have to set return_delete_token: 1 in the options during your file upload, then pass the returned image's delete_token to the cloudinary.delete_by_token(delete_token) method.

From the documentation, you can do this over REST like so: curl https://api.cloudinary.com/v1_1/demo/delete_by_token -X POST --data 'token=delete_token'


问:
UITableView Reload Rows unnaturally jerking the TableView in iOS 11.2
Strange issue arrived after updating new XCODE 9.2 with iOS 11.2, by calling

```<code>let indexPath = IndexPath(item: 0, section: 1)
self.tableViewHome.reloadRows(at: [indexPath], with: .none)
</code>```

It causes unnecessary jerking the whole TableView, Prior it was very fine with these code.

GIF Image for iOS 11.2

GIF Image for iOS 11.1

How to stop this Jerking, I have to reload only one cell in the tableview among two cells.

Any help will be appreciated.

Thanks

答:
Finally I got the answer, I have to use an delegate method of UITableView i.e

```<code>    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {

            return UITableViewAutomaticDimension
    }
</code>```

After putting this method by returning UITableViewAutomaticDimension it stop that jerking for iOS 11.2.

Body:
Strange issue arrived after updating new XCODE 9.2 with iOS 11.2, by calling

let indexPath = IndexPath(item: 0, section: 1)
self.tableViewHome.reloadRows(at: [indexPath], with: .none)

It causes unnecessary jerking the whole TableView, Prior it was very fine with these code.

GIF Image for iOS 11.2

GIF Image for iOS 11.1

How to stop this Jerking, I have to reload only one cell in the tableview among two cells.

Any help will be appreciated.

Thanks

Body:
Finally I got the answer, I have to use an delegate method of UITableView i.e

    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {

            return UITableViewAutomaticDimension
    }

After putting this method by returning UITableViewAutomaticDimension it stop that jerking for iOS 11.2.


问:
mat-checkbox check only if condition is true
I have a user table list with mat-checkbox. When mat-checkbox is clicked, the checkbox should be checked only if a certain condition is true.

Here in this code, I am trying to have checkbox checked only for id=2. But as you can see, initially when checkbox of 2 is clicked, it doesn't get checked even though 2 is added to array of elements which should be checked.

On the other hand, when checkbox of 1,3 or 4 is clicked, they get checked.

component.html

```<code><tbody>
    <tr *ngFor="let user of users; let in = index">
            <td>
                <mat-checkbox [ngModel]="canbeChecked(user.id)" (click)="userSelectClick(user.id)"></mat-checkbox>
            </td>
    </tr>
</tbody>
</code>```

component.ts

```<code>export class AppComponent {

  users = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }];
  checked: boolean = true
  constructor() { }
  selected: any = [];

  canbeChecked(id): boolean {
    console.log("check " + id)
    console.log(this.selected)
    return this.selected.includes(id);

  }

  userSelectClick(id) {

    if (!this.selected.includes(id)) {
      if (id == 2)
        this.selected.push(id);
      console.log("select " + id)
      console.log(this.selected)
    }
    else {
      this.selected = this.selected.filter(item => item !== id)
    }

  }

}
</code>```

Working code: https://stackblitz.com/edit/mat-checkbox-conditional

答:
I'm novice over stackoverflow.You can try change event for that stuff.

component.ts

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'material-app',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css']
})
export class AppComponent {
user_checked = false;
  users = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }];
  checked: boolean = false;
  constructor() { }
  selected: any = [];

  canbeChecked(id): boolean {
    console.log("check " + id)
    console.log(this.selected)
    return this.selected.includes(id);

  }

  userSelectClick(event,id) {
    if (!this.selected.includes(id)) {
      if (id == 2)
        this.selected.push(id);
      console.log("selecrted iDs " + id)
      console.log(this.selected)
    }
    else {
      this.selected = this.selected.filter(item => item !== id)
    }
  }

}

/**
 * Copyright Google LLC All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://angular.io/license
 */
</code>```

component.html

                        Checkboxes

Body:
I have a user table list with mat-checkbox. When mat-checkbox is clicked, the checkbox should be checked only if a certain condition is true.

Here in this code, I am trying to have checkbox checked only for id=2. But as you can see, initially when checkbox of 2 is clicked, it doesn't get checked even though 2 is added to array of elements which should be checked.

On the other hand, when checkbox of 1,3 or 4 is clicked, they get checked.

component.html

                <mat-checkbox [ngModel]="canbeChecked(user.id)" (click)="userSelectClick(user.id)"></mat-checkbox>

component.ts

export class AppComponent {

  users = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }];
  checked: boolean = true
  constructor() { }
  selected: any = [];

  canbeChecked(id): boolean {
    console.log("check " + id)
    console.log(this.selected)
    return this.selected.includes(id);

  }

  userSelectClick(id) {

    if (!this.selected.includes(id)) {
      if (id == 2)
        this.selected.push(id);
      console.log("select " + id)
      console.log(this.selected)
    }
    else {
      this.selected = this.selected.filter(item => item !== id)
    }

  }

}

Working code: https://stackblitz.com/edit/mat-checkbox-conditional

Body:
I'm novice over stackoverflow.You can try change event for that stuff.

component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'material-app',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css']
})
export class AppComponent {
user_checked = false;
  users = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }];
  checked: boolean = false;
  constructor() { }
  selected: any = [];

  canbeChecked(id): boolean {
    console.log("check " + id)
    console.log(this.selected)
    return this.selected.includes(id);

  }

  userSelectClick(event,id) {
    if (!this.selected.includes(id)) {
      if (id == 2)
        this.selected.push(id);
      console.log("selecrted iDs " + id)
      console.log(this.selected)
    }
    else {
      this.selected = this.selected.filter(item => item !== id)
    }
  }

}

/**
 * Copyright Google LLC All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://angular.io/license
 */

component.html

                        Checkboxes


问:
Styling a child of a shadow root in Shadow DOM
I'm trying to style a child element of a shadow DOM root.

This defines a custom element called element-el, which have a span class-named 'x' with the letter x in it, which I want, for the state of the matter, to be red.

```<code>class El extends HTMLElement {
    constructor() {
        super();
        var shadow = this.attachShadow({mode:'open'});
        shadow.innerHTML = '<span class="x">X</span>';
    }
}
customElements.define ('element-el',El);
</code>```

I've tried those CSS styles:

```<code>element-el::slotted(.x) {
  color:red;
}
element-el::host .x {
  color:red;
}
element-el:host .x {
  color:red;
}
element-el::shadow .x {
  color:red;
}
element-el /deep/ .x {
  color: red;
}
element-el::content .x {
  color:red;
}
</code>```

The X does not become red.
I'm using Chrome 56, which is supposed to support this...

I want to style it without putting a style element inside the shadow DOM.

Here is a codepen:
http://codepen.io/anon/pen/OpRLVG?editors=1111

EDIT:

This article suggests that it is possible to style shadow children from an external CSS file -- are they simply wrong?

答:
This may help someone else in a similar situation.

In my case I have:

```<code><svg class="icon">
    <use xlink:href="#my-icon"></use>
</svg>
</code>```

and to access the rendered icon in #shadow-root, I use:

```<code>.icon use {
  fill: #f80;
}
</code>```

Body:
I'm trying to style a child element of a shadow DOM root.

This defines a custom element called element-el, which have a span class-named 'x' with the letter x in it, which I want, for the state of the matter, to be red.

class El extends HTMLElement {
    constructor() {
        super();
        var shadow = this.attachShadow({mode:'open'});
        shadow.innerHTML = 'X';
    }
}
customElements.define ('element-el',El);

I've tried those CSS styles:

element-el::slotted(.x) {
  color:red;
}
element-el::host .x {
  color:red;
}
element-el:host .x {
  color:red;
}
element-el::shadow .x {
  color:red;
}
element-el /deep/ .x {
  color: red;
}
element-el::content .x {
  color:red;
}

The X does not become red.
I'm using Chrome 56, which is supposed to support this...

I want to style it without putting a style element inside the shadow DOM.

Here is a codepen:
http://codepen.io/anon/pen/OpRLVG?editors=1111

EDIT:

This article suggests that it is possible to style shadow children from an external CSS file -- are they simply wrong?

Body:
This may help someone else in a similar situation.

In my case I have:

<svg class="icon">
    <use xlink:href="#my-icon"></use>
</svg>

and to access the rendered icon in #shadow-root, I use:

.icon use {
  fill: #f80;
}


问:
Convert String of anyformat into dd-mm-yy hh:mm:ss in R
I am reading a date value from csv file.So the format will vary according to the date format of csv. How can I convert any date string to dd-mm-yyy  HH:mm:ss ?

EDIT :

The input format are :

```<code>dd/mm/yyyy HH:mm:ss
dd/mm/yyyy
dd-mm-yyyy HH:mm:ss
dd-mm-yyyy

mm-dd-yyyy HH:mm:ss
mm-dd-yyyy
mm/dd/yyyy

yyyy-mm-dd HH:mm:ss
yyyy-mm-dd
</code>```

I need to convert  all these formats to dd-mm-yyyy HH:mm:ss

答:
Try "lubridate" package. Here A_1.csv has both formats.</p>

```<code>Data <-read.csv("Al_1.csv") # import data
str(Data)
a = NULL # create a null object
library(lubridate)
a$Date <- mdy_hm(Data$Date) # store dd/mm/yyyy HH:mm:ss objects here
a$Price <- Data$Price # get respective values(it could by any other column)
b = NULL
b$Date <- mdy(Data$Date)
b$Price <- Data$Price

a <- as.data.frame(a)
b <- as.data.frame(b)

a <- a[is.na(a$Date)==FALSE,] # those with NA had diffrent formats remove it
b <- b[is.na(b$Date)==FALSE,]

b$Date <- as.POSIXlt(b$Date)# change your other format also to UTC

x <- rbind(a,b)
str(x)
x <- ts(x)
</code>```

Body:
I am reading a date value from csv file.So the format will vary according to the date format of csv. How can I convert any date string to dd-mm-yyy  HH:mm:ss ?

EDIT :

The input format are :

dd/mm/yyyy HH:mm:ss
dd/mm/yyyy
dd-mm-yyyy HH:mm:ss
dd-mm-yyyy

mm-dd-yyyy HH:mm:ss
mm-dd-yyyy
mm/dd/yyyy

yyyy-mm-dd HH:mm:ss
yyyy-mm-dd

I need to convert  all these formats to dd-mm-yyyy HH:mm:ss

Body:
Try "lubridate" package. Here A_1.csv has both formats.

Data <-read.csv("Al_1.csv") # import data
str(Data)
a = NULL # create a null object
library(lubridate)
a$Date <- mdy_hm(Data$Date) # store dd/mm/yyyy HH:mm:ss objects here
a$Price <- Data$Price # get respective values(it could by any other column)
b = NULL
b$Date <- mdy(Data$Date)
b$Price <- Data$Price

a <- as.data.frame(a)
b <- as.data.frame(b)

a <- a[is.na(a$Date)==FALSE,] # those with NA had diffrent formats remove it
b <- b[is.na(b$Date)==FALSE,]

b$Date <- as.POSIXlt(b$Date)# change your other format also to UTC

x <- rbind(a,b)
str(x)
x <- ts(x)


问:
How to print a UIWebView via UIActivityViewController?
I have a view controller containing a UIWebView and a toolbar with an action/share button. This initializes and presents a UIActivityViewController object. Depending on whether I supply the activityItems parameter with either the web view's URL or the URL's corresponding absoluteString, different actions are offered, but the Print option is never shown (nor offered in the "more" section).

I do know how to print the web view contents explicitly using UIPrintInfo and UIPrintInteractionController, but that would be a separate toolbar button whereas I want to simply include the system's Print option into the activity button row. I assume printing a web view does not need any explicit coding.

What can I do?

答:
You can create Custom Activity For UIActivityCotnroller like this,

```<code> import UIKit

protocol CustomActivityDelegate : NSObjectProtocol
{
    func performActionCompletion(actvity: CustomActivity)
}

class CustomActivity: UIActivity {

    var delegate: CustomActivityDelegate?

    override class var activityCategory: UIActivityCategory {
        return .action
    }

    override var activityType: UIActivityType? {
        guard let bundleId = Bundle.main.bundleIdentifier else {return nil}
        return UIActivityType(rawValue: bundleId + "\(self.classForCoder)")
    }

    override var activityTitle: String? {
        return "You title"
    }

    override var activityImage: UIImage? {
        return <Your activity image >
    }

    override func canPerform(withActivityItems activityItems: [Any]) -> Bool {
        return true
    }

    override func prepare(withActivityItems activityItems: [Any]) {
        //
    }

    override func perform() {
        self.delegate?.performActionCompletion(actvity: self)
        activityDidFinish(true)
    }
}
</code>```

You can initialize this activity some thing like this

```<code>let customActivity = CustomActivity()
customActivity.delegate = self
</code>```

And you can add this custom activity while preparing UIActivityController

```<code>let activityViewController : UIActivityViewController = UIActivityViewController(activityItems: [customActivity], applicationActivities: nil)
</code>```

and you will also need to implement the call back method

```<code>func performActionCompletion(actvity: CustomActivity)
{
   //Perform you task
}
</code>```

Note : This is just pseudo code, might contain error or syntax problems

Body:
You can create Custom Activity For UIActivityCotnroller like this,

 import UIKit

protocol CustomActivityDelegate : NSObjectProtocol
{
    func performActionCompletion(actvity: CustomActivity)
}

class CustomActivity: UIActivity {

    var delegate: CustomActivityDelegate?

    override class var activityCategory: UIActivityCategory {
        return .action
    }

    override var activityType: UIActivityType? {
        guard let bundleId = Bundle.main.bundleIdentifier else {return nil}
        return UIActivityType(rawValue: bundleId + "\(self.classForCoder)")
    }

    override var activityTitle: String? {
        return "You title"
    }

    override var activityImage: UIImage? {
        return <Your activity image >
    }

    override func canPerform(withActivityItems activityItems: [Any]) -> Bool {
        return true
    }

    override func prepare(withActivityItems activityItems: [Any]) {
        //
    }

    override func perform() {
        self.delegate?.performActionCompletion(actvity: self)
        activityDidFinish(true)
    }
}

You can initialize this activity some thing like this

let customActivity = CustomActivity()
customActivity.delegate = self

And you can add this custom activity while preparing UIActivityController

let activityViewController : UIActivityViewController = UIActivityViewController(activityItems: [customActivity], applicationActivities: nil)

and you will also need to implement the call back method

func performActionCompletion(actvity: CustomActivity)
{
   //Perform you task
}

Note : This is just pseudo code, might contain error or syntax problems