问:
Python | Pandas DataFrame: Advanced Slicing/GroupBy
I have been struggling with a pandas quest for a while now and maybe someone can shed some new light into this problem :)

Consider de following pandas dataframe, df:

```<code>Year Month Task TaskID TaskClass TaskClassID SomeValue
2019 11    A    1      X         10          6.58
2019 11    A    1      Y         20          1.58
2019 11    B    2      X         10          6.58
2019 11    B    2      Y         20          1.58
</code>```

objective: group by Task in a way that each Task gets a unique TaskClass observation (which Tasks gets a TaskClass is not important for this problem, can be considered random).
like this:

```<code>Year Month Task TaskID TaskClass TaskClassID SomeValue
2019 11    A    1      X         10          6.58
2019 11    B    2      Y         20          1.58
</code>```

or, for instance, this:

```<code>Year Month Task TaskID TaskClass TaskClassID SomeValue
2019 11    A    1      Y         20          1.58
2019 11    B    2      X         10          6.58
</code>```

other constraints the final problema will have thousands of tasks and, more important, can have more TaskClass per Task, something like this:

```<code>Year Month Task TaskID TaskClass TaskClassID SomeValue
2019 11    A    1      X         10          6.58
2019 11    A    1      Y         20          1.58
2019 11    A    1      Z         30          1.00
2019 11    A    1      W         40          0.25
2019 11    B    2      X         10          6.58
2019 11    B    2      Y         20          1.58
2019 11    B    2      Z         30          1.00
2019 11    B    2      W         40          0.25
</code>```

Thank you all, in advance.

答:
Why not use drop duplicates?

More here: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop_duplicates.html

Assume a dataframe like so:

```<code> data = pd.DataFrame({
        'Task Class': ['x', 'x', 'y', 'z', 'y', 'z'],
        'Value' : [1, 2, 3, 4, 5, 6],
    })

  Task Class  Value
0          x      1
1          x      2
2          y      3
3          z      4
4          y      5
5          z      6
</code>```

We can do:

```<code>data.drop_duplicates(['Task Class'], inplace=True)
</code>```

And get:

```<code>  Task Class  Value
0          x      1
2          y      3
3          z      4
</code>```

Body:
I have been struggling with a pandas quest for a while now and maybe someone can shed some new light into this problem :)

Consider de following pandas dataframe, df:

Year Month Task TaskID TaskClass TaskClassID SomeValue
2019 11    A    1      X         10          6.58
2019 11    A    1      Y         20          1.58
2019 11    B    2      X         10          6.58
2019 11    B    2      Y         20          1.58

objective: group by Task in a way that each Task gets a unique TaskClass observation (which Tasks gets a TaskClass is not important for this problem, can be considered random).
like this:

Year Month Task TaskID TaskClass TaskClassID SomeValue
2019 11    A    1      X         10          6.58
2019 11    B    2      Y         20          1.58

or, for instance, this:

Year Month Task TaskID TaskClass TaskClassID SomeValue
2019 11    A    1      Y         20          1.58
2019 11    B    2      X         10          6.58

other constraints the final problema will have thousands of tasks and, more important, can have more TaskClass per Task, something like this:

Year Month Task TaskID TaskClass TaskClassID SomeValue
2019 11    A    1      X         10          6.58
2019 11    A    1      Y         20          1.58
2019 11    A    1      Z         30          1.00
2019 11    A    1      W         40          0.25
2019 11    B    2      X         10          6.58
2019 11    B    2      Y         20          1.58
2019 11    B    2      Z         30          1.00
2019 11    B    2      W         40          0.25

Thank you all, in advance.

Body:
Why not use drop duplicates?

More here: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop_duplicates.html

Assume a dataframe like so:

 data = pd.DataFrame({
        'Task Class': ['x', 'x', 'y', 'z', 'y', 'z'],
        'Value' : [1, 2, 3, 4, 5, 6],
    })

  Task Class  Value
0          x      1
1          x      2
2          y      3
3          z      4
4          y      5
5          z      6

We can do:

data.drop_duplicates(['Task Class'], inplace=True)

And get:

  Task Class  Value
0          x      1
2          y      3
3          z      4


来源: stackexchange

问:
Is there a way to make a "reusable snapshot" of a program?
Here's the situation: I am working on a relatively big C++ program (in Linux). This program can be separated in two parts. Part A is just a bunch of precomputations based in some data that remains the same over time that builds a pretty complex and big data structure. The problem is that part A takes too much time (around a minute), and you can assume that it cannot be significantly optimized further. Part B, which goes right after part A, is basically some queries on the data loaded in part A.

So, here's what I want to do: since the data structure built in part A is always the same, wouldn't it be nice to have a "snapshot" of it, and so, every time you load the program you can just retrieve the data from the snapshot very quickly and just jump right to B?

And here's the question: Is there a way to do that?

答:
What you describe is basically "checkpointing" in HPC: you designate a chunk of memory that can be restored quickly if the program is restarted, without investing significant time in saving/loading this data.

There are many libraries or checkpointing out there, but I have used Ken in the past to great effect.
What this library does is create a virtual memory mapping at a fixed memory location, together with a mechanism for automatically capturing this memory to disk and reloading it.

When the program is restarted, you simply map the memory again and check if it was initialized or not.
Thus, your startup time is reduced to virtually nothing (the time to memory map the file and load some chunks from disk as you need them).

You did not present any code so I cannot give you concrete advice, but you will need to ensure that all memory allocations for the expensive piece are made inside of Ken-managed memory, for example by implementing your own memory allocator backed by the Ken-managed memory, by passing a custom allocator to all STL data structures, or simply convincing your memory management library of choice to allocate memory in the Ken memory. For an example of the last option, see jemalloc's arena.create and thread.arena options.

ContentLicense: CC BY-SA 4.0


问:
sql server 2005 'update from' query
I'm trying to update a table based upon the user id from another table.  I've come across the Update from syntax but I'm struggling to write my query correctly.

The below code should show you what I'm attempting to do.  When i run it i get 0 rows affected.

```<code>    update jared_test
       set user_count  = 1
      from new_user nuj
inner join (select us.userID
              from users us
             where us.email = 'j@j.co.uk') u on nuj.userid = u.userid
</code>```

/********EDIT*******************\

I discovered there was a problem with my Cursor loop that was preventing this from working, so this does actually work.  However I'd be interested if a where is better than a from in this instance for optimisations.

答:
I'm not 100% on why the other solutions are using a subselect which will perform slower than a regular join most often.  Though taos subselect is essentially a regular join just written interestingly.</p>

```<code>update aliasName
set aliasName.user_count =1
from new_user aliasName
inner join users u on aliasName.userid = u.userid
where email = 'j@j.co.uk'
</code>```

ContentLicense: CC BY-SA 3.0

Title: sql server 2005 'update from' query

Body:
I'm trying to update a table based upon the user id from another table.  I've come across the Update from syntax but I'm struggling to write my query correctly.

The below code should show you what I'm attempting to do.  When i run it i get 0 rows affected.

    update jared_test
       set user_count  = 1
      from new_user nuj
inner join (select us.userID
              from users us
             where us.email = 'j@j.co.uk') u on nuj.userid = u.userid

/********EDIT*******************\

I discovered there was a problem with my Cursor loop that was preventing this from working, so this does actually work.  However I'd be interested if a where is better than a from in this instance for optimisations.

Body:
I'm not 100% on why the other solutions are using a subselect which will perform slower than a regular join most often.  Though taos subselect is essentially a regular join just written interestingly.

update aliasName
set aliasName.user_count =1
from new_user aliasName
inner join users u on aliasName.userid = u.userid
where email = 'j@j.co.uk'


问:
Declaring points in array for drawing polygon in VB 2019
Is there a way to declare a constant array where i can declare the points for drawing a polygon?

Something along the lines like:

```<code>Dim myPoints As Point() = {{10,10}, {12,12}, {13,13}, {14,14}, {15,15}}
...
...
...
myGraphics.DrawPolygon(myPen, myPoints)
</code>```

The idea is hardcoding the points using the least posible code

答:
Do you mean something like this? </p>

```<code>        Dim NewPoint As Func(Of Integer, Integer, Point) = Function(left As Integer, top As Integer)
                                                               Return New Point(left, top)
                                                           End Function
        Dim myPoints As List(Of Point) = New List(Of Point) From {NewPoint(50, 50), NewPoint(80, 50), NewPoint(110, 80), NewPoint(80, 110), NewPoint(50, 110), NewPoint(20, 80)}
        myGraphics.DrawPolygon(Pens.Red, myPoints.ToArray)
</code>```

Body:
Is there a way to declare a constant array where i can declare the points for drawing a polygon?

Something along the lines like:

Dim myPoints As Point() = {{10,10}, {12,12}, {13,13}, {14,14}, {15,15}}
...
...
...
myGraphics.DrawPolygon(myPen, myPoints)

The idea is hardcoding the points using the least posible code

Body:
Do you mean something like this?

        Dim NewPoint As Func(Of Integer, Integer, Point) = Function(left As Integer, top As Integer)
                                                               Return New Point(left, top)
                                                           End Function
        Dim myPoints As List(Of Point) = New List(Of Point) From {NewPoint(50, 50), NewPoint(80, 50), NewPoint(110, 80), NewPoint(80, 110), NewPoint(50, 110), NewPoint(20, 80)}
        myGraphics.DrawPolygon(Pens.Red, myPoints.ToArray)


问:
Collecting comments from Reddit, outputting to CSV file
I'm trying to scrape comments from a certain submission on Reddit and output them to a CSV file.

```<code>import praw
import csv

reddit = praw.Reddit(client_id='ClientID', client_secret='ClientSecret', user_agent='UserAgent')

Submission = reddit.submission(id="SubmissionID")

with open('Reddit.csv', 'w') as csvfile:
    for comment in submission.comments:
        csvfile.write(comment.body)
</code>```

The problem is that for each cell the comments seem to be randomly split up. I want each comment in its own cell. Any ideas on how to achieve this?

答:
To write a CSV file in Python, use the csv module, specifically csv.writer(). You import this module at the top of your code, but you never use it.

Using this in your code, this looks like:

with open('Reddit.csv', 'w') as csvfile:
    comment_writer = csv.writer(csvfile)
    for comment in submission.comments:
        comment_writer.writerow([comment.body])
```

<p>Here, we use <code>csv.writer()</code> to create a CSV writer from the file that we've opened, and we call it <code>comment_writer</code>. Then, for each comment, we write another row to the CSV file. The row is represented as a list. Since we only have one piece of information to write on each row, the list contains just one item. The row is <code>[comment.body]</code>.</p>

<p>The <code>csv</code> module takes care of making sure that values with new lines, commas, or other special characters are properly formatted as CSV values.</p>

<hr>

<p>Note that, for some submissions with many comments, your PRAW code might raise an exception along the lines of <code>'MoreComments' object has no attribute 'body'</code>. The PRAW docs discuss this, and I encourage you to read that to learn more, but know that we can avoid this happening in code by further modifying our loop:</p>

<pre class="lang-py prettyprint-override"><code>from praw.models import Comment

# ...

with open('Reddit.csv', 'w') as csvfile:
    comment_writer = csv.writer(csvfile)
    for comment in submission.comments:
        if isinstance(comment, Comment):
            comment_writer.writerow([comment.body])
</code>```

Also, your code only gets the top level comments of a submission. If you're interested in more, see this question, which is about how to get more than just top-level comments from a submission.

Body:
I'm trying to scrape comments from a certain submission on Reddit and output them to a CSV file.

import praw
import csv

reddit = praw.Reddit(client_id='ClientID', client_secret='ClientSecret', user_agent='UserAgent')

Submission = reddit.submission(id="SubmissionID")

with open('Reddit.csv', 'w') as csvfile:
    for comment in submission.comments:
        csvfile.write(comment.body)

The problem is that for each cell the comments seem to be randomly split up. I want each comment in its own cell. Any ideas on how to achieve this?

Body:
To write a CSV file in Python, use the csv module, specifically csv.writer(). You import this module at the top of your code, but you never use it.

Using this in your code, this looks like:

with open('Reddit.csv', 'w') as csvfile:
    comment_writer = csv.writer(csvfile)
    for comment in submission.comments:
        comment_writer.writerow([comment.body])

Here, we use csv.writer() to create a CSV writer from the file that we've opened, and we call it comment_writer. Then, for each comment, we write another row to the CSV file. The row is represented as a list. Since we only have one piece of information to write on each row, the list contains just one item. The row is [comment.body].

The csv module takes care of making sure that values with new lines, commas, or other special characters are properly formatted as CSV values.

Note that, for some submissions with many comments, your PRAW code might raise an exception along the lines of 'MoreComments' object has no attribute 'body'. The PRAW docs discuss this, and I encourage you to read that to learn more, but know that we can avoid this happening in code by further modifying our loop:

from praw.models import Comment

# ...

with open('Reddit.csv', 'w') as csvfile:
    comment_writer = csv.writer(csvfile)
    for comment in submission.comments:
        if isinstance(comment, Comment):
            comment_writer.writerow([comment.body])

Also, your code only gets the top level comments of a submission. If you're interested in more, see this question, which is about how to get more than just top-level comments from a submission.


问:
Combine shell command lines in snakemake
I would like to combine two command lines as one single to avoid the intermediate files.

```<code>workdir: "/path/to/workdir/"

rule all:
    input:
        "my.filtered.vcf.gz"

rule bedtools:
    input:
        invcf="/path/to/my.vcf.gz",
        bedgz="/path/to/my.bed.gz"
    output:
        outvcf="my.filtered.vcf.gz"
    shell:
        "/Tools/bedtools2/bin/bedtools intersect -a {input.invcf} -b {input.bedgz} -header -wa |"
        "/Tools/bcftools/bcftools annotate -c CHROM,FROM,TO,GENE -h <(echo '##INFO=<ID=GENE,Number=1,Type=String,Description="Gene name">') > {output.outvcf}"
</code>```

I am getting invalid syntax error. I would appreciate if you could explain how to combine multiple shell lines in snakemake.

答:
Escaping the double quotes is the problem, but to add a little more on formatting and pipes.

I prefer the syntax of wrapping each line in " so that the lines can be spaced better:

```<code>rule bedtools:
    input:
        invcf="/path/to/my.vcf.gz",
        bedgz="/path/to/my.bed.gz"
    output:
        outvcf="my.filtered.vcf.gz"
    shell:
        "/Tools/bedtools2/bin/bedtools "
           "intersect "
           "-a {input.invcf} "
           "-b {input.bedgz} "
           "-header -wa "
        "| /Tools/bcftools/bcftools "
           "annotate "
           "-c CHROM,FROM,TO,GENE "
           "-h <(echo '##INFO=<ID=GENE,Number=1,Type=String,Description=\"Gene name\">') "
        "> {output.outvcf}"
</code>```

I find that clearer to see each argument and easier to change by moving lines around.  But note that the trailing space of each line is required and you have to use an explicit newline, \n, if you want a separate command.  When the prompt is printed the output is nicely formated.  With the """ syntax you have to escape each newline with \ at the end and spaces at the start of the line are retained in printing.

If you have lot's of pipe work to do, check out the pipe flag.  You write your first step as a rule and snakemake produces a named pipe between the rules, submitting them as a group:

```<code>rule bedtools_intersect:
    input:
        invcf="/path/to/my.vcf.gz",
        bedgz="/path/to/my.bed.gz"
    output:
        outvcf=pipe("my.intersected.vcf.gz")
    shell:
        "/Tools/bedtools2/bin/bedtools "
           "intersect "
           "-a {input.invcf} "
           "-b {input.bedgz} "
           "-header -wa "
        "> {output.outvcf}"

rule bcftools_annotate:
    input:
        invcf="my.intersected.vcf.gz"
    output:
        outvcf="my.filtered.vcf.gz"
    shell:
        "/Tools/bcftools/bcftools "
           "annotate "
           "-c CHROM,FROM,TO,GENE "
           "-h <(echo '##INFO=<ID=GENE,Number=1,Type=String,Description=\"Gene name\">') "
           "{input.invcf} "
        "> {output.outvcf}"
</code>```

The advantage is you can reuse each rule throughout your pipeline to intersect or annotate while avoiding temporary files.

Body:
I would like to combine two command lines as one single to avoid the intermediate files.

workdir: "/path/to/workdir/"

rule all:
    input:
        "my.filtered.vcf.gz"

rule bedtools:
    input:
        invcf="/path/to/my.vcf.gz",
        bedgz="/path/to/my.bed.gz"
    output:
        outvcf="my.filtered.vcf.gz"
    shell:
        "/Tools/bedtools2/bin/bedtools intersect -a {input.invcf} -b {input.bedgz} -header -wa |"
        "/Tools/bcftools/bcftools annotate -c CHROM,FROM,TO,GENE -h <(echo '##INFO=<ID=GENE,Number=1,Type=String,Description="Gene name">') > {output.outvcf}"

I am getting invalid syntax error. I would appreciate if you could explain how to combine multiple shell lines in snakemake.

Body:
Escaping the double quotes is the problem, but to add a little more on formatting and pipes.

I prefer the syntax of wrapping each line in " so that the lines can be spaced better:

rule bedtools:
    input:
        invcf="/path/to/my.vcf.gz",
        bedgz="/path/to/my.bed.gz"
    output:
        outvcf="my.filtered.vcf.gz"
    shell:
        "/Tools/bedtools2/bin/bedtools "
           "intersect "
           "-a {input.invcf} "
           "-b {input.bedgz} "
           "-header -wa "
        "| /Tools/bcftools/bcftools "
           "annotate "
           "-c CHROM,FROM,TO,GENE "
           "-h <(echo '##INFO=<ID=GENE,Number=1,Type=String,Description=\"Gene name\">') "
        "> {output.outvcf}"

I find that clearer to see each argument and easier to change by moving lines around.  But note that the trailing space of each line is required and you have to use an explicit newline, \n, if you want a separate command.  When the prompt is printed the output is nicely formated.  With the """ syntax you have to escape each newline with \ at the end and spaces at the start of the line are retained in printing.

If you have lot's of pipe work to do, check out the pipe flag.  You write your first step as a rule and snakemake produces a named pipe between the rules, submitting them as a group:

rule bedtools_intersect:
    input:
        invcf="/path/to/my.vcf.gz",
        bedgz="/path/to/my.bed.gz"
    output:
        outvcf=pipe("my.intersected.vcf.gz")
    shell:
        "/Tools/bedtools2/bin/bedtools "
           "intersect "
           "-a {input.invcf} "
           "-b {input.bedgz} "
           "-header -wa "
        "> {output.outvcf}"

rule bcftools_annotate:
    input:
        invcf="my.intersected.vcf.gz"
    output:
        outvcf="my.filtered.vcf.gz"
    shell:
        "/Tools/bcftools/bcftools "
           "annotate "
           "-c CHROM,FROM,TO,GENE "
           "-h <(echo '##INFO=<ID=GENE,Number=1,Type=String,Description=\"Gene name\">') "
           "{input.invcf} "
        "> {output.outvcf}"

The advantage is you can reuse each rule throughout your pipeline to intersect or annotate while avoiding temporary files.


问:
Cells with drag gesture overwrite the list scrolling using SwiftUI
I have a SwiftUI List with cells that are able to recognize drag gestures in order to swipe them.

The problem is that the drag gesture overlaps the scroll recognition of the list, so I only can swipe the cells. I can not scroll the list.

Is there a way in SwiftUI to tell the List that have to handle multiple gestures?

答:
You can set minimumDistance to some value (for instance 30) on your cell item. Then the drag only works when you drag horizontally and reach the minimum distance, otherwise, the scrollview or list gesture override the view gesture

.gesture(DragGesture(minimumDistance: 30, coordinateSpace: .local))
```


答:
You can initialize an array of Point like this

Dim myPoints = {
    New Point(10, 10),
    New Point(12, 12),
    New Point(13, 13),
    New Point(14, 14),
    New Point(15, 15)
}
```

<p>or put it all on one line, which looks just like your multidimensional array version.</p>

<pre class="lang-vb prettyprint-override"><code>Dim myPoints = {New Point(10, 10), New Point(12, 12), New Point(13, 13), New Point(14, 14), New Point(15, 15)}
</code>```

We can also instead use a jagged array which LINQ can operate on to select new Points

Dim myPoints =
    {New Integer() {10, 11}, New Integer() {12, 13}, New Integer() {14, 15}}.
    Select(Function(p) New Point(p(0), p(1))).ToArray()
```

Title: Declaring points in array for drawing polygon in VB 2019

Body:
You can initialize an array of Point like this

Dim myPoints = {
    New Point(10, 10),
    New Point(12, 12),
    New Point(13, 13),
    New Point(14, 14),
    New Point(15, 15)
}

or put it all on one line, which looks just like your multidimensional array version.

Dim myPoints = {New Point(10, 10), New Point(12, 12), New Point(13, 13), New Point(14, 14), New Point(15, 15)}

We can also instead use a jagged array which LINQ can operate on to select new Points

Dim myPoints =
    {New Integer() {10, 11}, New Integer() {12, 13}, New Integer() {14, 15}}.
    Select(Function(p) New Point(p(0), p(1))).ToArray()


问:
Process sometimes hangs while waiting for Exit
What may be the reason of my process hanging while waiting for exit?

This code has to start powershell script which inside performs many action e.g start recompiling code via MSBuild, but probably the problem is that it generates too much output and this code gets stuck while waiting to exit even after power shell script executed correctly

it's kinda "weird" because sometimes this code works fine and sometimes it just gets stuck.

Code hangs at:

process.WaitForExit(ProcessTimeOutMiliseconds);

Powershell script executes in like 1-2sec meanwhile timeout is 19sec.

```<code>public static (bool Success, string Logs) ExecuteScript(string path, int ProcessTimeOutMiliseconds, params string[] args)
{
    StringBuilder output = new StringBuilder();
    StringBuilder error = new StringBuilder();

    using (var outputWaitHandle = new AutoResetEvent(false))
    using (var errorWaitHandle = new AutoResetEvent(false))
    {
        try
        {
            using (var process = new Process())
            {
                process.StartInfo = new ProcessStartInfo
                {
                    WindowStyle = ProcessWindowStyle.Hidden,
                    FileName = "powershell.exe",
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    UseShellExecute = false,
                    Arguments = $"-ExecutionPolicy Bypass -File \"{path}\"",
                    WorkingDirectory = Path.GetDirectoryName(path)
                };

                if (args.Length > 0)
                {
                    var arguments = string.Join(" ", args.Select(x => $"\"{x}\""));
                    process.StartInfo.Arguments += $" {arguments}";
                }

                output.AppendLine($"args:'{process.StartInfo.Arguments}'");

                process.OutputDataReceived += (sender, e) =>
                {
                    if (e.Data == null)
                    {
                        outputWaitHandle.Set();
                    }
                    else
                    {
                        output.AppendLine(e.Data);
                    }
                };
                process.ErrorDataReceived += (sender, e) =>
                {
                    if (e.Data == null)
                    {
                        errorWaitHandle.Set();
                    }
                    else
                    {
                        error.AppendLine(e.Data);
                    }
                };

                process.Start();

                process.BeginOutputReadLine();
                process.BeginErrorReadLine();

                process.WaitForExit(ProcessTimeOutMiliseconds);

                var logs = output + Environment.NewLine + error;

                return process.ExitCode == 0 ? (true, logs) : (false, logs);
            }
        }
        finally
        {
            outputWaitHandle.WaitOne(ProcessTimeOutMiliseconds);
            errorWaitHandle.WaitOne(ProcessTimeOutMiliseconds);
        }
    }
}
</code>```

Script:

```<code>start-process $args[0] App.csproj -Wait -NoNewWindow

[string]$sourceDirectory  = "\bin\Debug\*"
[int]$count = (dir $sourceDirectory | measure).Count;

If ($count -eq 0)
{
    exit 1;
}
Else
{
    exit 0;
}
</code>```

where

$args[0] = "C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\MSBuild\Current\Bin\MSBuild.exe"

Edit

To @ingen's solution I added small wrapper which retries to execute hanged up MS Build

```<code>public static void ExecuteScriptRx(string path, int processTimeOutMilliseconds, out string logs, out bool success, params string[] args)
{
    var current = 0;
    int attempts_count = 5;
    bool _local_success = false;
    string _local_logs = "";

    while (attempts_count > 0 && _local_success == false)
    {
        Console.WriteLine($"Attempt: {++current}");
        InternalExecuteScript(path, processTimeOutMilliseconds, out _local_logs, out _local_success, args);
        attempts_count--;
    }

    success = _local_success;
    logs = _local_logs;
}
</code>```

Where InternalExecuteScript is ingen's code

答:
Not sure if this is your issue, but looking at MSDN there seems to be some weirdness with the overloaded WaitForExit when you are redirecting output asynchronously. MSDN article recommends calling the WaitForExit that takes no arguments after calling the overloaded method.

Docs page located here. Relevant text:

When standard output has been redirected to asynchronous event handlers, it is possible that output processing will not have completed when this method returns. To ensure that asynchronous event handling has been completed, call the WaitForExit() overload that takes no parameter after receiving a true from this overload. To help ensure that the Exited event is handled correctly in Windows Forms applications, set the SynchronizingObject property.

Code modification might look something like this:

```<code>if (process.WaitForExit(ProcessTimeOutMiliseconds))
{
  process.WaitForExit();
}
</code>```

Body:
What may be the reason of my process hanging while waiting for exit?

This code has to start powershell script which inside performs many action e.g start recompiling code via MSBuild, but probably the problem is that it generates too much output and this code gets stuck while waiting to exit even after power shell script executed correctly

it's kinda "weird" because sometimes this code works fine and sometimes it just gets stuck.

Code hangs at:

process.WaitForExit(ProcessTimeOutMiliseconds);

Powershell script executes in like 1-2sec meanwhile timeout is 19sec.

public static (bool Success, string Logs) ExecuteScript(string path, int ProcessTimeOutMiliseconds, params string[] args)
{
    StringBuilder output = new StringBuilder();
    StringBuilder error = new StringBuilder();

    using (var outputWaitHandle = new AutoResetEvent(false))
    using (var errorWaitHandle = new AutoResetEvent(false))
    {
        try
        {
            using (var process = new Process())
            {
                process.StartInfo = new ProcessStartInfo
                {
                    WindowStyle = ProcessWindowStyle.Hidden,
                    FileName = "powershell.exe",
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    UseShellExecute = false,
                    Arguments = $"-ExecutionPolicy Bypass -File \"{path}\"",
                    WorkingDirectory = Path.GetDirectoryName(path)
                };

                if (args.Length > 0)
                {
                    var arguments = string.Join(" ", args.Select(x => $"\"{x}\""));
                    process.StartInfo.Arguments += $" {arguments}";
                }

                output.AppendLine($"args:'{process.StartInfo.Arguments}'");

                process.OutputDataReceived += (sender, e) =>
                {
                    if (e.Data == null)
                    {
                        outputWaitHandle.Set();
                    }
                    else
                    {
                        output.AppendLine(e.Data);
                    }
                };
                process.ErrorDataReceived += (sender, e) =>
                {
                    if (e.Data == null)
                    {
                        errorWaitHandle.Set();
                    }
                    else
                    {
                        error.AppendLine(e.Data);
                    }
                };

                process.Start();

                process.BeginOutputReadLine();
                process.BeginErrorReadLine();

                process.WaitForExit(ProcessTimeOutMiliseconds);

                var logs = output + Environment.NewLine + error;

                return process.ExitCode == 0 ? (true, logs) : (false, logs);
            }
        }
        finally
        {
            outputWaitHandle.WaitOne(ProcessTimeOutMiliseconds);
            errorWaitHandle.WaitOne(ProcessTimeOutMiliseconds);
        }
    }
}

Script:

start-process $args[0] App.csproj -Wait -NoNewWindow

[string]$sourceDirectory  = "\bin\Debug\*"
[int]$count = (dir $sourceDirectory | measure).Count;

If ($count -eq 0)
{
    exit 1;
}
Else
{
    exit 0;
}

where

$args[0] = "C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\MSBuild\Current\Bin\MSBuild.exe"

Edit

To @ingen's solution I added small wrapper which retries to execute hanged up MS Build

public static void ExecuteScriptRx(string path, int processTimeOutMilliseconds, out string logs, out bool success, params string[] args)
{
    var current = 0;
    int attempts_count = 5;
    bool _local_success = false;
    string _local_logs = "";

    while (attempts_count > 0 && _local_success == false)
    {
        Console.WriteLine($"Attempt: {++current}");
        InternalExecuteScript(path, processTimeOutMilliseconds, out _local_logs, out _local_success, args);
        attempts_count--;
    }

    success = _local_success;
    logs = _local_logs;
}

Where InternalExecuteScript is ingen's code

Body:
Not sure if this is your issue, but looking at MSDN there seems to be some weirdness with the overloaded WaitForExit when you are redirecting output asynchronously. MSDN article recommends calling the WaitForExit that takes no arguments after calling the overloaded method.

Docs page located here. Relevant text:

When standard output has been redirected to asynchronous event handlers, it is possible that output processing will not have completed when this method returns. To ensure that asynchronous event handling has been completed, call the WaitForExit() overload that takes no parameter after receiving a true from this overload. To help ensure that the Exited event is handled correctly in Windows Forms applications, set the SynchronizingObject property.

Code modification might look something like this:

if (process.WaitForExit(ProcessTimeOutMiliseconds))
{
  process.WaitForExit();
}


问:
How to import popper.js?
It seems to be a lame question, but I cannot figure it out. How to import popper.js which comes together with Bootstrap 4 beta?

I use Bower, and I've installed Bootstrap 4 beta. Now in the bower_components folder, there is the popper.js directory, which contains a few sub-folders. The problem is there is no dist folder and the popper.min.js file.

Bootstrap 4 guide links to CDN: https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js.

How to import popper.js without CDN? Where to find the popper.min.js file?

EDIT: Even if I download a zip file from the popper.js website, it contains the same files as I've downloaded from Bower.

答:
Install popper.js with spesific version number like this:

```<code>bower install popper.js@^1.16.0
</code>```

Now u can find dist folder and popper.min.js file.

Title: How to import popper.js?

Body:
Install popper.js with spesific version number like this:

bower install popper.js@^1.16.0

Now u can find dist folder and popper.min.js file.


问:
How to use trackedRaycast(_:updateHandler:) method in ARKit?

Repeats a ray-cast query over time to notify you of updated surfaces in the physical environment.

How to use this func in ARKit?

```<code>func trackedRaycast(_ query: ARRaycastQuery,
              updateHandler: @escaping ([ARRaycastResult]) -> Void) -> ARTrackedRaycast?
</code>```

答:
First define a query with something like

```<code>let bounds = sceneView.bounds
let screenCenter = CGPoint(x: bounds.midX, y: bounds.midY)
let query = sceneView.raycastQuery(from: screenCenter, allowing: .estimatedPlane, alignment: .horizontal)
</code>```

Then initiate trackedRaycast with update handler:

```<code>let trackedRaycast = sceneView.castTrackedRay(for: query, updateHandler: { results in
    guard let result = results.first else { return }
    // Do something with results
    // Maybe adjust a relevent node's position
    someNode.simdWorldPosition = result.worldTransform.position
})
</code>```

Then, if at some point you don't need to track it/update position anymore, you can stop the updateHandler execution: trackedRaycast?.stopTracking()

Note that if a normal raycast would fail either because of query constraints or scene trouble, then a trackedRaycast will also fail and your trackedRaycast object will be nil.

Body:
Repeats a ray-cast query over time to notify you of updated surfaces in the physical environment.

How to use this func in ARKit?

func trackedRaycast(_ query: ARRaycastQuery,
              updateHandler: @escaping ([ARRaycastResult]) -> Void) -> ARTrackedRaycast?

Body:
First define a query with something like

let bounds = sceneView.bounds
let screenCenter = CGPoint(x: bounds.midX, y: bounds.midY)
let query = sceneView.raycastQuery(from: screenCenter, allowing: .estimatedPlane, alignment: .horizontal)

Then initiate trackedRaycast with update handler:

let trackedRaycast = sceneView.castTrackedRay(for: query, updateHandler: { results in
    guard let result = results.first else { return }
    // Do something with results
    // Maybe adjust a relevent node's position
    someNode.simdWorldPosition = result.worldTransform.position
})

Then, if at some point you don't need to track it/update position anymore, you can stop the updateHandler execution: trackedRaycast?.stopTracking()

Note that if a normal raycast would fail either because of query constraints or scene trouble, then a trackedRaycast will also fail and your trackedRaycast object will be nil.


问:
Show and Hide tables with Bootstrap?
I'm currently designing a price table. The table will have three options:

Personal

Professional

Business

each of these options will be on a button. The idea is that when the user clicks on the corresponding button, the table of that plan will be shown.

How should this be done with bootstrap? using jquery?

My logic tells me that it should be something like having all 3 tables in the html and modifying the display attribute according to the button that is clicked. However, I am not entirely clear on this.

答:
Bootstrap has an inbuilt collapse function for this, or you could look into its tab functionality depending on what you're looking for.

Of course this is also entirely possible to make from scratch in jQuery, but since you seem to be mainly looking for a Bootstrap solution, one of these might be it for you. It might be a time-saver for you as well.

Title: Show and Hide tables with Bootstrap?


问:
Bootstrap table, group-by-v2 plugin not working in example
I am using JQuery Bootstrap-table, grouping data. found here: https://examples.bootstrap-table.com/#extensions/group-by-v2.html.
The example given there currently shows an extra row (not found in JSON), but does not create expand-collapse icons or functionality.

Am I missing something?
this is the code I am using in HTML file:

```<code>        <link href="../lib/bootstrap-table/src/extensions/group-by-v2/bootstrap-table-group-by.css" rel="stylesheet"/>
        <link href="../lib/bootstrap-table/src/bootstrap-table.css" rel="stylesheet"/>
        <link href="../lib/bootstrap-table/src/extensions/filter-control/bootstrap-table-filter-control.css" rel="stylesheet"/>
        <link rel="stylesheet" href="../lib/bootstrap4-editable/css/bootstrap-editable.css">
...
       <script type="text/javascript" src="../util/bootstrap-table.js"></script>
        <script src="../lib/bootstrap-table/src/extensions/editable/bootstrap-table-editable.js"></script>
        <script src="../lib/bootstrap-table/src/extensions/filter-control/bootstrap-table-filter-control.js"></script>
        <script src="../lib/bootstrap-table/src/extensions/group-by-v2/bootstrap-table-group-by.js"></script>
</code>```

... Further down in HTML file.

```<code>                <table id="summGrid" data-toolbar="#summToolbar" data-search="true" data-show-refresh="true" data-show-toggle="true"
                data-show-fullscreen="true" data-show-columns="true" data-detail-view="false" data-show-export="true" data-click-to-select="true"
                data-group-by="true" data-group-by-field="shape"  data-url="./tree.json"
                data-pagination="true" data-filter-control="true" data-show-footer="true" data-unique-id="id" data-id-field="id">
                <thead>
                  <tr>
                    <th data-field="shape">Shape</th>
                    <th data-field="color">Color</th>
                    <th data-field="area">Area</th>
                  </tr>
                </thead>

                </table>
</code>```

The Json (tree.json) is like this:

```<code>[
    {
        "id": 1,
        "shape": "triangle",
        "color": "red",
        "area": 5,
        "label": "T1"
    },
    {
        "id": 2,
        "shape": "triangle",
        "color": "green",
        "area": 27,
        "label": "T2"
    },
...
</code>```

I copy pasted the whole thing from the example provided in the link above.

答:
I figured out that this extension (group-by-v2) does not have this functionality.
I found another extension which does this job.
tree-grid extension (https://live.bootstrap-table.com/example/extensions/treegrid.html). </p>

Body:
I am using JQuery Bootstrap-table, grouping data. found here: https://examples.bootstrap-table.com/#extensions/group-by-v2.html.
The example given there currently shows an extra row (not found in JSON), but does not create expand-collapse icons or functionality.

Am I missing something?
this is the code I am using in HTML file:

        <link href="../lib/bootstrap-table/src/extensions/group-by-v2/bootstrap-table-group-by.css" rel="stylesheet"/>
        <link href="../lib/bootstrap-table/src/bootstrap-table.css" rel="stylesheet"/>
        <link href="../lib/bootstrap-table/src/extensions/filter-control/bootstrap-table-filter-control.css" rel="stylesheet"/>
        <link rel="stylesheet" href="../lib/bootstrap4-editable/css/bootstrap-editable.css">
...

... Further down in HTML file.

                    Shape
                    Color
                    Area

The Json (tree.json) is like this:

[
    {
        "id": 1,
        "shape": "triangle",
        "color": "red",
        "area": 5,
        "label": "T1"
    },
    {
        "id": 2,
        "shape": "triangle",
        "color": "green",
        "area": 27,
        "label": "T2"
    },
...

I copy pasted the whole thing from the example provided in the link above.


问:
How to subtract an offset to dates generated through a recursive CTE?
The query below uses a recursive CTE to generate days if there is no data for that specific day. I want to group the daily downtime total starting at 7:15 the previous day until 7:15 the next day and do it over a month. This query works fine but I need to subtract DATEADD(minute, -(7 * 60 + 15) from each day.</p>

```<code>WITH dates as (
      SELECT CONVERT(date, 'Anydate') as dte
      UNION ALL
      SELECT DATEADD(day, 1, dte)
      FROM dates
      WHERE dte < 'Anydate + 1 month later'
     )
SELECT CONVERT(datetime,d.dte), ISNULL(SUM(long_stop_minutes), 0) AS downtime
FROM dates d LEFT JOIN
     long_stops_table b
     ON CAST(t_stamp as DATE) = d.dte AND Type = 'downtime'
GROUP BY CONVERT(datetime, d.dte)
ORDER BY CONVERT(datetime, d.dte) ASC;
</code>```

答:
Just subtract the appropriate time units.  Here is one way:

```<code>SELECT d.dte,
       COALESCE(SUM(lst.long_stop_minutes), 0) AS downtime
FROM dates d LEFT JOIN
     long_stops_table lst
     ON CONVERT(date, DATEADD(minute, -(7 * 60 + 15), lst.t_stamp) = d.dte AND
        lst.Type = 'downtime'
GROUP BY d.dte
ORDER BY d.dte ASC;
</code>```

I see no reason to convert dates.dte to a datetime, so I just removed the conversion.

Body:
The query below uses a recursive CTE to generate days if there is no data for that specific day. I want to group the daily downtime total starting at 7:15 the previous day until 7:15 the next day and do it over a month. This query works fine but I need to subtract DATEADD(minute, -(7 * 60 + 15) from each day.

WITH dates as (
      SELECT CONVERT(date, 'Anydate') as dte
      UNION ALL
      SELECT DATEADD(day, 1, dte)
      FROM dates
      WHERE dte < 'Anydate + 1 month later'
     )
SELECT CONVERT(datetime,d.dte), ISNULL(SUM(long_stop_minutes), 0) AS downtime
FROM dates d LEFT JOIN
     long_stops_table b
     ON CAST(t_stamp as DATE) = d.dte AND Type = 'downtime'
GROUP BY CONVERT(datetime, d.dte)
ORDER BY CONVERT(datetime, d.dte) ASC;

Body:
Just subtract the appropriate time units.  Here is one way:

SELECT d.dte,
       COALESCE(SUM(lst.long_stop_minutes), 0) AS downtime
FROM dates d LEFT JOIN
     long_stops_table lst
     ON CONVERT(date, DATEADD(minute, -(7 * 60 + 15), lst.t_stamp) = d.dte AND
        lst.Type = 'downtime'
GROUP BY d.dte
ORDER BY d.dte ASC;

I see no reason to convert dates.dte to a datetime, so I just removed the conversion.


问:
How to combine and filter two dart Streams
I am using flutter_blue for a flutter Application using bluetooth.

flutter_blue presents me with two streams:
   FlutterBlue.instance.connectedDevices
   FlutterBlue.instance.scanResults

I would like to combine those two streams into one and apply a filter.

Googling around I get references to rxdart but still,, I cant get it to work.
Help please :)

答:
You can use Rx.combineLatest2 like this:</p>

```<code>class CombinedResult {
  final List<BluetoothDevice> connectedDevices;
  final List<ScanResult> scanResults;

  CombinedResult(this.connectedDevices, this.scanResults);
}

final filteredStream = Rx.combineLatest2<List<BluetoothDevice>, List<ScanResult>, CombinedResult>(
  FlutterBlue.instance.connectedDevices,
  FlutterBlue.instance.scanResults,
  (devices, scanResults) => CombinedResult(connectedDevices, scanResults),
).where((combinedResult) {
  return true; //do your filtering here
});
</code>```

Body:
You can use Rx.combineLatest2 like this:

class CombinedResult {
  final List<BluetoothDevice> connectedDevices;
  final List<ScanResult> scanResults;

  CombinedResult(this.connectedDevices, this.scanResults);
}

final filteredStream = Rx.combineLatest2<List<BluetoothDevice>, List<ScanResult>, CombinedResult>(
  FlutterBlue.instance.connectedDevices,
  FlutterBlue.instance.scanResults,
  (devices, scanResults) => CombinedResult(connectedDevices, scanResults),
).where((combinedResult) {
  return true; //do your filtering here
});


问:
How to pass Current user to Django_filters ModelChoiceFilter queryset
How to pass Current user to Django_filters ModelChoiceFilter queryset.

I'm trying to filter the ModelChoiceFilter based on the current user , i've used the init method in the filter but it failed:

here is the code I've used :

views.py

def requests_reports(request):
    f = RequestsFilter(request.GET, queryset=LeaveRequest.objects.filter(user=request.user), user=request.user)
    context = {
        'filter': f,
    }
    return render(request, 'requests_reports.html', context)
```

<p><strong>forms.py</strong></p>

<pre class="lang-py prettyprint-override"><code>class RequestsFilter(django_filters.FilterSet):
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        super(RequestsFilter, self).__init__(*args, **kwargs)
        self.fields['employee'].queryset = Employee.objects.filter(user=self.user)

    start_date = DateFilter(field_name='date_time', lookup_expr='gt', widget=forms.TextInput(attrs={'type': 'date'}))
    end_date = DateFilter(field_name='date_time', lookup_expr='lt', widget=forms.TextInput(attrs={'type': 'date'}))

    class Meta:
        model = LeaveRequest
        fields = ['employee', 'type']
</code>```

It returns this error :

```<code>'RequestsFilter' object has no attribute 'fields'
</code>```

答:
you can set a custom method. More info here: https://django-filter.readthedocs.io/en/master/guide/usage.html#customize-filtering-with-filter-method</p>

```<code>class RequestsFilter(django_filters.FilterSet):
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        super().__init__(*args, **kwargs)

    employee = django_filters.filters.ModelMultipleChoiceFilter(
        field_name='employee',
        queryset=Employee.objects.all(),
        method="filter_employee",
    )
    start_date = DateFilter(field_name='date_time', lookup_expr='gt', widget=forms.TextInput(attrs={'type': 'date'}))
    end_date = DateFilter(field_name='date_time', lookup_expr='lt', widget=forms.TextInput(attrs={'type': 'date'}))

    class Meta:
        model = LeaveRequest
        fields = ['employee', 'type']

    def filter_employee(self, queryset, name, value):
        qs = queryset.filter(user=self.user).filter(**{name: value})
        if len(qs) >= 1:
            return qs[0]
        else:
            return None
</code>```

Body:
How to pass Current user to Django_filters ModelChoiceFilter queryset.

I'm trying to filter the ModelChoiceFilter based on the current user , i've used the init method in the filter but it failed:

here is the code I've used :

views.py

def requests_reports(request):
    f = RequestsFilter(request.GET, queryset=LeaveRequest.objects.filter(user=request.user), user=request.user)
    context = {
        'filter': f,
    }
    return render(request, 'requests_reports.html', context)

forms.py

class RequestsFilter(django_filters.FilterSet):
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        super(RequestsFilter, self).__init__(*args, **kwargs)
        self.fields['employee'].queryset = Employee.objects.filter(user=self.user)

    start_date = DateFilter(field_name='date_time', lookup_expr='gt', widget=forms.TextInput(attrs={'type': 'date'}))
    end_date = DateFilter(field_name='date_time', lookup_expr='lt', widget=forms.TextInput(attrs={'type': 'date'}))

    class Meta:
        model = LeaveRequest
        fields = ['employee', 'type']

It returns this error :

'RequestsFilter' object has no attribute 'fields'

Body:
you can set a custom method. More info here: https://django-filter.readthedocs.io/en/master/guide/usage.html#customize-filtering-with-filter-method

class RequestsFilter(django_filters.FilterSet):
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        super().__init__(*args, **kwargs)

    employee = django_filters.filters.ModelMultipleChoiceFilter(
        field_name='employee',
        queryset=Employee.objects.all(),
        method="filter_employee",
    )
    start_date = DateFilter(field_name='date_time', lookup_expr='gt', widget=forms.TextInput(attrs={'type': 'date'}))
    end_date = DateFilter(field_name='date_time', lookup_expr='lt', widget=forms.TextInput(attrs={'type': 'date'}))

    class Meta:
        model = LeaveRequest
        fields = ['employee', 'type']

    def filter_employee(self, queryset, name, value):
        qs = queryset.filter(user=self.user).filter(**{name: value})
        if len(qs) >= 1:
            return qs[0]
        else:
            return None


问:
Save path with spaces in a bash variable
I am having issues with a very, very simple task. For follow-up use, I would like to store a dirname in a variable which has spaces in it. To see if it works, I call it with ls.

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

BASE_DIR=/home/woodrow/Documents/"sleepy kittens"/
#SOURCE_FILE=${BASE_DIR}file.mp4

ls ${BASE_DIR}
</code>```

But how do I prevent this nonsense?

```<code>ls: cannot access '/home/woodrow/Documents/sleepy': No such file or directory
ls: cannot access 'kittens': No such file or directory
</code>```

Varitions that I tried but didn't work:

```<code>BASE_DIR=/home/woodrow/Documents/sleepy kittens/
BASE_DIR="/home/woodrow/Documents/sleepy kittens/"
BASE_DIR=/home/woodrow/Documents/`sleepy kittens`/
BASE_DIR=/home/woodrow/Documents/"`sleepy kittens`"/
BASE_DIR=$(/home/woodrow/Documents/sleepy kittens/)
BASE_DIR=$("/home/woodrow/Documents/sleepy kittens/")
BASE_DIR=$("`/home/woodrow/Documents/sleepy kittens/`")
BASE_DIR=$(echo /home/woodrow/Documents/sleepy kittens/)
BASE_DIR=$(echo "/home/woodrow/Documents/sleepy kittens/")
BASE_DIR=$(echo "`/home/woodrow/Documents/sleepy kittens/`")

ls "${BASE_DIR}"

BASE_DIR=/home/woodrow/Documents/
STEP="${BASE_DIR}sleepy kittens/"
ls ${STEP}
</code>```

Can someone please enlighten me?

答:
You can do this :</p>

```<code>(0) matias #> touch 'my spaced file.txt'
(0) matias #> myFile='my spaced file.txt'
(0) matias #> ls -lh "$myFile"
-rw-rw-r-- 1 matias matias 0 Feb 19 15:21 'my spaced file.txt'
</code>```

Body:
I am having issues with a very, very simple task. For follow-up use, I would like to store a dirname in a variable which has spaces in it. To see if it works, I call it with ls.

#!/bin/bash

BASE_DIR=/home/woodrow/Documents/"sleepy kittens"/
#SOURCE_FILE=${BASE_DIR}file.mp4

ls ${BASE_DIR}

But how do I prevent this nonsense?

ls: cannot access '/home/woodrow/Documents/sleepy': No such file or directory
ls: cannot access 'kittens': No such file or directory

Varitions that I tried but didn't work:

BASE_DIR=/home/woodrow/Documents/sleepy kittens/
BASE_DIR="/home/woodrow/Documents/sleepy kittens/"
BASE_DIR=/home/woodrow/Documents/`sleepy kittens`/
BASE_DIR=/home/woodrow/Documents/"`sleepy kittens`"/
BASE_DIR=$(/home/woodrow/Documents/sleepy kittens/)
BASE_DIR=$("/home/woodrow/Documents/sleepy kittens/")
BASE_DIR=$("`/home/woodrow/Documents/sleepy kittens/`")
BASE_DIR=$(echo /home/woodrow/Documents/sleepy kittens/)
BASE_DIR=$(echo "/home/woodrow/Documents/sleepy kittens/")
BASE_DIR=$(echo "`/home/woodrow/Documents/sleepy kittens/`")

ls "${BASE_DIR}"

BASE_DIR=/home/woodrow/Documents/
STEP="${BASE_DIR}sleepy kittens/"
ls ${STEP}

Can someone please enlighten me?

Body:
You can do this :

(0) matias #> touch 'my spaced file.txt'
(0) matias #> myFile='my spaced file.txt'
(0) matias #> ls -lh "$myFile"
-rw-rw-r-- 1 matias matias 0 Feb 19 15:21 'my spaced file.txt'


问:
REST - Jersey - Spring - File Download
I'm having a REST API (POST Method) that produces MediaType.APPLICATION_OCTET_STREAM and the response header is also set with the following code.

```<code>@Path("/file")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getFile() throws IOException {
</code>```

.
.
.

```<code>ResponseBuilder respBuilder = Response.ok((Object) file);
respBuilder.header("Content-Disposition", "attachment; filename=\"" + file.getName() + "\";");
return respBuilder.build();
</code>```

However when I call this API from Postman or  My App, This does not download a file, Rather it gives response in body with content and Response code 200.

Not sure what is wrong here! Am i supposed to do any additional configuration in Spring / WEB Server?

答:
You need to return an InputStream as the response body.
Try this:</p>

```<code>InputStream targetStream = new FileInputStream(file)
ResponseBuilder respBuilder = Response.ok(targetStream);
respBuilder.header("Content-Disposition", "attachment; filename=\"" + file.getName() + "\";");
return respBuilder.build();
</code>```

Title: REST - Jersey - Spring - File Download

Body:
I'm having a REST API (POST Method) that produces MediaType.APPLICATION_OCTET_STREAM and the response header is also set with the following code.

@Path("/file")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getFile() throws IOException {

.
.
.

ResponseBuilder respBuilder = Response.ok((Object) file);
respBuilder.header("Content-Disposition", "attachment; filename=\"" + file.getName() + "\";");
return respBuilder.build();

However when I call this API from Postman or  My App, This does not download a file, Rather it gives response in body with content and Response code 200.

Not sure what is wrong here! Am i supposed to do any additional configuration in Spring / WEB Server?

Body:
You need to return an InputStream as the response body.
Try this:

InputStream targetStream = new FileInputStream(file)
ResponseBuilder respBuilder = Response.ok(targetStream);
respBuilder.header("Content-Disposition", "attachment; filename=\"" + file.getName() + "\";");
return respBuilder.build();


问:
How to hide unneccessary subfolders in website address in firebase
I want to reduce the length of the URLs of my webpages in firebase. The html files are inside of an html folder which is inside the public folder. The URL for the index page right now is: www.lstein-28b62.web.app/htmlfolder/index.html
Would it be possible to change this to www.lstein-28b62.web.app/index.html without taking the index.html file out of the htmlfolder subfolder?
I basically just want to hide the /htmlfolder/ subfolder. It should be similar to the js function window.history.pushState(), although this creates problems if the page is refreshed.

答:
You have two options:

Change the folder you deploy to public/html, so that only the contents of the HTML folder are deployed.

```<code>"hosting": {
  "public": "public"

  // ...
}
</code>```

Use a rewrite rule to serve the contents from the root.

```<code>"hosting": {
  // ...

  // Add the "rewrites" attribute within "hosting"
  "rewrites": [ {
    "source": "/html/index.html",
    "destination": "/index.html"
  } ]
}
</code>```

I'd highly recommend the first approach, as the latter requires much more maintenance.

Body:
You have two options:

Change the folder you deploy to public/html, so that only the contents of the HTML folder are deployed.

"hosting": {
  "public": "public"

  // ...
}

Use a rewrite rule to serve the contents from the root.

"hosting": {
  // ...

  // Add the "rewrites" attribute within "hosting"
  "rewrites": [ {
    "source": "/html/index.html",
    "destination": "/index.html"
  } ]
}

I'd highly recommend the first approach, as the latter requires much more maintenance.


问:
Is there a `not` ArgumentMatcher for mockito stubbing
I am trying to verify that a method is called with a long having any value but a given one.

I thus would like to know if there is an ArgumentMatcher that fits to my use case, such as:

verify(mObject).verifiedMethod(notEq(longValueThatShouldBeAvoided));
```

<hr>

<p>I found this workaround:</p>

<pre class="lang-java prettyprint-override"><code>verify(mObject).method(longThat(arg -> arg != longValueThatShouldBeAvoided));
</code>```

But I find weird that such simple ArgumentMatcher has to be written from scratch.

Additional question:
How to proceed when checking for multiple values to avoid ?

Similarly, I found the workaround of using arg -> arg != val0 && arg != val1 lambda as parameter of ArgumentsMatcher.longThat method to achieve this.

答:
try:</p>

```<code>import static org.mockito.AdditionalMatchers.not;
import static org.mockito.ArgumentMatchers.eq;

verify(mObject).verifiedMethod(not(eq(longValueThatShouldBeAvoided)));
</code>```

Body:
I am trying to verify that a method is called with a long having any value but a given one.

I thus would like to know if there is an ArgumentMatcher that fits to my use case, such as:

verify(mObject).verifiedMethod(notEq(longValueThatShouldBeAvoided));

I found this workaround:

verify(mObject).method(longThat(arg -> arg != longValueThatShouldBeAvoided));

But I find weird that such simple ArgumentMatcher has to be written from scratch.

Additional question:
How to proceed when checking for multiple values to avoid ?

Similarly, I found the workaround of using arg -> arg != val0 && arg != val1 lambda as parameter of ArgumentsMatcher.longThat method to achieve this.

Body:
try:

import static org.mockito.AdditionalMatchers.not;
import static org.mockito.ArgumentMatchers.eq;

verify(mObject).verifiedMethod(not(eq(longValueThatShouldBeAvoided)));


问:
I have two tuple comparison. Almost the same data. Why this error:
```<code>print( ('abc', 1, 2) > ('aaa', 777, 'ssst..') )

print( ('abc', 1, 2) > ('abc', 1, 'ssst..') )
</code>```

Result:

```<code>True

Traceback (most recent call last):
  File "//frserv-bu.playtika.local/users$/constantinio/Documents/Python_course/Sedinta3/ex.py", line 33, in <module>
    print( ('abc', 1, 2) > ('abc', 1, 'ssst..') )
TypeError: '>' not supported between instances of 'int' and 'str'

Process finished with exit code 1
</code>```

答:
The first comparison goes as far as comparing 'abc' to 'aaa', and then it knows what the result is and doesn't have to continue to the other elements.

In the second comparison, the tuples have the same value for the first two elements, so it has to check the third, at which point it tries to compare 2 to 'ssst..', which causes the error you saw.

Body:
print( ('abc', 1, 2) > ('aaa', 777, 'ssst..') )

print( ('abc', 1, 2) > ('abc', 1, 'ssst..') )

Result:

True

Traceback (most recent call last):
  File "//frserv-bu.playtika.local/users$/constantinio/Documents/Python_course/Sedinta3/ex.py", line 33, in <module>
    print( ('abc', 1, 2) > ('abc', 1, 'ssst..') )
TypeError: '>' not supported between instances of 'int' and 'str'

Process finished with exit code 1


问:
Cross domain ajax request from javascript file without help of server side code
I am consuming service of random.org, (I want to get the numbers from random.org site using url). I am fetching data using ajax from my JavaScript. So how to make cross domain ajax call from my domain (and avoid permission error)? I want solution without help of server side code (sever proxy). Example code will be great help for me. </p>

答:
Just sent an email to random.org and received this reply

Thanks for your email.  Yes, I am working on a JSONP interface.

Best regards,

Mads

ContentLicense: CC BY-SA 2.5


问:
Create OpenCV Video Widgets to use in Kivy
I have 2 to 4 rtsp streams that I want to display within a box layout in Kivy but I can't seem to figure out how to use the kv language to achieve this. I am able to get one camera displaying using this code:

```<code>class KivyCamera(Image):
    def __init__(self, capture, fps, **kwargs):
        super(KivyCamera, self).__init__(**kwargs)
        self.capture = capture
        Clock.schedule_interval(self.update, 1.0 / fps)

    def update(self, dt):
        ret, frame = self.capture.read()
        if ret:
            # convert it to texture
            buf1 = cv2.flip(frame, 0)
            buf = buf1.tostring()
            image_texture = Texture.create(
                size=(frame.shape[1], frame.shape[0]), colorfmt='bgr')
            image_texture.blit_buffer(buf, colorfmt='bgr', bufferfmt='ubyte')
            # display image from the texture
            self.texture = image_texture

class CamApp(App):
    def build(self):
        self.capture = cv2.VideoCapture('stream address removed for stack overflow')
        self.my_camera = KivyCamera(capture=self.capture, fps=30)
        return self.my_camera

    def on_stop(self):
        #without this, app will not exit even if the window is closed
        self.capture.release()

if __name__ == '__main__':
    CamApp().run()
</code>```

However this is only using .py. I would like to have the ability to use the kv language to create instances of KivyCamera and set a different capture value for each one.

For example:

```<code>BoxLayout:
        orientation: 'horizontal'

        KivyCamera:
            capture: 'myvalue'
            pos_hint: {'left': 1}

        KivyCamera:
            capture: 'anothervalue'
            pos_hint: {'right': 1}
</code>```

答:
You can make the properties be fps and the source (index, filename, etc) instead of the VideoCapture:

main.py

from kivy.app import App
from kivy.uix.image import Image
from kivy.clock import Clock
from kivy.graphics.texture import Texture
from kivy.properties import ObjectProperty, NumericProperty

import cv2

class KivyCamera(Image):
    source = ObjectProperty()
    fps = NumericProperty(30)

    def __init__(self, **kwargs):
        super(KivyCamera, self).__init__(**kwargs)
        self._capture = None
        if self.source is not None:
            self._capture = cv2.VideoCapture(self.source)
        Clock.schedule_interval(self.update, 1.0 / self.fps)

    def on_source(self, *args):
        if self._capture is not None:
            self._capture.release()
        self._capture = cv2.VideoCapture(self.source)

    @property
    def capture(self):
        return self._capture

    def update(self, dt):
        ret, frame = self.capture.read()
        if ret:
            buf1 = cv2.flip(frame, 0)
            buf = buf1.tostring()
            image_texture = Texture.create(
                size=(frame.shape[1], frame.shape[0]), colorfmt="bgr"
            )
            image_texture.blit_buffer(buf, colorfmt="bgr", bufferfmt="ubyte")
            self.texture = image_texture

class CamApp(App):
    pass

if __name__ == "__main__":
    CamApp().run()
```

<p><strong>cam.kv</strong></p>

```BoxLayout:
    orientation: 'horizontal'

    KivyCamera:
        source: "stream address removed for stack overflow"
```

Body:
I have 2 to 4 rtsp streams that I want to display within a box layout in Kivy but I can't seem to figure out how to use the kv language to achieve this. I am able to get one camera displaying using this code:

class KivyCamera(Image):
    def __init__(self, capture, fps, **kwargs):
        super(KivyCamera, self).__init__(**kwargs)
        self.capture = capture
        Clock.schedule_interval(self.update, 1.0 / fps)

    def update(self, dt):
        ret, frame = self.capture.read()
        if ret:
            # convert it to texture
            buf1 = cv2.flip(frame, 0)
            buf = buf1.tostring()
            image_texture = Texture.create(
                size=(frame.shape[1], frame.shape[0]), colorfmt='bgr')
            image_texture.blit_buffer(buf, colorfmt='bgr', bufferfmt='ubyte')
            # display image from the texture
            self.texture = image_texture

class CamApp(App):
    def build(self):
        self.capture = cv2.VideoCapture('stream address removed for stack overflow')
        self.my_camera = KivyCamera(capture=self.capture, fps=30)
        return self.my_camera

    def on_stop(self):
        #without this, app will not exit even if the window is closed
        self.capture.release()

if __name__ == '__main__':
    CamApp().run()

However this is only using .py. I would like to have the ability to use the kv language to create instances of KivyCamera and set a different capture value for each one.

For example:

BoxLayout:
        orientation: 'horizontal'

        KivyCamera:
            capture: 'myvalue'
            pos_hint: {'left': 1}

        KivyCamera:
            capture: 'anothervalue'
            pos_hint: {'right': 1}

Body:
You can make the properties be fps and the source (index, filename, etc) instead of the VideoCapture:

main.py

from kivy.app import App
from kivy.uix.image import Image
from kivy.clock import Clock
from kivy.graphics.texture import Texture
from kivy.properties import ObjectProperty, NumericProperty

import cv2

class KivyCamera(Image):
    source = ObjectProperty()
    fps = NumericProperty(30)

    def __init__(self, **kwargs):
        super(KivyCamera, self).__init__(**kwargs)
        self._capture = None
        if self.source is not None:
            self._capture = cv2.VideoCapture(self.source)
        Clock.schedule_interval(self.update, 1.0 / self.fps)

    def on_source(self, *args):
        if self._capture is not None:
            self._capture.release()
        self._capture = cv2.VideoCapture(self.source)

    @property
    def capture(self):
        return self._capture

    def update(self, dt):
        ret, frame = self.capture.read()
        if ret:
            buf1 = cv2.flip(frame, 0)
            buf = buf1.tostring()
            image_texture = Texture.create(
                size=(frame.shape[1], frame.shape[0]), colorfmt="bgr"
            )
            image_texture.blit_buffer(buf, colorfmt="bgr", bufferfmt="ubyte")
            self.texture = image_texture

class CamApp(App):
    pass

if __name__ == "__main__":
    CamApp().run()

cam.kv

BoxLayout:
    orientation: 'horizontal'

    KivyCamera:
        source: "stream address removed for stack overflow"


问:
Exclude category from list
i need to exclude a category from category list in wordpress. i have used below code.
wants to exclude category = "featured_home"

```<code>   $categories = get_categories();
   foreach($categories as $category) {
   echo '<button class="button" data-filter=".' .$category->name. '">'.$category->name.'</button>';
                    }
</code>```

Please help me as soon as possible.

Thanks in advance.

答:
You could add an if-statement to the loop:

```<code>foreach( $categories as $category ):
    if ($category->cat_name === 'TheCategoryToIgnore') {
        continue; // This will skip the rest and jump to the next category
    }
    ?>
    ... // Your current code
</code>```

If you rather check on the id or the slug, just change the condition in the if-statement.

Title: Exclude category from list

Body:
i need to exclude a category from category list in wordpress. i have used below code.
wants to exclude category = "featured_home"

   $categories = get_categories();
   foreach($categories as $category) {
   echo '<button class="button" data-filter=".' .$category->name. '">'.$category->name.'</button>';
                    }

Please help me as soon as possible.

Thanks in advance.

Body:
You could add an if-statement to the loop:

foreach( $categories as $category ):
    if ($category->cat_name === 'TheCategoryToIgnore') {
        continue; // This will skip the rest and jump to the next category
    }
    ?>
    ... // Your current code

If you rather check on the id or the slug, just change the condition in the if-statement.


问:
Trailing spaces during integer to string conversion in power shell script
I am converting an integer to string . The string is appended with spaces at the end . I used Trim() function but still its giving trailing spaces towards the end. What is the funny thing happening here?. I use PS version 5.

Code:

```<code>$OutputFileDtls = $OutputFileDtls + "/" + $Global:FilenmPathCur + ":" + $CurRecCnt.ToString().Trim() + ";"
        Add-Content -Value "$TimeinSec Log: Details of the output files found for current job: $jobname in the $mastTableNm table are Count: $OutputFileRecCnt Details: $OutputFileDtls " -Path $logfile
</code>```

output:

```<code>2020-02-19 14:21:38 Log: Details of the output files found for current job: BD_PR_AMS_FNTR_DATAVALIDATION_BLOCK1 in the [dbo].[DSTalendJobs] table are Count: 0 Details: /Dataproviders/Temp/Validated/GCW/FinalTier/AMS/gcw_finaltier_ams_565_20191124_03_58_37_data_validation.valid:0;/Dataproviders/Temp/Rejected/GCW/FinalTier/AMS/gcw_finaltier_ams_565_20191124_03_58_37_data_validation.reject:0;/Dataproviders/Temp/Blocked/GCW/FinalTier/AMS/gcw_finaltier_ams_565_20191124_03_58_37_cutoffdate.block                                                                                :0
</code>```

Here you can see a zero at the end after trailing spaces which shouldn't come in the first place

答:
You should also trim FilenmPathCur:
$Global:FilenmPathCur.Trim()

You also have a trailing space in the Add-Content value.

Body:
I am converting an integer to string . The string is appended with spaces at the end . I used Trim() function but still its giving trailing spaces towards the end. What is the funny thing happening here?. I use PS version 5.

Code:

$OutputFileDtls = $OutputFileDtls + "/" + $Global:FilenmPathCur + ":" + $CurRecCnt.ToString().Trim() + ";"
        Add-Content -Value "$TimeinSec Log: Details of the output files found for current job: $jobname in the $mastTableNm table are Count: $OutputFileRecCnt Details: $OutputFileDtls " -Path $logfile

output:

2020-02-19 14:21:38 Log: Details of the output files found for current job: BD_PR_AMS_FNTR_DATAVALIDATION_BLOCK1 in the [dbo].[DSTalendJobs] table are Count: 0 Details: /Dataproviders/Temp/Validated/GCW/FinalTier/AMS/gcw_finaltier_ams_565_20191124_03_58_37_data_validation.valid:0;/Dataproviders/Temp/Rejected/GCW/FinalTier/AMS/gcw_finaltier_ams_565_20191124_03_58_37_data_validation.reject:0;/Dataproviders/Temp/Blocked/GCW/FinalTier/AMS/gcw_finaltier_ams_565_20191124_03_58_37_cutoffdate.block                                                                                :0

Here you can see a zero at the end after trailing spaces which shouldn't come in the first place


问:
I'm having a problem related disk space in nexus when trying to delete old docker image
I've faced a disk space problem while trying to publish new docker images from Jenkins to Nexus. I've tried deleting unnecessary docker images but still get the same error. So still unable to publish them.

WARN [elasticsearch[B53806D8-E678EED6-33AE6D2D-74559435-2CF713DB][management][T#1]] *SYSTEM org.elasticsearch.cluster.routing.allocation.decider - [B53806D8-E678EED6-33AE6D2D-74559435-2CF713DB] high disk watermark [90%] exceeded on [IkQiINmZTfGaLtZlXK3btg][B53806D8-E678EED6-33AE6D2D-74559435-2CF713DB][/nexus-data/elasticsearch/nexus/nodes/0] free: 2.5gb[0.3%], shards will be relocated away from this node

答: this is about your othe containers. you can use du -h -d 1 /var/lib/docker and you can see diks usage status</p>


问:
for-loop interruption slows down OpenCL kernel
Learning OpenCL implementing program which finds 8 most similar pixels within 10 pixels radius for every pixel:

//-DBEST=8

__kernel void best_pixel_matches(
    __global const uint * image,
    const ushort width,
    const ushort height,
    // [ width ] [ height ] [ BEST ] [ 2 ]
    __global short * best,
    __global int * errors
)
{
    const int x = get_global_id(0);
    const int y = get_global_id(1);

    const uint pixel = image[ y * width + x ];

    const short SURROUND = 10;

    //local best pixels coordinates:
    short s[ BEST ][ 2 ];
    //... corresponding local best pixels computed deltas (storage instead of recompute speeds program about twice):
    uint d[ BEST ];
    //... init with none:
    for ( short i = 0; i < BEST; ++ i ) d[ i ] = -1;

    for ( short sw = - SURROUND; sw < SURROUND; ++ sw ) {
    for ( short sh = - SURROUND; sh < SURROUND; ++ sh ) {
        //avoid inexistent pixels:
        const short tw = x + sw; if ( tw < 0 || tw >= width  ) continue;
        const short th = y + sh; if ( th < 0 || th >= height ) continue;
        //not with itself:
        if ( tw == x && th == y ) continue;
        const uint diff = (uint) abs( (long)pixel - (long)image[ th * width + tw ] );

        for ( short si = 0; si < BEST; ++ si ) {
            if ( d[si] == -1 || diff < d[si] ) {
                d[si] = diff;
                s[si][0] = tw;
                s[si][1] = th;
                break;//<-- this line causes 4 (!) times slow down
            }
        }
    } }

    //copy results from private memory to global:
    const long p = ( x * height + y ) * BEST;
    for ( short b = 0; b < BEST; ++ b ) {
        const long pb = ( p + b ) * 2;
        best[ pb     ] = s[b][0];
        best[ pb + 1 ] = s[b][1];
    }
}
```

The problem was that it took GPU 3593ms for 2560*1440 image which is almost exactly the same time as plain C++ CPU code I had before (~8500ms). Then I tried to tune it here and there and occasionally removed break; line and execution time -> 900ms!

What's the reason behind such surprising speed up? That break; line just tells program it's not needed to check any other pixels further so supposed to decrease execution time - not slow it down? Maybe there are some other ways to speed up this program too? :)

答:
Try to maintain memory access order, just before global writing

```<code> // here
 barrier(CLK_GLOBAL_MEM_FENCE);

 //copy results from private memory to global:
 const long p = ( x * height + y ) * BEST;
</code>```

if your performance problem is originating from memory access pattern, this should ease it.

If problem comes from just branching between threads, then you can also try maintaining order within the second loop after innermost loop:

```<code>for ( short si = 0; si < BEST; ++ si ) {
            if ( d[si] == -1 || diff < d[si] ) {
                d[si] = diff;
                s[si][0] = tw;
                s[si][1] = th;
                break;
            }
        }
barrier(CLK_LOCAL_MEM_FENCE); // local => should be faster for many devices
</code>```

so that in every iteration, all neighboring threads rejoin together and continue executing same instructions until a new break breaks the order.

Lastly, algorithm seems like sorting pixel value differences between SURROUND pixels, by decreasing values. So, the innermost loop could actually be moved to outermost and have all the branching be minimized, just after innermost two new loops(which were outermost before). But this increases image[ th * width + tw ] reading by BEST times so it can be slower too(maybe not when data moved to local memory before this). But, d does not need to be an array now so BEST number of private registers are saved and could give it some performance boost by decreasing register pressure.

Body:
Learning OpenCL implementing program which finds 8 most similar pixels within 10 pixels radius for every pixel:

//-DBEST=8

__kernel void best_pixel_matches(
    __global const uint * image,
    const ushort width,
    const ushort height,
    // [ width ] [ height ] [ BEST ] [ 2 ]
    __global short * best,
    __global int * errors
)
{
    const int x = get_global_id(0);
    const int y = get_global_id(1);

    const uint pixel = image[ y * width + x ];

    const short SURROUND = 10;

    //local best pixels coordinates:
    short s[ BEST ][ 2 ];
    //... corresponding local best pixels computed deltas (storage instead of recompute speeds program about twice):
    uint d[ BEST ];
    //... init with none:
    for ( short i = 0; i < BEST; ++ i ) d[ i ] = -1;

    for ( short sw = - SURROUND; sw < SURROUND; ++ sw ) {
    for ( short sh = - SURROUND; sh < SURROUND; ++ sh ) {
        //avoid inexistent pixels:
        const short tw = x + sw; if ( tw < 0 || tw >= width  ) continue;
        const short th = y + sh; if ( th < 0 || th >= height ) continue;
        //not with itself:
        if ( tw == x && th == y ) continue;
        const uint diff = (uint) abs( (long)pixel - (long)image[ th * width + tw ] );

        for ( short si = 0; si < BEST; ++ si ) {
            if ( d[si] == -1 || diff < d[si] ) {
                d[si] = diff;
                s[si][0] = tw;
                s[si][1] = th;
                break;//<-- this line causes 4 (!) times slow down
            }
        }
    } }

    //copy results from private memory to global:
    const long p = ( x * height + y ) * BEST;
    for ( short b = 0; b < BEST; ++ b ) {
        const long pb = ( p + b ) * 2;
        best[ pb     ] = s[b][0];
        best[ pb + 1 ] = s[b][1];
    }
}

The problem was that it took GPU 3593ms for 2560*1440 image which is almost exactly the same time as plain C++ CPU code I had before (~8500ms). Then I tried to tune it here and there and occasionally removed break; line and execution time -> 900ms!

What's the reason behind such surprising speed up? That break; line just tells program it's not needed to check any other pixels further so supposed to decrease execution time - not slow it down? Maybe there are some other ways to speed up this program too? :)

Body:
Try to maintain memory access order, just before global writing

 // here
 barrier(CLK_GLOBAL_MEM_FENCE);

 //copy results from private memory to global:
 const long p = ( x * height + y ) * BEST;

if your performance problem is originating from memory access pattern, this should ease it.

If problem comes from just branching between threads, then you can also try maintaining order within the second loop after innermost loop:

for ( short si = 0; si < BEST; ++ si ) {
            if ( d[si] == -1 || diff < d[si] ) {
                d[si] = diff;
                s[si][0] = tw;
                s[si][1] = th;
                break;
            }
        }
barrier(CLK_LOCAL_MEM_FENCE); // local => should be faster for many devices

so that in every iteration, all neighboring threads rejoin together and continue executing same instructions until a new break breaks the order.

Lastly, algorithm seems like sorting pixel value differences between SURROUND pixels, by decreasing values. So, the innermost loop could actually be moved to outermost and have all the branching be minimized, just after innermost two new loops(which were outermost before). But this increases image[ th * width + tw ] reading by BEST times so it can be slower too(maybe not when data moved to local memory before this). But, d does not need to be an array now so BEST number of private registers are saved and could give it some performance boost by decreasing register pressure.


问:
Entering custom data into GraphiQL Docs
I would like to use GraphiQL docs to document my GraphQL API. The out-of-the-box version already looks pretty useful, however I would like to enrich it by the information about permissions.

My imagination is that in this

there will be another section, i.e. "Permissions", with some description of the permissions.

My question: is this the way to do it? If not, how can one express permissions in the GraphiQL Docs? And if this could be the way, is there any tool capable of doing this?

答:
What's shown in GraphiQL (or similar tools like GraphQL Playground, Altair, etc.) is limited to what can be returned through introspection of the schema, which is limited by what the spec specifies. You can add descriptions to types, fields, arguments, enum values and directives. A description for the schema itself is in the works.

At best, you could add a description to your field specifying the permissions. You can use markdown if you want to jazz it up.

Title: Entering custom data into GraphiQL Docs


问:
Vue.js Compile Error: no-unused-vars & no-undef
I'm currently trying to create a Vue.js component. When I start the app there's an error.
The error message as shown below:

```<code><template>
    <div class="hello" id="app">
         <span style="font-size:30px;cursor:pointer;" onclick="openNav()">☰</span>

        <div id="mySidenav" class="sidenav">
            <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>
            <a href="#">{{name1}}</a>
            <a href="#">{{name2}}</a>
            <a href="#">{{name3}}</a>
            <a href="#">{{name4}}</a>

            <div id="bottom">
                <input v-model="name1" style="margin-left: 25px;max-width: 50%;">
                <input v-model="name2" style="margin-left: 25px;max-width: 50%;">
                <input v-model="name3" style="margin-left: 25px;max-width: 50%;">
                <input v-model="name4" style="margin-left: 25px;max-width: 50%;">
            </div>

        </div>
        <h2>Lorem ipsum dolor sit amet</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque elit velit, dictum in urna et,
            vulputate ornare sapien. Phasellus sed metus sed dolor hendrerit iaculis.
            Cras eget libero sit amet massa aliquet dignissim. Vivamus faucibus lorem sit amet semper luctus.
            Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. In at placerat
            felis,
            id finibus mauris. Proin maximus orci quis lacus pellentesque, ac dignissim sapien vestibulum. Maecenas
            pharetra
            vulputate semper.
            Suspendisse potenti. Donec nisi nisi, aliquam eget felis euismod, semper dictum ligula.
            Aenean mauris enim, iaculis vel malesuada vel, pulvinar et risus. Fusce sit amet orci eget diam commodo
            ultricies sed vel elit.
            Curabitur quis scelerisque est.</p>
    </div>
</template>

<script>
    //Vue App
    var app = new Vue({
        el: '#app',
        data: {
            /*
            navlink: [
                {id: 1, link: "https://www.tfbern.ch"},
                {id: 2, link: "https://www.tfbern.ch"},
                {id: 3, link: "https://www.tfbern.ch"},
                {id: 4, link: "https://www.tfbern.ch"}
                ]
            */

            name1: 'name 1',
            name2: 'name 2',
            name3: 'name 3',
            name4: 'name 4'
        }
    })
    export default {
        name: 'NavigationDrawer',
        props: {
            msg: String
        }
    }

    //Navbar Animation
   /*
   function openNav() {
        document.getElementById("mySidenav").style.width = "250px";
    }

    function closeNav() {
        document.getElementById("mySidenav").style.width = "0"; -->
    }
     */
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>
</code>```

Navigation-Drawer.vue

```<code><template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
    <HelloWorld msg="Welcome to Your Vue.js App"/>
    <App msg="test">
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'
import App from './components/Navigation-Drawer.vue'
export default {
  name: 'App',
  components: {
    HelloWorld,
    App
  }
}

</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
</code>```

App.vue

答:
The CLI should have created a file called main.js. In there you'll have something a bit like this that creates a new Vue instance:

new Vue({
  render: h => h(App)
}).mount('#app')
```

<p>It might use an <code>el</code> property instead of calling <code>mount</code> and it may mention <code>store</code> or <code>router</code> if you chose to include those when creating the project. It doesn't really matter, the key thing is that this is where the root Vue instance gets created. Unless you're writing an atypical application you shouldn't need to use <code>new Vue</code> again. You certainly shouldn't be using it inside a <code>.vue</code> file.</p>

<p>The <code>App</code> referenced in the code I wrote above should be the component in <code>App.vue</code>, which should be imported earlier in <code>main.js</code>.</p>

<p>Then there's your <code>App.vue</code>. This line is a bit odd:</p>

<pre class="lang-js prettyprint-override"><code>import App from './components/Navigation-Drawer.vue'
</code>```

Technically it isn't wrong but it's really confusing. Rename App to some a bit more sensible, like NavigationDrawer. You'll need to update everywhere it's used, including the template.

Next up, Navigation-Drawer.vue. There are several problems here.

Firstly, get rid of the id="app" on the template, that just shouldn't be there and may cause problems.

To implement onclick="openNav()" in Vue you'd instead write @click="openNav" and then define openNav within the methods section of the component.

The script section should look something like this:

```

Hopefully that'll be enough to get it all working.

The original linting errors were caused because:

You were creating a variable called app but never using it.

You were trying to call new Vue but hadn't imported Vue. In general you need to import things if you want to be able to access them from inside a .vue file.

However, the linting errors were just side-effects of the more serious problems I've outlined above.

Body:
I'm currently trying to create a Vue.js component. When I start the app there's an error.
The error message as shown below:

<template>

         ☰

            ×
            {{name1}}
            {{name2}}
            {{name3}}
            {{name4}}

                <input v-model="name1" style="margin-left: 25px;max-width: 50%;">
                <input v-model="name2" style="margin-left: 25px;max-width: 50%;">
                <input v-model="name3" style="margin-left: 25px;max-width: 50%;">
                <input v-model="name4" style="margin-left: 25px;max-width: 50%;">

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque elit velit, dictum in urna et,
            vulputate ornare sapien. Phasellus sed metus sed dolor hendrerit iaculis.
            Cras eget libero sit amet massa aliquet dignissim. Vivamus faucibus lorem sit amet semper luctus.
            Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. In at placerat
            felis,
            id finibus mauris. Proin maximus orci quis lacus pellentesque, ac dignissim sapien vestibulum. Maecenas
            pharetra
            vulputate semper.
            Suspendisse potenti. Donec nisi nisi, aliquam eget felis euismod, semper dictum ligula.
            Aenean mauris enim, iaculis vel malesuada vel, pulvinar et risus. Fusce sit amet orci eget diam commodo
            ultricies sed vel elit.
            Curabitur quis scelerisque est.

</template>

Navigation-Drawer.vue

<template>

    <HelloWorld msg="Welcome to Your Vue.js App"/>
    <App msg="test">

</template>

App.vue

Body:
The CLI should have created a file called main.js. In there you'll have something a bit like this that creates a new Vue instance:

new Vue({
  render: h => h(App)
}).mount('#app')

It might use an el property instead of calling mount and it may mention store or router if you chose to include those when creating the project. It doesn't really matter, the key thing is that this is where the root Vue instance gets created. Unless you're writing an atypical application you shouldn't need to use new Vue again. You certainly shouldn't be using it inside a .vue file.

The App referenced in the code I wrote above should be the component in App.vue, which should be imported earlier in main.js.

Then there's your App.vue. This line is a bit odd:

import App from './components/Navigation-Drawer.vue'

Technically it isn't wrong but it's really confusing. Rename App to some a bit more sensible, like NavigationDrawer. You'll need to update everywhere it's used, including the template.

Next up, Navigation-Drawer.vue. There are several problems here.

Firstly, get rid of the id="app" on the template, that just shouldn't be there and may cause problems.

To implement onclick="openNav()" in Vue you'd instead write @click="openNav" and then define openNav within the methods section of the component.

The script section should look something like this:

<script>
    export default {
        name: 'NavigationDrawer',

        props: {
            msg: String
        },

        // Note that this is a function when used on a component
        data () {
            return {
                name1: 'name 1',
                name2: 'name 2',
                name3: 'name 3',
                name4: 'name 4'
            }
        },

        methods: {
            openNav() {
                console.log('openNav called')
            },

            closeNav() {
                console.log('closeNav')
            }
        }
    }
</script>

Hopefully that'll be enough to get it all working.

The original linting errors were caused because:

You were creating a variable called app but never using it.

You were trying to call new Vue but hadn't imported Vue. In general you need to import things if you want to be able to access them from inside a .vue file.

However, the linting errors were just side-effects of the more serious problems I've outlined above.


问:
Angular / JS generate random Uniq Serial ID
I'm creating a function that generate a random Uniq Serial id by replacing a string with this format ; xxxx-xxxx-xxxx-xxxx , the goal is to get a serial like that : ABCD-1234-EFGH-5678 ,the first and third parts are a letters and the second and last parts are numbers, this is my code :

```<code>public generateUniqSerial() {
   return 'xxxx-xxxx-xxx-xxxx'.replace(/[x]/g, function (c) {
     let r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8)
     return v.toString(16)
   })
 }
</code>```

it give a result like that : "7f8f-0d9a-fd5-450f"
, how to edit this function to get a result with this format : ABCD-1234-EFGH-6789 ?

答:
You can do something like this to generate a random Uniq Serial id with a format like ABCD-1234-EFGH-5678:

function rnd(t) {
  let str = '';
  const min = t === 'a' ? 10 : 0;
  const max = t === 'n' ? 10 : 62;
  for (let i = 0; i++ < 4;) {
    let r = Math.random() * (max - min) + min << 0;
    str += String.fromCharCode(r += r > 9 ? r < 36 ? 55 : 61 : 48);
  }
  return str;
}

function generateUniqSerial() {
  return `${rnd('a')}-${rnd('n')}-${rnd('a')}-${rnd('n')}`
}

console.log(generateUniqSerial())
console.log(generateUniqSerial())```

Body:
I'm creating a function that generate a random Uniq Serial id by replacing a string with this format ; xxxx-xxxx-xxxx-xxxx , the goal is to get a serial like that : ABCD-1234-EFGH-5678 ,the first and third parts are a letters and the second and last parts are numbers, this is my code :

public generateUniqSerial() {
   return 'xxxx-xxxx-xxx-xxxx'.replace(/[x]/g, function (c) {
     let r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8)
     return v.toString(16)
   })
 }

it give a result like that : "7f8f-0d9a-fd5-450f"
, how to edit this function to get a result with this format : ABCD-1234-EFGH-6789 ?


问:
Optional return in C#.Net
Java 1.8 is receiving the Optional<T> class, that allows us to explicitly say when a method may return a null value and "force" its consumer to verify if it is not null (isPresent()) before using it.

I see C# has Nullable<T>, that does something similar, but with basic types. It seems to be used for DB queries, to distinguish when a value exists and is 0 from when it doesn't exist and is null.

But it seems that C#'s Nullable<T>doesn't work for objects, only for basic types, while Java's Optional<T> only works for objects and not for basic types.

Is there a Nullable/Optional class in C#, that forces us to test if object exists before extracting and using it?

答:
Use T? nullable reference instead  of Option<T>

Since C#8 you should deprecate custom Option<T>-implementations. The null dilemma is now completely resolved.

T? is a complete substitution for Option<T>

C# has the following features for handling null:

Null coalescing operator

Null conditional operator

Non nullable & nullable reference types (since C#8)

Configurable compile errors/warnings

Keep in mind that

```<code>Option<Car> optional = Option<Car>.Create(myCar);
string color = optional
  .Select(car => car.Color.Name)
  .DefaultIfEmpty("<no car>")
  .Single();  // you can call First(), too
</code>```

is the same as

```<code>string color = myCar?.Color.Name ?? "<no car>";
</code>```

and additionally the string color is also a reference that can't be null.

Title: Optional return in C#.Net

Body:
Use T? nullable reference instead  of Option<T>

Since C#8 you should deprecate custom Option<T>-implementations. The null dilemma is now completely resolved.

T? is a complete substitution for Option<T>

C# has the following features for handling null:

Null coalescing operator

Null conditional operator

Non nullable & nullable reference types (since C#8)

Configurable compile errors/warnings

Keep in mind that

Option<Car> optional = Option<Car>.Create(myCar);
string color = optional
  .Select(car => car.Color.Name)
  .DefaultIfEmpty("<no car>")
  .Single();  // you can call First(), too

is the same as

string color = myCar?.Color.Name ?? "<no car>";

and additionally the string color is also a reference that can't be null.


问:
Pattern matching with Alternative empty or Applicative pure
I know it is possible, to pattern match against (named) constructors like so:

f1 :: Maybe a -> Bool
f1 Nothing = False
f1 (Just x) = True -- in reality have something that uses x here

f2 :: [a] -> Int
f2 [] = False
f2 x = True
```

<p>How can I write such a function for general <code>Alternative</code>s similar to</p>

<pre class="lang-hs prettyprint-override"><code>f :: (Alternative m) => m a -> Bool
f empty = False
f x = True
</code>```

If I try this, I get the error Parse error in pattern: empty. Which makes sense, I guess, as empty as a function here and not a constructor. But how can I accomplish this for general Alternatives idiomatically?

Edit 1:
My actual goal is to define a Monad instance (and probably also a MonadPlus instance) for a custom result type. Instead of the basic Either Error Result type, it should support a Maybe Error (and if possible also other Alternatives like [Error]) as error type and also some Applicative as result type in order to support lazy evaluation, for example with the result type (Maybe Error, [Tokens]) of a tokenizer.

I'd like something similar to

instance (Alterantive mErr, Applicative mRes) => Monad (mErr e, mRes a) where
  return x = (empty, pure x)
  (empty, pure x) >>= f = f x
  (err, x) >>= f = (err, x)
```

答:
The best you can do is:</p>

```<code>f :: (Eq (m a), Alternative m) => m a -> Bool
f x | x == empty = False
    | otherwise = True
</code>```

Body:
I know it is possible, to pattern match against (named) constructors like so:

f1 :: Maybe a -> Bool
f1 Nothing = False
f1 (Just x) = True -- in reality have something that uses x here

f2 :: [a] -> Int
f2 [] = False
f2 x = True

How can I write such a function for general Alternatives similar to

f :: (Alternative m) => m a -> Bool
f empty = False
f x = True

If I try this, I get the error Parse error in pattern: empty. Which makes sense, I guess, as empty as a function here and not a constructor. But how can I accomplish this for general Alternatives idiomatically?

Edit 1:
My actual goal is to define a Monad instance (and probably also a MonadPlus instance) for a custom result type. Instead of the basic Either Error Result type, it should support a Maybe Error (and if possible also other Alternatives like [Error]) as error type and also some Applicative as result type in order to support lazy evaluation, for example with the result type (Maybe Error, [Tokens]) of a tokenizer.

I'd like something similar to

instance (Alterantive mErr, Applicative mRes) => Monad (mErr e, mRes a) where
  return x = (empty, pure x)
  (empty, pure x) >>= f = f x
  (err, x) >>= f = (err, x)

Body:
The best you can do is:

f :: (Eq (m a), Alternative m) => m a -> Bool
f x | x == empty = False
    | otherwise = True


问:
How to center a colorbar at a specific color for Seaborn Heatmap?
Is it possible to specify the color of center of colorbar in seaborn heatmap?
As example the ceneter of colorbar of the following heat map is 70, and I want to be specified with black color instead of white.
Thanks in advance.

the example heatmap

答:
You can use DivergingNorm to specify an off-centered normalization. To create the cmap with black in the center, use LinearSegmentedColormap

```<code>from matplotlib.colors import LinearSegmentedColormap, DivergingNorm

cmap = LinearSegmentedColormap.from_list('BkR',['blue','black','red'])
norm = DivergingNorm(vmin=0, vcenter=70, vmax=100)

x,y = np.random.randint(0,100, size=(2,50))

plt.figure()
plt.scatter(x,y,c=y, norm=norm, cmap=cmap)
plt.colorbar()
plt.show()
</code>```

Body:
You can use DivergingNorm to specify an off-centered normalization. To create the cmap with black in the center, use LinearSegmentedColormap

from matplotlib.colors import LinearSegmentedColormap, DivergingNorm

cmap = LinearSegmentedColormap.from_list('BkR',['blue','black','red'])
norm = DivergingNorm(vmin=0, vcenter=70, vmax=100)

x,y = np.random.randint(0,100, size=(2,50))

plt.figure()
plt.scatter(x,y,c=y, norm=norm, cmap=cmap)
plt.colorbar()
plt.show()