问:
Performance issue in combined where clauses
Question

I would like to know: How can I rewrite/alter my search query/strategy to get an acceptable performance for my end users?

The search

I'm implementing a search for our users, they are provided the ability to search for candidates on our system based on:

A professional group they fall into,

A location + radius,

A full text search.

The query

```<code>select v.id
    from (
        select
            c.id,
            c.ts_description,
            c.latitude,
            c.longitude,
            g.group
        from entities.candidates c
        join entities.candidates_connections cc on cc.candidates_id = c.id
        join system.groups g on cc.systems_id = g.id
    ) v

    -- Group selection
    where v.group = 'medical'

    -- Location + radius
    and earth_distance(ll_to_earth(v.latitude, v.longitude), ll_to_earth(50.87050439999999, -1.2191283)) < 48270

    -- Full text search
    and v.ts_description @@ to_tsquery('simple', 'nurse | doctor')
;
</code>```

Data size & benchmarks

I am working with 1.7 million records

I have the 3 conditions in order of impact which were benchmarked in isolation:

Group clause: 3s & reduces to 700k records

Location clause: 8s & reduces to 54k records

Full text clause: 60s+ & reduces to 10k records

When combined they seem to take 71s, which is the full impact of the 3 queries in isolation, my expectation was that when putting all 3 clauses together they would work sequentially i.e on the subset of data from the previous clause therefore the timing should reduce dramatically - but this has not happened.

What I've tried

All join conditions & where clauses are indexed

Notably the ts_description index (GIN) is 2GB

lat/lng is indexed with ll_to_earth() to reduce the impact inline

I nested each where clause into a different subquery in order

Changed the order of all clauses & subqueries

Increased the shared_buffers size to increase the potential cache hits

答:
It seems you do not need to subquery, and it is also a good practice to filter with numeric fields, so, instead of filtering with where v.group = 'medical' for example, create a dictionary and just filter with where v.group = 1

```<code>        select
            DISTINCT c.id,
        from entities.candidates c
        join entities.candidates_connections cc on cc.candidates_id = c.id
        join system.groups g on cc.systems_id = g.id
    where tablename.group = 1
    and earth_distance(ll_to_earth(v.latitude, v.longitude), ll_to_earth(50.87050439999999, -1.2191283)) < 48270
    and v.ts_description @@ to_tsquery(0, 1 | 2)
</code>```

also, use EXPLAIN ANALYSE to see and check your execution plan. These quick tips will help you improve it clearly.

Body:
Question

I would like to know: How can I rewrite/alter my search query/strategy to get an acceptable performance for my end users?

The search

I'm implementing a search for our users, they are provided the ability to search for candidates on our system based on:

A professional group they fall into,

A location + radius,

A full text search.

The query

select v.id
    from (
        select
            c.id,
            c.ts_description,
            c.latitude,
            c.longitude,
            g.group
        from entities.candidates c
        join entities.candidates_connections cc on cc.candidates_id = c.id
        join system.groups g on cc.systems_id = g.id
    ) v

    -- Group selection
    where v.group = 'medical'

    -- Location + radius
    and earth_distance(ll_to_earth(v.latitude, v.longitude), ll_to_earth(50.87050439999999, -1.2191283)) < 48270

    -- Full text search
    and v.ts_description @@ to_tsquery('simple', 'nurse | doctor')
;

Data size & benchmarks

I am working with 1.7 million records

I have the 3 conditions in order of impact which were benchmarked in isolation:

Group clause: 3s & reduces to 700k records

Location clause: 8s & reduces to 54k records

Full text clause: 60s+ & reduces to 10k records

When combined they seem to take 71s, which is the full impact of the 3 queries in isolation, my expectation was that when putting all 3 clauses together they would work sequentially i.e on the subset of data from the previous clause therefore the timing should reduce dramatically - but this has not happened.

What I've tried

All join conditions & where clauses are indexed

Notably the ts_description index (GIN) is 2GB

lat/lng is indexed with ll_to_earth() to reduce the impact inline

I nested each where clause into a different subquery in order

Changed the order of all clauses & subqueries

Increased the shared_buffers size to increase the potential cache hits

Body:
It seems you do not need to subquery, and it is also a good practice to filter with numeric fields, so, instead of filtering with where v.group = 'medical' for example, create a dictionary and just filter with where v.group = 1

        select
            DISTINCT c.id,
        from entities.candidates c
        join entities.candidates_connections cc on cc.candidates_id = c.id
        join system.groups g on cc.systems_id = g.id
    where tablename.group = 1
    and earth_distance(ll_to_earth(v.latitude, v.longitude), ll_to_earth(50.87050439999999, -1.2191283)) < 48270
    and v.ts_description @@ to_tsquery(0, 1 | 2)

also, use EXPLAIN ANALYSE to see and check your execution plan. These quick tips will help you improve it clearly.


来源: stackexchange

问:
how to fix the height of bars in flutter horizontal bar charts
In flutter charts, the horizontal chart automatically stretches according to the height of the screen. Is there any way through which I may fix the height of the bars so that it may not stretch to the entire screen?       </p>

答:
Simple add your chart in the ConstrainedBox like this -</p>

```<code>ConstrainedBox(
  constraints: BoxConstraints.expand(height: 200.0), // give the height according to you
   child : Your_Chart_here(), // your chart here
),
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Simple add your chart in the ConstrainedBox like this -

ConstrainedBox(
  constraints: BoxConstraints.expand(height: 200.0), // give the height according to you
   child : Your_Chart_here(), // your chart here
),


问:
How can assigning a variable result in a serious performance drop while the execution order is (nearly) untouched?
When playing around with multithreading, I could observe some unexpected but serious performance issues related to AtomicLong (and classes using it, such as java.util.Random), for which I currently have no explanation. However, I created a minimalistic example, which basically consists of two classes: a class "Container", which keeps a reference to a volatile variable, and a class "DemoThread", which operates on an instance of "Container" during thread execution. Note that the references to "Container" and the volatile long are private, and never shared between threads (I know that there's no need to use volatile here, it's just for demonstration purposes) - thus, multiple instances of "DemoThread" should run perfectly parallel on a multiprocessor machine, but for some reason, they do not (Complete example is at the bottom of this post).

```<code>private static class Container  {

    private volatile long value;

    public long getValue() {
        return value;
    }

    public final void set(long newValue) {
        value = newValue;
    }
}

private static class DemoThread extends Thread {

    private Container variable;

    public void prepare() {
        this.variable = new Container();
    }

    public void run() {
        for(int j = 0; j < 10000000; j++) {
            variable.set(variable.getValue() + System.nanoTime());
        }
    }
}
</code>```

During my test, I repeatedly create 4 DemoThreads, which are then started and joined. The only difference in each loop is the time when "prepare()" gets called (which is obviously required for the thread to run, as it otherwise would result in a NullPointerException):

```<code>DemoThread[] threads = new DemoThread[numberOfThreads];
    for(int j = 0; j < 100; j++) {
        boolean prepareAfterConstructor = j % 2 == 0;
        for(int i = 0; i < threads.length; i++) {
            threads[i] = new DemoThread();
            if(prepareAfterConstructor) threads[i].prepare();
        }

        for(int i = 0; i < threads.length; i++) {
            if(!prepareAfterConstructor) threads[i].prepare();
            threads[i].start();
        }
        joinThreads(threads);
    }
</code>```

For some reason, if prepare() is executed immediately before starting the thread, it will take twice as more time to finish, and even without the "volatile" keyword, the performance differences were significant, at  least on two of the machines and OS'es I tested the code. Here's a short summary:

Mac OS Summary:

Java Version: 1.6.0_24

Java Class Version: 50.0

VM Vendor: Sun Microsystems Inc.

VM Version: 19.1-b02-334

VM Name: Java HotSpot(TM) 64-Bit Server VM

OS Name: Mac OS X

OS Arch: x86_64

OS Version: 10.6.5

Processors/Cores: 8

With volatile keyword:

Final results:

31979 ms. when prepare() was called after instantiation.

96482 ms. when prepare() was called before execution.

Without volatile keyword:

Final results:

26009 ms. when prepare() was called after instantiation.

35196 ms. when prepare() was called before execution.

Windows Summary:

Java Version: 1.6.0_24

Java Class Version: 50.0

VM Vendor: Sun Microsystems Inc.

VM Version: 19.1-b02

VM Name: Java HotSpot(TM) 64-Bit Server VM

OS Name: Windows 7

OS Arch: amd64

OS Version: 6.1

Processors/Cores: 4

With volatile keyword:

Final results:

18120 ms. when prepare() was called after instantiation.

36089 ms. when prepare() was called before execution.

Without volatile keyword:

Final results:

10115 ms. when prepare() was called after instantiation.

10039 ms. when prepare() was called before execution.

Linux Summary:

Java Version: 1.6.0_20

Java Class Version: 50.0

VM Vendor: Sun Microsystems Inc.

VM Version: 19.0-b09

VM Name: OpenJDK 64-Bit Server VM

OS Name: Linux

OS Arch: amd64

OS Version: 2.6.32-28-generic

Processors/Cores: 4

With volatile keyword:

Final results:

45848 ms. when prepare() was called after instantiation.

110754 ms. when prepare() was called before execution.

Without volatile keyword:

Final results:

37862 ms. when prepare() was called after instantiation.

39357 ms. when prepare() was called before execution.

Mac OS Details (volatile):

Test 1, 4 threads, setting variable in creation loop

Thread-2 completed after 653 ms.

Thread-3 completed after 653 ms.

Thread-4 completed after 653 ms.

Thread-5 completed after 653 ms.

Overall time: 654 ms.

Test 2, 4 threads, setting variable in start loop

Thread-7 completed after 1588 ms.

Thread-6 completed after 1589 ms.

Thread-8 completed after 1593 ms.

Thread-9 completed after 1593 ms.

Overall time: 1594 ms.

Test 3, 4 threads, setting variable in creation loop

Thread-10 completed after 648 ms.

Thread-12 completed after 648 ms.

Thread-13 completed after 648 ms.

Thread-11 completed after 648 ms.

Overall time: 648 ms.

Test 4, 4 threads, setting variable in start loop

Thread-17 completed after 1353 ms.

Thread-16 completed after 1957 ms.

Thread-14 completed after 2170 ms.

Thread-15 completed after 2169 ms.

Overall time: 2172 ms.

(and so on, sometimes one or two of the threads in the 'slow' loop finish as expected, but most times they don't).

The given example looks theoretically, as it is of no use, and 'volatile' is not needed here - however, if you'd use a 'java.util.Random'-Instance instead of the 'Container'-Class and call, for instance, nextInt() multiple times, the same effects will occur: The thread will be executed fast if you create the object in the Thread's constructor, but slow if you create it within the run()-method. I believe that the performance issues described in Java Random Slowdowns on Mac OS more than a year ago are related to this effect, but I have no idea why it is as it is - besides that I'm sure that it shouldn't be like that, as it would mean that it's always dangerous to create a new object within the run-method of a thread, unless you know that no volatile variables will get involved within the object graph. Profiling doesn't help, as the problem disappears in this case (same observation as in Java Random Slowdowns on Mac OS cont'd), and it also does not happen on a single-core-PC - so I'd guess that it's kind of a thread synchronization problem... however, the strange thing is that there's actually nothing to synchronize, as all variables are thread-local.

Really looking forward for any hints - and just in case you want to confirm or falsify the problem, see the test case below.

Thanks,

Stephan

```<code>public class UnexpectedPerformanceIssue {

private static class Container  {

    // Remove the volatile keyword, and the problem disappears (on windows)
    // or gets smaller (on mac os)
    private volatile long value;

    public long getValue() {
        return value;
    }

    public final void set(long newValue) {
        value = newValue;
    }
}

private static class DemoThread extends Thread {

    private Container variable;

    public void prepare() {
        this.variable = new Container();
    }

    @Override
    public void run() {
        long start = System.nanoTime();
        for(int j = 0; j < 10000000; j++) {
            variable.set(variable.getValue() + System.nanoTime());
        }
        long end = System.nanoTime();
        System.out.println(this.getName() + " completed after "
                +  ((end - start)/1000000) + " ms.");
    }
}

public static void main(String[] args) {
    System.out.println("Java Version: " + System.getProperty("java.version"));
    System.out.println("Java Class Version: " + System.getProperty("java.class.version"));

    System.out.println("VM Vendor: " + System.getProperty("java.vm.specification.vendor"));
    System.out.println("VM Version: " + System.getProperty("java.vm.version"));
    System.out.println("VM Name: " + System.getProperty("java.vm.name"));

    System.out.println("OS Name: " + System.getProperty("os.name"));
    System.out.println("OS Arch: " + System.getProperty("os.arch"));
    System.out.println("OS Version: " + System.getProperty("os.version"));
    System.out.println("Processors/Cores: " + Runtime.getRuntime().availableProcessors());

    System.out.println();
    int numberOfThreads = 4;

    System.out.println("\nReference Test (single thread):");
    DemoThread t = new DemoThread();
    t.prepare();
    t.run();

    DemoThread[] threads = new DemoThread[numberOfThreads];
    long createTime = 0, startTime = 0;
    for(int j = 0; j < 100; j++) {
        boolean prepareAfterConstructor = j % 2 == 0;
        long overallStart = System.nanoTime();
        if(prepareAfterConstructor) {
            System.out.println("\nTest " + (j+1) + ", " + numberOfThreads + " threads, setting variable in creation loop");
        } else {
            System.out.println("\nTest " + (j+1) + ", " + numberOfThreads + " threads, setting variable in start loop");
        }

        for(int i = 0; i < threads.length; i++) {
            threads[i] = new DemoThread();
            // Either call DemoThread.prepare() here (in odd loops)...
            if(prepareAfterConstructor) threads[i].prepare();
        }

        for(int i = 0; i < threads.length; i++) {
            // or here (in even loops). Should make no difference, but does!
            if(!prepareAfterConstructor) threads[i].prepare();
            threads[i].start();
        }
        joinThreads(threads);
        long overallEnd = System.nanoTime();
        long overallTime = (overallEnd - overallStart);
        if(prepareAfterConstructor) {
            createTime += overallTime;
        } else {
            startTime += overallTime;
        }
        System.out.println("Overall time: " + (overallTime)/1000000 + " ms.");
    }
    System.out.println("Final results:");
    System.out.println(createTime/1000000 + " ms. when prepare() was called after instantiation.");
    System.out.println(startTime/1000000 + " ms. when prepare() was called before execution.");
}

private static void joinThreads(Thread[] threads) {
    for(int i = 0; i < threads.length; i++) {
        try {
            threads[i].join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
</code>```

}

答:
I am not an expert in the internals of Java, but I read your question and find it fascinating. If I had to guess, I think what you have discovered:

Does NOT have anything to do with the instantiation of the volitale property. However, from your data, where the property gets instantiated affects how expensive it is to read/write to it.

Does have to do with finding the reference of the volitale property at runtime. That is, I would be interested to see how the delay grows with more threads that loop more often. Is the number of calls to the volitale property what is causing the delay, or the addition itself, or the writing of the new value.

I would have to guess that: there is probably a JVM optimization that attempts to quickly instantiate the property, and later, if there is time, to alter the property in memory so it is easier to read/write to it. Maybe there is a (1) quick-to-create read/write queue for volitale properties, and a (2) hard-to-create but quick to call queue, and the JVM begins with (1) and later alters the volitale property to (2).

Perhaps if you prepare() right before the run() method gets called, the JVM does not have enough free cycles to optimize from (1) to (2).

The way to test this answer would be to:

prepare(), sleep(), run() and see if you get the same delay. If the sleep is the only thing that is causing for the optimization to take place, then it could mean the JVM needs cycles to optimize the volitale property

OR (a bit more risky) ...

prepare() and run() the threads, later in the middle of the loop, to either pause() or sleep() or somehow stop access to the property in a way that the JVM can attempt to move it to (2).

I'd be interested to see what you find out. Interesting question.

ContentLicense: CC BY-SA 3.0

Body:
When playing around with multithreading, I could observe some unexpected but serious performance issues related to AtomicLong (and classes using it, such as java.util.Random), for which I currently have no explanation. However, I created a minimalistic example, which basically consists of two classes: a class "Container", which keeps a reference to a volatile variable, and a class "DemoThread", which operates on an instance of "Container" during thread execution. Note that the references to "Container" and the volatile long are private, and never shared between threads (I know that there's no need to use volatile here, it's just for demonstration purposes) - thus, multiple instances of "DemoThread" should run perfectly parallel on a multiprocessor machine, but for some reason, they do not (Complete example is at the bottom of this post).

private static class Container  {

    private volatile long value;

    public long getValue() {
        return value;
    }

    public final void set(long newValue) {
        value = newValue;
    }
}

private static class DemoThread extends Thread {

    private Container variable;

    public void prepare() {
        this.variable = new Container();
    }

    public void run() {
        for(int j = 0; j < 10000000; j++) {
            variable.set(variable.getValue() + System.nanoTime());
        }
    }
}

During my test, I repeatedly create 4 DemoThreads, which are then started and joined. The only difference in each loop is the time when "prepare()" gets called (which is obviously required for the thread to run, as it otherwise would result in a NullPointerException):

DemoThread[] threads = new DemoThread[numberOfThreads];
    for(int j = 0; j < 100; j++) {
        boolean prepareAfterConstructor = j % 2 == 0;
        for(int i = 0; i < threads.length; i++) {
            threads[i] = new DemoThread();
            if(prepareAfterConstructor) threads[i].prepare();
        }

        for(int i = 0; i < threads.length; i++) {
            if(!prepareAfterConstructor) threads[i].prepare();
            threads[i].start();
        }
        joinThreads(threads);
    }

For some reason, if prepare() is executed immediately before starting the thread, it will take twice as more time to finish, and even without the "volatile" keyword, the performance differences were significant, at  least on two of the machines and OS'es I tested the code. Here's a short summary:

Mac OS Summary:

Java Version: 1.6.0_24

Java Class Version: 50.0

VM Vendor: Sun Microsystems Inc.

VM Version: 19.1-b02-334

VM Name: Java HotSpot(TM) 64-Bit Server VM

OS Name: Mac OS X

OS Arch: x86_64

OS Version: 10.6.5

Processors/Cores: 8

With volatile keyword:

Final results:

31979 ms. when prepare() was called after instantiation.

96482 ms. when prepare() was called before execution.

Without volatile keyword:

Final results:

26009 ms. when prepare() was called after instantiation.

35196 ms. when prepare() was called before execution.

Windows Summary:

Java Version: 1.6.0_24

Java Class Version: 50.0

VM Vendor: Sun Microsystems Inc.

VM Version: 19.1-b02

VM Name: Java HotSpot(TM) 64-Bit Server VM

OS Name: Windows 7

OS Arch: amd64

OS Version: 6.1

Processors/Cores: 4

With volatile keyword:

Final results:

18120 ms. when prepare() was called after instantiation.

36089 ms. when prepare() was called before execution.

Without volatile keyword:

Final results:

10115 ms. when prepare() was called after instantiation.

10039 ms. when prepare() was called before execution.

Linux Summary:

Java Version: 1.6.0_20

Java Class Version: 50.0

VM Vendor: Sun Microsystems Inc.

VM Version: 19.0-b09

VM Name: OpenJDK 64-Bit Server VM

OS Name: Linux

OS Arch: amd64

OS Version: 2.6.32-28-generic

Processors/Cores: 4

With volatile keyword:

Final results:

45848 ms. when prepare() was called after instantiation.

110754 ms. when prepare() was called before execution.

Without volatile keyword:

Final results:

37862 ms. when prepare() was called after instantiation.

39357 ms. when prepare() was called before execution.

Mac OS Details (volatile):

Test 1, 4 threads, setting variable in creation loop

Thread-2 completed after 653 ms.

Thread-3 completed after 653 ms.

Thread-4 completed after 653 ms.

Thread-5 completed after 653 ms.

Overall time: 654 ms.

Test 2, 4 threads, setting variable in start loop

Thread-7 completed after 1588 ms.

Thread-6 completed after 1589 ms.

Thread-8 completed after 1593 ms.

Thread-9 completed after 1593 ms.

Overall time: 1594 ms.

Test 3, 4 threads, setting variable in creation loop

Thread-10 completed after 648 ms.

Thread-12 completed after 648 ms.

Thread-13 completed after 648 ms.

Thread-11 completed after 648 ms.

Overall time: 648 ms.

Test 4, 4 threads, setting variable in start loop

Thread-17 completed after 1353 ms.

Thread-16 completed after 1957 ms.

Thread-14 completed after 2170 ms.

Thread-15 completed after 2169 ms.

Overall time: 2172 ms.

(and so on, sometimes one or two of the threads in the 'slow' loop finish as expected, but most times they don't).

The given example looks theoretically, as it is of no use, and 'volatile' is not needed here - however, if you'd use a 'java.util.Random'-Instance instead of the 'Container'-Class and call, for instance, nextInt() multiple times, the same effects will occur: The thread will be executed fast if you create the object in the Thread's constructor, but slow if you create it within the run()-method. I believe that the performance issues described in Java Random Slowdowns on Mac OS more than a year ago are related to this effect, but I have no idea why it is as it is - besides that I'm sure that it shouldn't be like that, as it would mean that it's always dangerous to create a new object within the run-method of a thread, unless you know that no volatile variables will get involved within the object graph. Profiling doesn't help, as the problem disappears in this case (same observation as in Java Random Slowdowns on Mac OS cont'd), and it also does not happen on a single-core-PC - so I'd guess that it's kind of a thread synchronization problem... however, the strange thing is that there's actually nothing to synchronize, as all variables are thread-local.

Really looking forward for any hints - and just in case you want to confirm or falsify the problem, see the test case below.

Thanks,

Stephan

public class UnexpectedPerformanceIssue {

private static class Container  {

    // Remove the volatile keyword, and the problem disappears (on windows)
    // or gets smaller (on mac os)
    private volatile long value;

    public long getValue() {
        return value;
    }

    public final void set(long newValue) {
        value = newValue;
    }
}

private static class DemoThread extends Thread {

    private Container variable;

    public void prepare() {
        this.variable = new Container();
    }

    @Override
    public void run() {
        long start = System.nanoTime();
        for(int j = 0; j < 10000000; j++) {
            variable.set(variable.getValue() + System.nanoTime());
        }
        long end = System.nanoTime();
        System.out.println(this.getName() + " completed after "
                +  ((end - start)/1000000) + " ms.");
    }
}

public static void main(String[] args) {
    System.out.println("Java Version: " + System.getProperty("java.version"));
    System.out.println("Java Class Version: " + System.getProperty("java.class.version"));

    System.out.println("VM Vendor: " + System.getProperty("java.vm.specification.vendor"));
    System.out.println("VM Version: " + System.getProperty("java.vm.version"));
    System.out.println("VM Name: " + System.getProperty("java.vm.name"));

    System.out.println("OS Name: " + System.getProperty("os.name"));
    System.out.println("OS Arch: " + System.getProperty("os.arch"));
    System.out.println("OS Version: " + System.getProperty("os.version"));
    System.out.println("Processors/Cores: " + Runtime.getRuntime().availableProcessors());

    System.out.println();
    int numberOfThreads = 4;

    System.out.println("\nReference Test (single thread):");
    DemoThread t = new DemoThread();
    t.prepare();
    t.run();

    DemoThread[] threads = new DemoThread[numberOfThreads];
    long createTime = 0, startTime = 0;
    for(int j = 0; j < 100; j++) {
        boolean prepareAfterConstructor = j % 2 == 0;
        long overallStart = System.nanoTime();
        if(prepareAfterConstructor) {
            System.out.println("\nTest " + (j+1) + ", " + numberOfThreads + " threads, setting variable in creation loop");
        } else {
            System.out.println("\nTest " + (j+1) + ", " + numberOfThreads + " threads, setting variable in start loop");
        }

        for(int i = 0; i < threads.length; i++) {
            threads[i] = new DemoThread();
            // Either call DemoThread.prepare() here (in odd loops)...
            if(prepareAfterConstructor) threads[i].prepare();
        }

        for(int i = 0; i < threads.length; i++) {
            // or here (in even loops). Should make no difference, but does!
            if(!prepareAfterConstructor) threads[i].prepare();
            threads[i].start();
        }
        joinThreads(threads);
        long overallEnd = System.nanoTime();
        long overallTime = (overallEnd - overallStart);
        if(prepareAfterConstructor) {
            createTime += overallTime;
        } else {
            startTime += overallTime;
        }
        System.out.println("Overall time: " + (overallTime)/1000000 + " ms.");
    }
    System.out.println("Final results:");
    System.out.println(createTime/1000000 + " ms. when prepare() was called after instantiation.");
    System.out.println(startTime/1000000 + " ms. when prepare() was called before execution.");
}

private static void joinThreads(Thread[] threads) {
    for(int i = 0; i < threads.length; i++) {
        try {
            threads[i].join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

}


问:
Referencing inserted ID in multiple insert transactions in Postgres
I need to build a SQL query that must be able to insert data in a first table, grab the inserted ID and then use it as foreign key in the following tables.

```<code>WITH inserted AS (
    INSERT INTO firstTable (name) VALUES ('somename') RETURNING id
)

SELECT * FROM inserted; -- this has the inserted id

INSERT INTO secondTable (name, foreign_id) VALUES ('someexternalname', ???)
</code>```

So how do I reference the id in inserted in the secondTable insert?

答:
You can do this:</p>

```<code>WITH inserted AS (
    INSERT INTO firstTable (name) VALUES ('somename') RETURNING id
)

INSERT INTO secondTable (name, foreign_id)
SELECT
'someexternalname',
id
FROM inserted;
</code>```

Body:
I need to build a SQL query that must be able to insert data in a first table, grab the inserted ID and then use it as foreign key in the following tables.

WITH inserted AS (
    INSERT INTO firstTable (name) VALUES ('somename') RETURNING id
)

SELECT * FROM inserted; -- this has the inserted id

INSERT INTO secondTable (name, foreign_id) VALUES ('someexternalname', ???)

So how do I reference the id in inserted in the secondTable insert?

Body:
You can do this:

WITH inserted AS (
    INSERT INTO firstTable (name) VALUES ('somename') RETURNING id
)

INSERT INTO secondTable (name, foreign_id)
SELECT
'someexternalname',
id
FROM inserted;


答:
You have completed this 80% percent, the complete SQL is:</p>

```<code>with inserted as (
 insert into first_table(name) values ('somename') returning id
)
insert into second_table(name, foreign_id) select 'someexternalname',id from inserted
</code>```

Title: Referencing inserted ID in multiple insert transactions in Postgres

Body:
You have completed this 80% percent, the complete SQL is:

with inserted as (
 insert into first_table(name) values ('somename') returning id
)
insert into second_table(name, foreign_id) select 'someexternalname',id from inserted


问:
UIGesturerecognizer is not working on UIView
When I am tapping on UIView but Gesture is not working.

```<code>override func viewDidLoad() {
        super.viewDidLoad()

        let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
        viewForSHadow.isUserInteractionEnabled = true
        viewForSHadow.addGestureRecognizer(tap)

        // Do any additional setup after loading the view.
    }

func handleTap(_sender: UITapGestureRecognizer) {
        print("---------View Tapped--------")
        viewForSHadow.isHidden = true
        viewForAlert.isHidden = true
    }

</code>```

I just want to perform this action on UIView tap.

答:
Your code is more than enough to have working UIGestureRecognizer, you should check some other stuff like, is there something else that can consume the user interaction. And also to check if you use

isUserInteractionEnabled = false

to some parent view of viewForSHadow.

Body:
When I am tapping on UIView but Gesture is not working.

override func viewDidLoad() {
        super.viewDidLoad()

        let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
        viewForSHadow.isUserInteractionEnabled = true
        viewForSHadow.addGestureRecognizer(tap)

        // Do any additional setup after loading the view.
    }

func handleTap(_sender: UITapGestureRecognizer) {
        print("---------View Tapped--------")
        viewForSHadow.isHidden = true
        viewForAlert.isHidden = true
    }

I just want to perform this action on UIView tap.


问:
Javascript/PHP Family Tree Builder with Multiple Parents
Is there an existing PHP, Javascript, or even command line tool that can build a family tree in HTML (preferably) or at the very least create an image for it?  Multiple parents are a requirement.  I have been googling this for hours, but to no avail.

For instance, the Google Organizational Chart would be ideal, but it only allows each node to have at most one parent.  I need two parents to be possible.

Whatever this website does would also be perfect: http://www.familyecho.com/, but it seems to not be done with javascript and they don't publish the code that actually creates the visualization.

Even connecting to an external website to use their API to generate a visualization would be perfect.

答:
You might be interested in Raphaël, especially this demo.

Edit: I just came across a couple other promising-looking options from this question.

Protovis - I knew about this one when I first answered, but didn't think of it at the time. It's really flexible. Check out the examples.

Dracula Graph - haven't tried it. It might be too simple for your uses.


问:
Unable to install mysqlclient for mac on mojave
I am using Python + Django + MySql in my web application.
Whenever I tried to install mysqlclient I getting mutliple errors.

Now I am stuck on this:

when I ran
pip install mysqlclient I am getting following error:

Error Text Logs : https://pastebin.com/VrTGgpnr

答:
You can use the official MySQL Connector/Python.

```<code>pip install mysql-connector-python
</code>```

You don't need to install OpenSSL or any other library.

More details about installation https://dev.mysql.com/doc/dev/connector-python/8.0/installation.html

Here's how to configure your app: https://dev.mysql.com/doc/connector-python/en/connector-python-django-backend.html

Body:
You can use the official MySQL Connector/Python.

pip install mysql-connector-python

You don't need to install OpenSSL or any other library.

More details about installation https://dev.mysql.com/doc/dev/connector-python/8.0/installation.html

Here's how to configure your app: https://dev.mysql.com/doc/connector-python/en/connector-python-django-backend.html


问:
Can not connect to remote database
Local config:
Node.js 12.2.0

Server config:
VPS
Ubuntu 18.04
MongoDB 3.2.22

There is basic script to connect to remote mongodb database. This returns error -  Cannot read property 'db' of null.

There are admin and test databases.
For admin DB I created an user

```<code>db.createUser(
  {
    user: "root",
    pwd: "passw0rd",
    roles: [ { role: "root", db: "admin" } ]
  }
)

</code>```

node app.js

```<code>// app.js

const MongoClient = require("mongodb").MongoClient;

// const url = "mongodb://root:passw0rd@46.173.213.195:27017/admin";
const url = "mongodb://46.173.213.195:27017/test";
const mongoClient = new MongoClient(url, { useNewUrlParser: true });

mongoClient.connect(function(err, client){
    const db = client.db("admin");
    const collection = db.collection("users");
    let user = {name: "Tomy", age: 23};
    collection.insertOne(user, function(err, result){
        if(err){
            return console.log(err);
        }
        console.log(result.ops);
        client.close();
    });
});
</code>```

```<code>// package.json

{
   "name": "mongoapp",
   "version": "1.0.0",
   "dependencies": {
      "express": "^4.16.0",
      "body-parser": "^1.18.0",
      "mongodb": "^3.1.0"
   }
}
</code>```

Both urls returns errors.

What I tried:

Changed bindIp to any

```<code>///nano etc/mongod.conf

# network interfaces
net:
  port: 27017
#  bindIp: 127.0.0.1
  bindIp: 0.0.0.0

</code>```

sudo netstat -ntlp | grep LISTEN

```<code>tcp    0    0 0.0.0.0:27017      0.0.0.0:*    LISTEN      17184/mongod
...
...
</code>```

Applied this code for iptables

```<code>iptables -A INPUT -s 185.228.232.150 -p tcp --destination-port 27017 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -d 185.228.232.150 -p tcp --source-port 27017 -m state --state ESTABLISHED -j ACCEPT
</code>```

sudo systemctl status mongodb tells that db works good

Can anyone help?..
The code can be tested from your computer.

Update:
Accoringly to that post https://www.mkyong.com/mongodb/mongodb-bind-failed-errno99-cannot-assign-requested-address-for-socket/ bindIp shouldn't be equals to server IP.

答:
Your DB is running well and so does application. Problem is in application to DB network communication. Please check for the below points (assuming your DB is running on 46.173.213.195)

DB host: Check if necessary inbound rules are defined properly in your remote database host. That mean DB host is allowing port 27017 from application IP etc.

DB host: Change Bind ip to 46.173.213.195

Application host: Telnet 46.173.213.195:27017.

Now if your telnet is successful, application should be able to communicate remote DB too.

Title: Can not connect to remote database

Body:
Local config:
Node.js 12.2.0

Server config:
VPS
Ubuntu 18.04
MongoDB 3.2.22

There is basic script to connect to remote mongodb database. This returns error -  Cannot read property 'db' of null.

There are admin and test databases.
For admin DB I created an user

db.createUser(
  {
    user: "root",
    pwd: "passw0rd",
    roles: [ { role: "root", db: "admin" } ]
  }
)

node app.js

// app.js

const MongoClient = require("mongodb").MongoClient;

// const url = "mongodb://root:passw0rd@46.173.213.195:27017/admin";
const url = "mongodb://46.173.213.195:27017/test";
const mongoClient = new MongoClient(url, { useNewUrlParser: true });

mongoClient.connect(function(err, client){
    const db = client.db("admin");
    const collection = db.collection("users");
    let user = {name: "Tomy", age: 23};
    collection.insertOne(user, function(err, result){
        if(err){
            return console.log(err);
        }
        console.log(result.ops);
        client.close();
    });
});

// package.json

{
   "name": "mongoapp",
   "version": "1.0.0",
   "dependencies": {
      "express": "^4.16.0",
      "body-parser": "^1.18.0",
      "mongodb": "^3.1.0"
   }
}

Both urls returns errors.

What I tried:

Changed bindIp to any

///nano etc/mongod.conf

# network interfaces
net:
  port: 27017
#  bindIp: 127.0.0.1
  bindIp: 0.0.0.0

sudo netstat -ntlp | grep LISTEN

tcp    0    0 0.0.0.0:27017      0.0.0.0:*    LISTEN      17184/mongod
...
...

Applied this code for iptables

iptables -A INPUT -s 185.228.232.150 -p tcp --destination-port 27017 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -d 185.228.232.150 -p tcp --source-port 27017 -m state --state ESTABLISHED -j ACCEPT

sudo systemctl status mongodb tells that db works good

Can anyone help?..
The code can be tested from your computer.

Update:
Accoringly to that post https://www.mkyong.com/mongodb/mongodb-bind-failed-errno99-cannot-assign-requested-address-for-socket/ bindIp shouldn't be equals to server IP.


问:
Add one character before every special character in a string in javascript
I want to add one character for every special character in a string by regular expression i tried below expression but it is adding after the special character.

I expect the output to add one character for every special character in a string.

```<code>var string1="aaa!dd,"
var expressionResult = text.replace(/([\/,!?_])/g, '/');
</code>```

the output should be aaa/!dd/,

答:
You can use back reference to the group $& MDN ref

var string1="aaa!dd,"
var expressionResult = string1.replace(/[\/,!?_]/g, '/$&');

console.log(expressionResult)```
</div>
</div>
</p>

<p>By special character if you mean everything else than alphabet and digits than you can change your regex to </p>

```[^a-z\d]  - Match anything except alphabet and digit
```

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var string1="aaa!dd,"
var expressionResult = string1.replace(/[^a-z\d]/g, '/$&');

console.log(expressionResult)</code>```

Body:
I want to add one character for every special character in a string by regular expression i tried below expression but it is adding after the special character.

I expect the output to add one character for every special character in a string.

var string1="aaa!dd,"
var expressionResult = text.replace(/([\/,!?_])/g, '/');

the output should be aaa/!dd/,

Body:
You can use back reference to the group $& MDN ref

var string1="aaa!dd,"
var expressionResult = string1.replace(/[\/,!?_]/g, '/$&');

console.log(expressionResult)

By special character if you mean everything else than alphabet and digits than you can change your regex to

[^a-z\d]  - Match anything except alphabet and digit

var string1="aaa!dd,"
var expressionResult = string1.replace(/[^a-z\d]/g, '/$&');

console.log(expressionResult)


问:
How to get email checkbox checked by default?
I have defined connection alternatives for email and SMS. I want to have email checked by default.
I wondered if I can add attribute checked in Razor without changing model or controller.
Because if I use plain HTML, then it works but with Razor and when I inspection the page, there is no checked attribute.

```<code>@checked = "checked"
@checked = checked
@checked = "true"
@checked = true
new{@checked = "checked"}

<div class="checkbox-wrapper">
                    <label>
                        @Html.CheckBoxFor(m => m.Email, new { @class = "form-check-input", id = "E-post", @checked = "checked" })
                        <label for="E-post">E-post</label>
                    </label>
                </div>
</code>```

email checkbox checked when the page is loaded

答:
In your controller action,set Model.Email=true;.

this link might help you, set a CheckBox by default Checked

Body:
I have defined connection alternatives for email and SMS. I want to have email checked by default.
I wondered if I can add attribute checked in Razor without changing model or controller.
Because if I use plain HTML, then it works but with Razor and when I inspection the page, there is no checked attribute.

@checked = "checked"
@checked = checked
@checked = "true"
@checked = true
new{@checked = "checked"}

                        @Html.CheckBoxFor(m => m.Email, new { @class = "form-check-input", id = "E-post", @checked = "checked" })
                        E-post

email checkbox checked when the page is loaded


问:
Any cocoa source code for AES encryption decryption?
I am searching for some cocoa code on AES encryption and I did some google search for it. I found this very useful link -
 http://iphonedevelopment.blogspot.com/2009/02/strong-encryption-for-cocoa-cocoa-touch.html. So I tried it but it did not work for me.

Can anyone suggest me some useful link or source code which can help me to implement it in my sample application.

答:
thanks for the great category extension. One thing that I've discovered - when you use CCCrypt with an algorithm stronger then 64 bit, you need to be compliant to the BIS export regulations. See the iTunes Connect FAQ for more details. Even if you use Apple's inbuild crypto api you need to get approval from the BIS.

There was a discussion on sf about this topic before (in context of ssl usage):

Using SSL in an iPhone App - Export Compliance

Best Regards
Chris


问:
Login request with JWT response
I have a request '/login' which basically validates the USERNAME and PASSWORD and further on success, return token (JWT).

Now the question is my API is also returning USERNAME and PASSWORD in response with token. Is it the right way or should I remove USERNAME and PASSWORD from response.

REQUEST JSON

```<code>{
"USERNAME": "admin",
"PASSWORD": "123456"
}
</code>```

Response

```<code>{
    "token": "eyJhbGciOiJIUzUxMiJ9.eyJleHAiOjE1NTk1NTM4NjcsInVzZXJMb2dpbklkIjoiYWRtaW4ifQ.fxaENKTXxPG5wl8hp7_cSORfMzI38ODu_HgNRj3c7UZwohiFNFfZVpou8MYU4kkxEXV87-LP3upctjGCpGV6_Q",
    "PASSWORD": "123456",
    "USERNAME": "admin"
}
</code>```

答:
I can't add a comment on the Brother's answer so I'll share my thoughts here.

As Brother said, you should not expose the password, or any sensitive informations if it's not needed. If you want to know which user the token is referencing to, you can put a UUID inside, which is a non-linear string identifier for your user. Many databases handle this type of identifiers as primary keys.
You should also encrypt the password with libs like bcrypt.

Title: Login request with JWT response

Body:
I have a request '/login' which basically validates the USERNAME and PASSWORD and further on success, return token (JWT).

Now the question is my API is also returning USERNAME and PASSWORD in response with token. Is it the right way or should I remove USERNAME and PASSWORD from response.

REQUEST JSON

{
"USERNAME": "admin",
"PASSWORD": "123456"
}

Response

{
    "token": "eyJhbGciOiJIUzUxMiJ9.eyJleHAiOjE1NTk1NTM4NjcsInVzZXJMb2dpbklkIjoiYWRtaW4ifQ.fxaENKTXxPG5wl8hp7_cSORfMzI38ODu_HgNRj3c7UZwohiFNFfZVpou8MYU4kkxEXV87-LP3upctjGCpGV6_Q",
    "PASSWORD": "123456",
    "USERNAME": "admin"
}


问:
Optimization problem - GlobalSearch is not generating initial vector in MATLAB
INTRO

I have to solve optimization problem, containing a set of ordinary differential equations. Whats more I need to find global minimum. So far I've only managed to find few local minimums, but examining manually which one is global is tricky for so complex problem.

Description

Let's say I have 3 Matlab files:

Main.m - its the general script file, which is a driver for all others

ODE_set.m - this hold all my ODE's system

Opt_query.m - this contain the definition of optimization objectives, and all equations needed to determined the minimum. Also from this file the ODE solver is started.

I can look for local minimum with this code, and it works totally fine, without any errors:

Main.m

```<code>global k1 k2 k3
x0 = [0.5 8 13];
lu =[ 0.9 25.74 60.9];
lb =[ 0.1 0.74 0.9];
[k,fval,exitflag,output] = fmincon('Opt_query',x0,[],[],[],[],lb,lu);
disp(k1)
disp(k2)
disp(k3)
</code>```

However as I mentioned above I need global minimum so I started to try with GlobalSearch. Here is my code:

```<code>x0 = [0.5 8 13];
lu =[ 0.9 25.74 60.9];
lb =[ 0.1 0.74 0.9];
gs = GlobalSearch;
problem = createOptimProblem('fmincon',Opt_query,x0,[],[],[],[],lb,lu);
[x,fval,exitflag,output] = run(gs,problem);
</code>```

It ends with an error:

Not enough input arguments.

Error in Opt_query (line 3)

k1 = p(1)

Here is the structure of Opt_query.m:

```<code>function q = Opt_query(p)
    global k1 k2 k3
    k1 = p(1)
    k2 = p(2)
    k3 = p(3)
    y0=[1 2 3]
    [t,y] = ode45(@ODE_set,[0, 130],y0,k1,k2,k3)
    t_steps=0:5:130;
    y_steps=interp1(t,y,t_steps);
    for j = 1:27
        Z = Z+ abs(y_steps(j,1)-5)+abs(y_steps(j,2)-7)+abs(y_steps(j,3)-9);
    end
    q = sqrt(Z);
end
</code>```

Here is the structure of ODE_set.m:

```<code>function dydt = ODE_set(t, y, k1, k2, k3)

F = 20.1;
A_in = 2.5;
V = 100;
k = 0.150;
A = y(1);
B = y(2);
C = y(3);

n = numel(y);
dydt = zeros(n,1);
dydt(1) = F/V*(A_in - A) - k1*A^2;
dydt(1) = F/V*(B) - k2*B^2;
dydt(1) = F/V*(C) - k3*C^2;
</code>```

The Problem

So my question is - why when I use fmincon alone, it works fine, but when initiated with GlobalSearch it doesn't generate initial p vector which holds parameters to optimized? Did I miss something, or maybe GlobalSearch require different syntax?

答:
Few mistakes

In Opt_query change this

```<code>[t,y] = ode45(@ODE_set,[0, 130],y0,k1,k2,k3);
</code>```

to this

```<code>[t,y] = ode45(@(t,y)ODE_set(t,y, k1, k2, k3),[0, 130],y0);
</code>```

After tspan = [0,30] you should only use the initial conditions, do
  not include k1, k2, k3

Just take the function ODE_set which has 5 inputs t,y, k1, k2, k3
make a new one with two inputs  t , ythen k1, k2, k3 will be kept
as fixed inputs

```<code>new_ODE_set = @(t, y)ODE_set(t, y, k1, k2, k3)
</code>```

Here is the syntax for ode45

```<code>[t,y] = ode45(odefun,tspan,y0)
</code>```

odefun is a function of t, y only

Since new_ODE_set is a function of t, y as well it can be used now as
odefun

but actually we still have k1, k2, k3 inside it

```<code>for j = 1:27
   Z = Z+ abs(y_steps(j,1)-5)+abs(y_steps(j,2)-7)+abs(y_steps(j,3)-9);
end
</code>```

Here you should initialize Z to zero before running the loop, like
  this

```<code>Z = 0;
for j = 1:27
    Z = Z+ abs(y_steps(j,1)-5)+abs(y_steps(j,2)-7)+abs(y_steps(j,3)-9);
end
</code>```

In ODE_set you're only using index 1 for dydt

Change this

```<code>dydt(1) = F/V*(A_in - A) - k1*A^2;
dydt(1) = F/V*(B) - k2*B^2;
dydt(1) = F/V*(C) - k3*C^2;
</code>```

to this

```<code>dydt(1) = F/V*(A_in - A) - k1*A^2;
dydt(2) = F/V*(B) - k2*B^2;
dydt(3) = F/V*(C) - k3*C^2;
</code>```

To sum up

Main.m

```<code>global k1 k2 k3
x0 = [0.5 8 13];
lu =[ 0.9 25.74 60.9];
lb =[ 0.1 0.74 0.9];
gs = GlobalSearch;

problem = createOptimProblem('fmincon','objective',...
    @Opt_query,'x0',x0,'lb',lb,'ub',lu);

[x,fval,exitflag,output] = run(gs,problem);
disp(k1)
disp(k2)
disp(k3)
</code>```

ODE_set.m

```<code>function dydt = ODE_set(t, y, k1, k2, k3)

    F = 20.1;
    A_in = 2.5;
    V = 100;
    k = 0.150;
    A = y(1);
    B = y(2);
    C = y(3);

    n = numel(y);
    dydt = zeros(n,1);
    dydt(1) = F/V*(A_in - A) - k1*A^2;
    dydt(2) = F/V*(B) - k2*B^2;
    dydt(3) = F/V*(C) - k3*C^2;
end
</code>```

Opt_query.m

```<code>function q = Opt_query(p)

    global k1 k2 k3
    k1 = p(1);
    k2 = p(2);
    k3 = p(3);
    y0=[1 2 3];

    [t,y] = ode45(@(t,y)ODE_set(t,y, k1, k2, k3),[0, 130],y0);
    t_steps=0:5:130;
    y_steps=interp1(t,y,t_steps);
    Z = 0;
    for j = 1:27
        Z = Z+ abs(y_steps(j,1)-5)+abs(y_steps(j,2)-7)+abs(y_steps(j,3)-9);
    end
    q = sqrt(Z);
end
</code>```

Body:
INTRO

I have to solve optimization problem, containing a set of ordinary differential equations. Whats more I need to find global minimum. So far I've only managed to find few local minimums, but examining manually which one is global is tricky for so complex problem.

Description

Let's say I have 3 Matlab files:

Main.m - its the general script file, which is a driver for all others

ODE_set.m - this hold all my ODE's system

Opt_query.m - this contain the definition of optimization objectives, and all equations needed to determined the minimum. Also from this file the ODE solver is started.

I can look for local minimum with this code, and it works totally fine, without any errors:

Main.m

global k1 k2 k3
x0 = [0.5 8 13];
lu =[ 0.9 25.74 60.9];
lb =[ 0.1 0.74 0.9];
[k,fval,exitflag,output] = fmincon('Opt_query',x0,[],[],[],[],lb,lu);
disp(k1)
disp(k2)
disp(k3)

However as I mentioned above I need global minimum so I started to try with GlobalSearch. Here is my code:

x0 = [0.5 8 13];
lu =[ 0.9 25.74 60.9];
lb =[ 0.1 0.74 0.9];
gs = GlobalSearch;
problem = createOptimProblem('fmincon',Opt_query,x0,[],[],[],[],lb,lu);
[x,fval,exitflag,output] = run(gs,problem);

It ends with an error:

Not enough input arguments.

Error in Opt_query (line 3)

k1 = p(1)

Here is the structure of Opt_query.m:

function q = Opt_query(p)
    global k1 k2 k3
    k1 = p(1)
    k2 = p(2)
    k3 = p(3)
    y0=[1 2 3]
    [t,y] = ode45(@ODE_set,[0, 130],y0,k1,k2,k3)
    t_steps=0:5:130;
    y_steps=interp1(t,y,t_steps);
    for j = 1:27
        Z = Z+ abs(y_steps(j,1)-5)+abs(y_steps(j,2)-7)+abs(y_steps(j,3)-9);
    end
    q = sqrt(Z);
end

Here is the structure of ODE_set.m:

function dydt = ODE_set(t, y, k1, k2, k3)

F = 20.1;
A_in = 2.5;
V = 100;
k = 0.150;
A = y(1);
B = y(2);
C = y(3);

n = numel(y);
dydt = zeros(n,1);
dydt(1) = F/V*(A_in - A) - k1*A^2;
dydt(1) = F/V*(B) - k2*B^2;
dydt(1) = F/V*(C) - k3*C^2;

The Problem

So my question is - why when I use fmincon alone, it works fine, but when initiated with GlobalSearch it doesn't generate initial p vector which holds parameters to optimized? Did I miss something, or maybe GlobalSearch require different syntax?

Body:
Few mistakes

In Opt_query change this

[t,y] = ode45(@ODE_set,[0, 130],y0,k1,k2,k3);

to this

[t,y] = ode45(@(t,y)ODE_set(t,y, k1, k2, k3),[0, 130],y0);

After tspan = [0,30] you should only use the initial conditions, do
  not include k1, k2, k3

Just take the function ODE_set which has 5 inputs t,y, k1, k2, k3
make a new one with two inputs  t , ythen k1, k2, k3 will be kept
as fixed inputs

new_ODE_set = @(t, y)ODE_set(t, y, k1, k2, k3)

Here is the syntax for ode45

[t,y] = ode45(odefun,tspan,y0)

odefun is a function of t, y only

Since new_ODE_set is a function of t, y as well it can be used now as
odefun

but actually we still have k1, k2, k3 inside it

for j = 1:27
   Z = Z+ abs(y_steps(j,1)-5)+abs(y_steps(j,2)-7)+abs(y_steps(j,3)-9);
end

Here you should initialize Z to zero before running the loop, like
  this

Z = 0;
for j = 1:27
    Z = Z+ abs(y_steps(j,1)-5)+abs(y_steps(j,2)-7)+abs(y_steps(j,3)-9);
end

In ODE_set you're only using index 1 for dydt

Change this

dydt(1) = F/V*(A_in - A) - k1*A^2;
dydt(1) = F/V*(B) - k2*B^2;
dydt(1) = F/V*(C) - k3*C^2;

to this

dydt(1) = F/V*(A_in - A) - k1*A^2;
dydt(2) = F/V*(B) - k2*B^2;
dydt(3) = F/V*(C) - k3*C^2;

To sum up

Main.m

global k1 k2 k3
x0 = [0.5 8 13];
lu =[ 0.9 25.74 60.9];
lb =[ 0.1 0.74 0.9];
gs = GlobalSearch;

problem = createOptimProblem('fmincon','objective',...
    @Opt_query,'x0',x0,'lb',lb,'ub',lu);

[x,fval,exitflag,output] = run(gs,problem);
disp(k1)
disp(k2)
disp(k3)

ODE_set.m

function dydt = ODE_set(t, y, k1, k2, k3)

    F = 20.1;
    A_in = 2.5;
    V = 100;
    k = 0.150;
    A = y(1);
    B = y(2);
    C = y(3);

    n = numel(y);
    dydt = zeros(n,1);
    dydt(1) = F/V*(A_in - A) - k1*A^2;
    dydt(2) = F/V*(B) - k2*B^2;
    dydt(3) = F/V*(C) - k3*C^2;
end

Opt_query.m

function q = Opt_query(p)

    global k1 k2 k3
    k1 = p(1);
    k2 = p(2);
    k3 = p(3);
    y0=[1 2 3];

    [t,y] = ode45(@(t,y)ODE_set(t,y, k1, k2, k3),[0, 130],y0);
    t_steps=0:5:130;
    y_steps=interp1(t,y,t_steps);
    Z = 0;
    for j = 1:27
        Z = Z+ abs(y_steps(j,1)-5)+abs(y_steps(j,2)-7)+abs(y_steps(j,3)-9);
    end
    q = sqrt(Z);
end


问:
Laravel replace comma by dot in array input before validation
I'd like to replace all commas by dots in multiple array inputs, before checking if the input is numeric. I've got 6 inputs named percentage with an index from 1 to 6.

This is how I'd like to merge the modified percentages with the $request variable.

    for ($c = 1; $c <= 6; $c++) {
        if ($request->percentage[$c] != null) {
          $request->merge([
            "percentage.$c" => str_replace(',', '.', $request->percentage[$c])
          ]);
        }
      }
```

<p>This is how I'd like to validate the percentages.</p>

<pre class="lang-php prettyprint-override"><code>    $this->validate($request, [
        'percentage.1' => 'required|numeric',
        'percentage.2' => 'numeric|nullable',
        'percentage.3' => 'numeric|nullable',
        'percentage.4' => 'numeric|nullable',
        'percentage.5' => 'numeric|nullable',
        'percentage.6' => 'numeric|nullable',
      ]);
</code>```

However, this solution is somehow not working. If I enter for example 20,77 it says that it's not numeric.
Does anybody know, what the problem is?

答:
I think this needs to be explained a little more. Like what the $request data looks like before modifying it. Or what the output $request data looks like after modifying it.

I imagine that the two numbers you said (20 and 77) are supposed to be where the $c variable is? So you're looping through 1 to 6 and checking for $request->percentage[$c] where $c is the numbers you've inputted, e.g. 20 or 77... Because your script is stopping after it hits 6, it will never reach 20 or 77.

Body:
I'd like to replace all commas by dots in multiple array inputs, before checking if the input is numeric. I've got 6 inputs named percentage with an index from 1 to 6.

This is how I'd like to merge the modified percentages with the $request variable.

    for ($c = 1; $c <= 6; $c++) {
        if ($request->percentage[$c] != null) {
          $request->merge([
            "percentage.$c" => str_replace(',', '.', $request->percentage[$c])
          ]);
        }
      }

This is how I'd like to validate the percentages.

    $this->validate($request, [
        'percentage.1' => 'required|numeric',
        'percentage.2' => 'numeric|nullable',
        'percentage.3' => 'numeric|nullable',
        'percentage.4' => 'numeric|nullable',
        'percentage.5' => 'numeric|nullable',
        'percentage.6' => 'numeric|nullable',
      ]);

However, this solution is somehow not working. If I enter for example 20,77 it says that it's not numeric.
Does anybody know, what the problem is?


问:
Is toString() only useful for debugging?
Besides of course, their use with primitives. Most (if not all) of the implementations I see are only useful from a programmer viewpoint.

EDIT: I understand that I'm supposed to override the default behavior, that's why I mentioned implementations :). And I do get the value of overriding it in some components requiring a String representation inside a GUI. However, in the JDK at least, I see lots of implementations that only come to use whenever you need to debug the object instances.

Why is it rooted at the Object class, since that is only seems useful for GUI/debugging stuff? are there other uses I'm not aware of?

答:
Aside from what everyone else has already said, overriding ToString() is also useful when using controls that call it.  For example, a ComboBox:</p>

```<code>myComboBox.Items.Add(new MyClass());
// now, whatever ToString() returns is shown in the
// ComboBox, but you can get the object back by through
// the SlectedItem property.
</code>```

OwnerDisplayName: Camilo Díaz

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Camilo Díaz

Body:
Aside from what everyone else has already said, overriding ToString() is also useful when using controls that call it.  For example, a ComboBox:

myComboBox.Items.Add(new MyClass());
// now, whatever ToString() returns is shown in the
// ComboBox, but you can get the object back by through
// the SlectedItem property.

OwnerDisplayName: Ed Swangren


问:
Azure Active Directory and Azure DevOps
We're planning on migrating our TFS on premise to Azure DevOps. I understand that to migrate, we need Azure AD. My question is, what would be the subscription level should I get?

I'm fairly new to this so please go easy on me. Thanks!

答:
Do you mean Azure Subscription?

DevOps doesn't requires Azure Subscription. But if you anticipate needing to purchase any additional user plans, build/deployment pipelines, hosted build services, hosted load test services, or other developer services, we highly recommend making sure that you have an Azure Subscription ready for linking to your imported Azure DevOps Services organization once the import has completed.

You could refer to the migration guide first, which can be downloaded from website below:

https://azure.microsoft.com/en-us/services/devops/migrate/

Title: Azure Active Directory and Azure DevOps


问:
Why I don't have Build File in my Flutter Project
Whenever i create a new project in flutter, I don't get the Build File! Why?

答: your build file available in folder name Android, see below capture


问:
Is it mandatory to save *.iml files in Version control?
I have now switched to Android Studio and saving my projects in Git with Source Tree. Whenever I add or remove any library from my module, its .iml file also changes. It really doesn't matter if I commit the *.iml because they get auto-generated in others Android Studio. However, here
 it says you should store *.iml . My question is, do we really need to share our *.iml with others? If yes, why?</p>

答:
I agree that they are IDE-dependant files irrelevant to code and they should not be shared. But, then you should know how to regenerate them.

You may encounter with situations while your remote repo does not contain these files and when you clone the code and open in IDEA, it just shows a bunch of errors. Why? *.iml files are not regenerated.

You must import from IDEA with "File" - "New" - "Project from Version control". Only this can generated the files for you.


问:
Is there any way to assign resource limits after scheduling a pod? ( I would like to implement my own resource allocation policy)
I would like to create a way to specify resource limits after scheduling pods. Is it possible to do this? if yes, shall I implement it inside the kubelet or as a separate component?</p>

答: you can use kubectl patch command to update resource limits</p>


问:
OPENCART - 4 products in category page
how can I put 4 products per line in my categories page
https://fixfone.pt/index.php?route=product/category&path=345

need help to resolve this :(
I do not know what to do anymore

答:
this is just CSS. since you are using Bootstrap simply change the class for

.product-grid.col-md-4

to

.product-grid.col-md-3

if you catalog/view/theme/YOUR THEME/template/product/catalog.twig

Title: OPENCART - 4 products in category page


问:
How to open a link in new windows
Good morning
how can I open the link called by the action "URLPAYPAL" in a new window? I tried with onclick = "window.open (); but it doesn't work</p>

```<code>echo "<a href=# class=\"btn btn-lg btn-block btn-inverse\" onclick=\"";
echo "formid = document.getElementById('gest');\n";
echo "document.getElementById('tabdati2').style.display='';\n";
echo "document.getElementById('tabdati1').style.display='none';\n";
echo "document.getElementById('gest').action='" . URLPAYPAL . "';\n";
echo "formid.email.style.backgroundColor ='#FFFFFF';\n";
echo "var ctrlerr = 0;\n";
echo "var regtel = /^(\d+)$/;\n";
echo "var regema =  /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})$/;\n";
echo "if ((formid.cli.value) != (formid.cli2.value)) {\n";
echo "formid.cli.style.backgroundColor ='#E55B3C';\n";
echo "alert ('Il numero di telefono non coincide!');\n";
echo "ctrlerr=1;\n";
echo "}\n";
echo "if ((formid.cli.value == '') || (formid.cli.value == 'Numero di telefono')) {\n";
echo "formid.cli.style.backgroundColor ='#E55B3C';\n";
echo "alert ('Scrivi il numero di telefono!');\n";
echo "ctrlerr=1;\n";
echo "}\n";
echo "if(!ctrlerr) {\n";
echo "formid.submit();\n";
echo "}\n";
echo "\"> Ricarica<span class=\"fui-arrow-right\"></span> </a>\n";
</code>```

答:
you can add this to your form </p>

```<code>target="_blank"
</code>```

Title: How to open a link in new windows

Body:
Good morning
how can I open the link called by the action "URLPAYPAL" in a new window? I tried with onclick = "window.open (); but it doesn't work

echo "<a href=# class=\"btn btn-lg btn-block btn-inverse\" onclick=\"";
echo "formid = document.getElementById('gest');\n";
echo "document.getElementById('tabdati2').style.display='';\n";
echo "document.getElementById('tabdati1').style.display='none';\n";
echo "document.getElementById('gest').action='" . URLPAYPAL . "';\n";
echo "formid.email.style.backgroundColor ='#FFFFFF';\n";
echo "var ctrlerr = 0;\n";
echo "var regtel = /^(\d+)$/;\n";
echo "var regema =  /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})$/;\n";
echo "if ((formid.cli.value) != (formid.cli2.value)) {\n";
echo "formid.cli.style.backgroundColor ='#E55B3C';\n";
echo "alert ('Il numero di telefono non coincide!');\n";
echo "ctrlerr=1;\n";
echo "}\n";
echo "if ((formid.cli.value == '') || (formid.cli.value == 'Numero di telefono')) {\n";
echo "formid.cli.style.backgroundColor ='#E55B3C';\n";
echo "alert ('Scrivi il numero di telefono!');\n";
echo "ctrlerr=1;\n";
echo "}\n";
echo "if(!ctrlerr) {\n";
echo "formid.submit();\n";
echo "}\n";
echo "\"> Ricarica \n";

Body:
you can add this to your form

target="_blank"


问:
split xml value with xpath and check string position
I have the following xml file:

```<code> <courses>
   <course>
    <name>Course 1</name>
    <code>00162</code>
    <questions>2,2,1,1,2,1,1,1</questions>
   </course>
   </courses>
</code>```

I need to query the file (I'm using xpath) to split the 'questions' element, check the position in which each number appears and check if it is number 1 or 2.

Basically I need to this in xpath:

```<code>Dim ints As String() = QuestionsString.ToString.Split(",")
Dim i As Integer

        For i = 0 To UBound(ints)
            If ints(i) = "2" Then
             'do something
            Else
            'do something else
            End If
        Next
</code>```

Update from comments

Hi, thank you. I was going to edit the
  question as it was incorrect. I want
  to get, for example, all course names
  and codes whose 'questions' element
  (after split) has "2" in the second
  position, as in 1,2,2,1,1,1,2,1
  Thanks!

答:
```<code>/courses
   /course[
      substring-before(
         substring-after(
            question,
            ','
         ),
         ','
      ) = 2
   ]/*[self::name|self::code]
</code>```

Or

```<code>/courses
   /course[
      substring(question,3,1) = '2'
   ]/*[self::name|self::code]
</code>```

Body:
I have the following xml file:

 <courses>
   <course>
    <name>Course 1</name>
    00162
    <questions>2,2,1,1,2,1,1,1</questions>
   </course>
   </courses>

I need to query the file (I'm using xpath) to split the 'questions' element, check the position in which each number appears and check if it is number 1 or 2.

Basically I need to this in xpath:

Dim ints As String() = QuestionsString.ToString.Split(",")
Dim i As Integer

        For i = 0 To UBound(ints)
            If ints(i) = "2" Then
             'do something
            Else
            'do something else
            End If
        Next

Update from comments

Hi, thank you. I was going to edit the
  question as it was incorrect. I want
  to get, for example, all course names
  and codes whose 'questions' element
  (after split) has "2" in the second
  position, as in 1,2,2,1,1,1,2,1
  Thanks!

Body:
/courses
   /course[
      substring-before(
         substring-after(
            question,
            ','
         ),
         ','
      ) = 2
   ]/*[self::name|self::code]

Or

/courses
   /course[
      substring(question,3,1) = '2'
   ]/*[self::name|self::code]


问:
How to fix os.path.join(os.getcwd(), os.relpath('my_file')) not returning the path to 'my_file'?
I have the following working directory: /Users/jordan/Coding/Employer/code_base, and the file I want to get the absolute path for is located at /Users/jordan/Coding/Employer/code_base/framework/GTC/tests/day_document.json.
I have tests in the file /Users/jordan/Coding/Employer/code_base/framework/GTC/tests/test.py.

Currently when I use os.path.join(os.getcwd(), os.path.relpath('day_document.json') I'm getting /Users/jordan/Coding/Employer/code_base/day_document.json. I want to get the correct filepath to day_document.json so that tests can work properly in CI. The code is currently running in the test file, located at /Users/jordan/Coding/Employer/code_base/framework/GTC/tests/test.py.

I've already tried os.path.relpath('day_document.json') and os.path.abspath('day_document.json') in os.join, and both return /Users/jordan/Coding/Employer/code_base/day_document.json. I've also done a ton of googling, but can't seem to find anything where people are getting the correct answer. When I use os.path.join(os.getcwd(), 'framework/GTC/tests/day_document.json'), I get the correct behavior, but I don't want to hardcode file paths.

This works:

```<code>day_document_file_location = os.path.join(os.getcwd(), 'framework/GTC/tests/day_document.json')
with open(day_document_file_location, 'r') as day_doc_json:
    day_doc_endpoint._content = day_doc_json.read()
</code>```

But I don't understand why this doesn't:

```<code>day_document_file_location = os.path.join(os.getcwd(), os.path.relpath('day_document.json'))
with open(day_document_file_location, 'r') as day_doc_json:
    day_doc_endpoint._content = day_doc_json.read()
</code>```

I have to mention, that the latter code works when I run it from the file location, but not from the working directory.

I want to find a way to not hard code a file path, and be able to get /Users/jordan/Coding/Employer/code_base/framework/GTC/tests/day_document.json from the working directory.

答:
According to [Python 3.Docs]: os.path.relpath(path, start=os.curdir) (emphasis is mine):

... This is a path computation: the filesystem is not accessed to confirm the existence or nature of path or start.

If you don't want to hardcode framework/GTC/tests/day_document.json (the intermediary dirs), you need to search for the file. One way would be to use [Python 3.Docs]: glob.iglob(pathname, *, recursive=False):

document_name = "day_document.json"
document_path = ""
for p in glob.iglob(os.path.join("**", document_name), recursive=True):
    document_path = os.path.abspath(p)
    break
if not document_path:
    # Handle file not being present, e.g.:
    raise FileNotFoundError(document_name)
```

Needless to say that if you have more than one file with that name in the dir tree, the 1st one will be returned (and there's no guarantee that it will be the one you're expecting).

Body:
I have the following working directory: /Users/jordan/Coding/Employer/code_base, and the file I want to get the absolute path for is located at /Users/jordan/Coding/Employer/code_base/framework/GTC/tests/day_document.json.
I have tests in the file /Users/jordan/Coding/Employer/code_base/framework/GTC/tests/test.py.

Currently when I use os.path.join(os.getcwd(), os.path.relpath('day_document.json') I'm getting /Users/jordan/Coding/Employer/code_base/day_document.json. I want to get the correct filepath to day_document.json so that tests can work properly in CI. The code is currently running in the test file, located at /Users/jordan/Coding/Employer/code_base/framework/GTC/tests/test.py.

I've already tried os.path.relpath('day_document.json') and os.path.abspath('day_document.json') in os.join, and both return /Users/jordan/Coding/Employer/code_base/day_document.json. I've also done a ton of googling, but can't seem to find anything where people are getting the correct answer. When I use os.path.join(os.getcwd(), 'framework/GTC/tests/day_document.json'), I get the correct behavior, but I don't want to hardcode file paths.

This works:

day_document_file_location = os.path.join(os.getcwd(), 'framework/GTC/tests/day_document.json')
with open(day_document_file_location, 'r') as day_doc_json:
    day_doc_endpoint._content = day_doc_json.read()

But I don't understand why this doesn't:

day_document_file_location = os.path.join(os.getcwd(), os.path.relpath('day_document.json'))
with open(day_document_file_location, 'r') as day_doc_json:
    day_doc_endpoint._content = day_doc_json.read()

I have to mention, that the latter code works when I run it from the file location, but not from the working directory.

I want to find a way to not hard code a file path, and be able to get /Users/jordan/Coding/Employer/code_base/framework/GTC/tests/day_document.json from the working directory.

Body:
According to [Python 3.Docs]: os.path.relpath(path, start=os.curdir) (emphasis is mine):

... This is a path computation: the filesystem is not accessed to confirm the existence or nature of path or start.

If you don't want to hardcode framework/GTC/tests/day_document.json (the intermediary dirs), you need to search for the file. One way would be to use [Python 3.Docs]: glob.iglob(pathname, *, recursive=False):

document_name = "day_document.json"
document_path = ""
for p in glob.iglob(os.path.join("**", document_name), recursive=True):
    document_path = os.path.abspath(p)
    break
if not document_path:
    # Handle file not being present, e.g.:
    raise FileNotFoundError(document_name)

Needless to say that if you have more than one file with that name in the dir tree, the 1st one will be returned (and there's no guarantee that it will be the one you're expecting).


问:
Filtering resources with different encodings
I have a maven project. In /src/main/resources/ I have two files foo.properties and bar.xml. The first is encoded in ISO-8859-1 and the second one in UTF-8.

Is there an easy way to get filtering for both files without breaking encoding?

As far as I see, I cannot specify an encoding in a <resource> block. It seems only possible to specify an encoding for the plugin itself, but this would lead in both files being filtered using the same encoding.

Ideally I would like to specify something like:

*.properties -> filter using ISO-8859-1

*.xml -> filter using UTF-8

*.pdf -> do not filter

anything else -> filter using default encoding

This doesn't feel like a very unusual situation, is there an easy way to configure this?

答:
If you don't want to keep your resources in separate directories you can also keep them in the default directory src/main/resources and play with exclusions.
The idea is:

file extensions that should not be filtered should be added to the default configuration using nonFilteredFileExtensions

let the default execution of the resources plugin process resources with the default encoding

exclude files that do no use this encoding from the build/resources configuration

for each additional encoding you want to handle, add an execution of goal "copy-resources" with explicit includes that selects only the targeted files

This example only handles .properties but you can easily generalize:

```<code><resources>
     <resource>
        <directory>src/main/resources</directory>
        <excludes>
            <exclude>application*.properties</exclude>
        </excludes>
        <filtering>true</filtering>
    </resource>
 </resources>
</code>```

...

```<code>   <plugin>
        <artifactId>maven-resources-plugin</artifactId>
        <configuration>
            <nonFilteredFileExtensions>
                  <nonFilteredFileExtension>pdf</nonFilteredFileExtension>
            </nonFilteredFileExtensions>
        </configuration>
        <executions>
            <execution>
                <id>properties</id>
                <phase>process-resources</phase>
                <goals>
                    <goal>copy-resources</goal>
                </goals>
                <configuration>
                    <encoding>ISO-8859-1</encoding>
                    <resources>
                        <resource>
                            <directory>src/main/resources</directory>
                            <filtering>true</filtering>
                            <includes>
                                <include>application*.properties</include>
                            </includes>
                        </resource>
                    </resources>
                    <outputDirectory>${project.build.outputDirectory}</outputDirectory>
                </configuration>
            </execution>
        </executions>
    </plugin>
</code>```

Body:
If you don't want to keep your resources in separate directories you can also keep them in the default directory src/main/resources and play with exclusions.
The idea is:

file extensions that should not be filtered should be added to the default configuration using nonFilteredFileExtensions

let the default execution of the resources plugin process resources with the default encoding

exclude files that do no use this encoding from the build/resources configuration

for each additional encoding you want to handle, add an execution of goal "copy-resources" with explicit includes that selects only the targeted files

This example only handles .properties but you can easily generalize:

<resources>
     <resource>
        <directory>src/main/resources</directory>
        <excludes>
            <exclude>application*.properties</exclude>
        </excludes>
        <filtering>true</filtering>
    </resource>
 </resources>

...

   <plugin>
        <artifactId>maven-resources-plugin</artifactId>
        <configuration>
            <nonFilteredFileExtensions>
                  <nonFilteredFileExtension>pdf</nonFilteredFileExtension>
            </nonFilteredFileExtensions>
        </configuration>
        <executions>
            <execution>
                <id>properties</id>
                <phase>process-resources</phase>
                <goals>
                    <goal>copy-resources</goal>
                </goals>
                <configuration>
                    <encoding>ISO-8859-1</encoding>
                    <resources>
                        <resource>
                            <directory>src/main/resources</directory>
                            <filtering>true</filtering>
                            <includes>
                                <include>application*.properties</include>
                            </includes>
                        </resource>
                    </resources>
                    <outputDirectory>${project.build.outputDirectory}</outputDirectory>
                </configuration>
            </execution>
        </executions>
    </plugin>


问:
"Header content contains invalid characters" error when piping multipart upload part into a new request
My express server receives file uploads from browsers.  The uploads are transferred as multipart/form-data requests; I use multiparty to parse the incoming entity body.

Multiparty allows you to get a part (roughly, a single form field like an <input type="file">) as a readable stream.  I do not want to process or store the uploaded file(s) on my web server, so I just pipe the uploaded file part into a request made to another service (using the request module).

```<code>app.post('/upload', function(req, res) {
    var form = new multiparty.Form();

    form.on('part', function(part) {

        var serviceRequest = request({
            method: 'POST',
            url: 'http://other-service/process-file',
            headers: {
                'Content-Type': 'application/octet-stream'
            }
        }, function(err, svcres, body) {
            // handle response
        });

        part.pipe(serviceRequest);
    });

    form.parse(req);
});
</code>```

This works correctly most of the time.  node automatically applies chunked transfer encoding, and as the browser uploads file bytes, they are correctly sent to the backend service as a raw entity body (without the multipart formatting), which ultimately gets the complete file and returns successfully.

However, sometimes the request fails and my callback gets called with this err:

```<code>TypeError: The header content contains invalid characters
    at ClientRequest.OutgoingMessage.setHeader (_http_outgoing.js:360:11)
    at new ClientRequest (_http_client.js:85:14)
    at Object.exports.request (http.js:31:10)
    at Object.exports.request (https.js:199:15)
    at Request.start (/app/node_modules/request/request.js:744:32)
    at Request.write (/app/node_modules/request/request.js:1421:10)
    at PassThrough.ondata (_stream_readable.js:555:20)
    at emitOne (events.js:96:13)
    at PassThrough.emit (events.js:188:7)
    at PassThrough.Readable.read (_stream_readable.js:381:10)
    at flow (_stream_readable.js:761:34)
    at resume_ (_stream_readable.js:743:3)
    at _combinedTickCallback (internal/process/next_tick.js:80:11)
    at process._tickDomainCallback (internal/process/next_tick.js:128:9)
</code>```

I'm unable to explain where that error is coming from since I only set the Content-Type header and the stack does not contain any of my code.

Why do my uploads occasionally fail?

答:
This example shows how to send file as an attachment with national symbols in the filename.</p>

```<code>const http = require('http');
const fs = require('fs');
const contentDisposition = require('content-disposition');
...

// req, res - http request and response
let filename='totally legit .pdf';
let filepath = 'D:/temp/' + filename;

res.writeHead(200, {
    'Content-Disposition': contentDisposition(filename), // Mask non-ANSI chars
    'Content-Transfer-Encoding': 'binary',
    'Content-Type': 'application/octet-stream'
});

var readStream = fs.createReadStream(filepath);
readStream.pipe(res);
readStream.on('error', (err) => ...);
</code>```

Body:
My express server receives file uploads from browsers.  The uploads are transferred as multipart/form-data requests; I use multiparty to parse the incoming entity body.

Multiparty allows you to get a part (roughly, a single form field like an <input type="file">) as a readable stream.  I do not want to process or store the uploaded file(s) on my web server, so I just pipe the uploaded file part into a request made to another service (using the request module).

app.post('/upload', function(req, res) {
    var form = new multiparty.Form();

    form.on('part', function(part) {

        var serviceRequest = request({
            method: 'POST',
            url: 'http://other-service/process-file',
            headers: {
                'Content-Type': 'application/octet-stream'
            }
        }, function(err, svcres, body) {
            // handle response
        });

        part.pipe(serviceRequest);
    });

    form.parse(req);
});

This works correctly most of the time.  node automatically applies chunked transfer encoding, and as the browser uploads file bytes, they are correctly sent to the backend service as a raw entity body (without the multipart formatting), which ultimately gets the complete file and returns successfully.

However, sometimes the request fails and my callback gets called with this err:

TypeError: The header content contains invalid characters
    at ClientRequest.OutgoingMessage.setHeader (_http_outgoing.js:360:11)
    at new ClientRequest (_http_client.js:85:14)
    at Object.exports.request (http.js:31:10)
    at Object.exports.request (https.js:199:15)
    at Request.start (/app/node_modules/request/request.js:744:32)
    at Request.write (/app/node_modules/request/request.js:1421:10)
    at PassThrough.ondata (_stream_readable.js:555:20)
    at emitOne (events.js:96:13)
    at PassThrough.emit (events.js:188:7)
    at PassThrough.Readable.read (_stream_readable.js:381:10)
    at flow (_stream_readable.js:761:34)
    at resume_ (_stream_readable.js:743:3)
    at _combinedTickCallback (internal/process/next_tick.js:80:11)
    at process._tickDomainCallback (internal/process/next_tick.js:128:9)

I'm unable to explain where that error is coming from since I only set the Content-Type header and the stack does not contain any of my code.

Why do my uploads occasionally fail?

Body:
This example shows how to send file as an attachment with national symbols in the filename.

const http = require('http');
const fs = require('fs');
const contentDisposition = require('content-disposition');
...

// req, res - http request and response
let filename='totally legit .pdf';
let filepath = 'D:/temp/' + filename;

res.writeHead(200, {
    'Content-Disposition': contentDisposition(filename), // Mask non-ANSI chars
    'Content-Transfer-Encoding': 'binary',
    'Content-Type': 'application/octet-stream'
});

var readStream = fs.createReadStream(filepath);
readStream.pipe(res);
readStream.on('error', (err) => ...);


问:
Using RegEx to Insert Character before Matches
I know I can use RegEx to replace all occurrences of 'a', 'b', or 'c' with a blackslash character in a string like this:

```<code>string result = Regex.Replace(input, "[abc]", "\\");
</code>```

But how can I replace each occurrence with a backslash followed by the character that matched?

答:
No need to use any MatchEvaluator, Regex.Replace offers dedicated means to access the whole match value in the replacement pattern: $&. See Substituting the Entire Match:

The $& substitution includes the entire match in the replacement string. Often, it is used to add a substring to the beginning or end of the matched string. For example, the ($&) replacement pattern adds parentheses to the beginning and end of each match. If there is no match, the $& substitution has no effect.

Use

```<code>var result = Regex.Replace(input, @"[abc]", @"\$&");
</code>```

C# demo:

```<code>var s = "abcd";
var result = Regex.Replace(s, @"[abc]", @"\$&");
Console.WriteLine(result);
// => \a\b\cd
</code>```

Body:
I know I can use RegEx to replace all occurrences of 'a', 'b', or 'c' with a blackslash character in a string like this:

string result = Regex.Replace(input, "[abc]", "\\");

But how can I replace each occurrence with a backslash followed by the character that matched?

Body:
No need to use any MatchEvaluator, Regex.Replace offers dedicated means to access the whole match value in the replacement pattern: $&. See Substituting the Entire Match:

The $& substitution includes the entire match in the replacement string. Often, it is used to add a substring to the beginning or end of the matched string. For example, the ($&) replacement pattern adds parentheses to the beginning and end of each match. If there is no match, the $& substitution has no effect.

Use

var result = Regex.Replace(input, @"[abc]", @"\$&");

C# demo:

var s = "abcd";
var result = Regex.Replace(s, @"[abc]", @"\$&");
Console.WriteLine(result);
// => \a\b\cd


问:
Sequence processing with Azure Function & Service Bus
I have an issue with Azure Function Service Bus trigger.
The issue is Azure function cannot wait a message done before process a new message. It process Parallel, it not wait 5s before get next message. But i need it process sequencecy (as image bellow).
How can i do that?

```<code>[FunctionName("HttpStartSingle")]
    public static void Run(
 [ServiceBusTrigger("MyServiceBusQueue", Connection = "Connection")]string myQueueItem,
[OrchestrationClient] DurableOrchestrationClient starter,
ILogger log)
    {
        Console.WriteLine($"MessageId={myQueueItem}");
        Thread.Sleep(5000);
    }
</code>```

答:
There are two approaches you can accomplish this,

(1) You are looking for Durable Function with function chaining

For background jobs you often need to ensure that only one instance of
  a particular orchestrator runs at a time. This can be done in Durable
  Functions by assigning a specific instance ID to an orchestrator when
  creating it.

(2) Based on the messages that you are writing to Queue, you need to partition the data, that will automatically handle the order of messages which you do not need to handle manually by azure function

Body:
I have an issue with Azure Function Service Bus trigger.
The issue is Azure function cannot wait a message done before process a new message. It process Parallel, it not wait 5s before get next message. But i need it process sequencecy (as image bellow).
How can i do that?

[FunctionName("HttpStartSingle")]
    public static void Run(
 [ServiceBusTrigger("MyServiceBusQueue", Connection = "Connection")]string myQueueItem,
[OrchestrationClient] DurableOrchestrationClient starter,
ILogger log)
    {
        Console.WriteLine($"MessageId={myQueueItem}");
        Thread.Sleep(5000);
    }


问:
Counting an increase in series with changing parameters for each ID
I have an dataset which has 12 different values for an ID, and also start and end Values. What I want to initilize is take the start value as my begining argument of loop and end value as the last argument. Search trough values accourding to them, and finding the first consecutive increase.

Below I posted an example dataset:

```<code>create table #sample_data(
ID  VARCHAR(10), val1 INT, val2 INT, val3 INT, val4 INT, val5 INT, val6 INT, val7 INT, val8 INT, val9 INT, val10 INT, val11 INT, val12 INT, startValue INT, endValue INT
);

insert into #sample_data values
    (1001,3,2,1,0,1,2,3,0,0,0,0,0,1,7),
    (1002,1,2,3,4,0,0,0,1,2,3,0,0,1,12),
    (1003,0,3,2,1,0,0,0,0,0,0,0,0,1,12),
    (1004,0,1,2,3,4,0,0,0,0,0,0,0,3,9),
    (1005,1,1,1,1,2,3,2,2,1,1,0,0,1,8);
</code>```

That is the result I expect:
for the ID = 1001 my startValue is 1 and end is 7 algorith will go through from val1 to val7 to compare each val with the next one and count an increase till it ends.
In this case for 1001 it will be be 0 since series will start with a decrease.
for ID 1002 it will also be 3 (val1 to val4 and it will stop at val5 when a decrease occur)
for ID 1003 it will be 1 since there is only an increase at the begining
for ID 1004 it will be 2 since it starts from 3 and ends at val9
for ID 1005 it will be 2 which is the increase from val4 to val6

I have tried to execute this with writing CURSOR  but since I had more than 300K line of data it took hours to execute. If you have any better suggestion (without using cursor), I will be so thakful.

答:
If I understood correctly what you were aiming for, you can to that using a select case like this:

```<code>select result.Id,
    -- result.resulttext
    LEN(replace(substring(result.resulttext,1, charindex('0', result.resulttext)-1), '1', '')) as finaltesult
    from
    (select ID,
        case when S.val1 <= S.val2   then case when S.val2  >= S.startvalue and S.val2  <= S.endvalue then case when S.val1 < S.val2 then '2' else '1' end else '1' end else '0' end +
        case when S.val2 <= S.val3   then case when S.val3  >= S.startvalue and S.val3  <= S.endvalue then case when S.val2 < S.val3 then '2' else '1' end  else '1' end else '0' end +
        case when S.val3 <= S.val4   then case when S.val4  >= S.startvalue and S.val4  <= S.endvalue then case when S.val3 < S.val4 then '2' else '1' end  else '1' end else '0' end +
        case when S.val4 <= S.val5   then case when S.val5  >= S.startvalue and S.val5  <= S.endvalue then case when S.val4 < S.val5 then '2' else '1' end  else '1' end else '0' end +
        case when S.val5 <= S.val6   then case when S.val6  >= S.startvalue and S.val6  <= S.endvalue then case when S.val5 < S.val6 then '2' else '1' end  else '1' end else '0' end +
        case when S.val6 <= S.val7   then case when S.val6  >= S.startvalue and S.val7  <= S.endvalue then case when S.val6 < S.val7 then '2' else '1' end  else '1' end else '0' end +
        case when S.val7 <= S.val8   then case when S.val8  >= S.startvalue and S.val8  <= S.endvalue then case when S.val7 < S.val8 then '2' else '1' end  else '1' end else '0' end +
        case when S.val8 <= S.val9   then case when S.val9  >= S.startvalue and S.val9  <= S.endvalue then case when S.val8 < S.val9 then '2' else '1' end  else '1' end else '0' end +
        case when S.val9 <= S.val10  then case when S.val10 >= S.startvalue and S.val10 <= S.endvalue then case when S.val9 < S.val10 then '2' else '1' end  else '1' end else '0' end +
        case when S.val10 <= S.val11 then case when S.val11 >= S.startvalue and S.val11 <= S.endvalue then case when S.val10 < S.val11 then '2' else '1' end  else '1' end else '0' end +
        case when S.val11 <= S.val12 then case when S.val12 >= S.startvalue and S.val12 <= S.endvalue then case when S.val11 < S.val12 then '2' else '1' end  else '1' end else '0' end  as resulttext
    from @sample_data as S) result
</code>```

This case will transform each transition to:

'0' is value valN is higher than valN+1

'1' if value matches the limits but valN is equal to valN+1

and '2' if the transition from valN to vanN+1 matches all your
conditions

Than is just a matter of working with the result string.
Uncomment result.resulttext if you want to take a look at the 'transformed' result string.

Body:
I have an dataset which has 12 different values for an ID, and also start and end Values. What I want to initilize is take the start value as my begining argument of loop and end value as the last argument. Search trough values accourding to them, and finding the first consecutive increase.

Below I posted an example dataset:

create table #sample_data(
ID  VARCHAR(10), val1 INT, val2 INT, val3 INT, val4 INT, val5 INT, val6 INT, val7 INT, val8 INT, val9 INT, val10 INT, val11 INT, val12 INT, startValue INT, endValue INT
);

insert into #sample_data values
    (1001,3,2,1,0,1,2,3,0,0,0,0,0,1,7),
    (1002,1,2,3,4,0,0,0,1,2,3,0,0,1,12),
    (1003,0,3,2,1,0,0,0,0,0,0,0,0,1,12),
    (1004,0,1,2,3,4,0,0,0,0,0,0,0,3,9),
    (1005,1,1,1,1,2,3,2,2,1,1,0,0,1,8);

That is the result I expect:
for the ID = 1001 my startValue is 1 and end is 7 algorith will go through from val1 to val7 to compare each val with the next one and count an increase till it ends.
In this case for 1001 it will be be 0 since series will start with a decrease.
for ID 1002 it will also be 3 (val1 to val4 and it will stop at val5 when a decrease occur)
for ID 1003 it will be 1 since there is only an increase at the begining
for ID 1004 it will be 2 since it starts from 3 and ends at val9
for ID 1005 it will be 2 which is the increase from val4 to val6

I have tried to execute this with writing CURSOR  but since I had more than 300K line of data it took hours to execute. If you have any better suggestion (without using cursor), I will be so thakful.

Body:
If I understood correctly what you were aiming for, you can to that using a select case like this:

select result.Id,
    -- result.resulttext
    LEN(replace(substring(result.resulttext,1, charindex('0', result.resulttext)-1), '1', '')) as finaltesult
    from
    (select ID,
        case when S.val1 <= S.val2   then case when S.val2  >= S.startvalue and S.val2  <= S.endvalue then case when S.val1 < S.val2 then '2' else '1' end else '1' end else '0' end +
        case when S.val2 <= S.val3   then case when S.val3  >= S.startvalue and S.val3  <= S.endvalue then case when S.val2 < S.val3 then '2' else '1' end  else '1' end else '0' end +
        case when S.val3 <= S.val4   then case when S.val4  >= S.startvalue and S.val4  <= S.endvalue then case when S.val3 < S.val4 then '2' else '1' end  else '1' end else '0' end +
        case when S.val4 <= S.val5   then case when S.val5  >= S.startvalue and S.val5  <= S.endvalue then case when S.val4 < S.val5 then '2' else '1' end  else '1' end else '0' end +
        case when S.val5 <= S.val6   then case when S.val6  >= S.startvalue and S.val6  <= S.endvalue then case when S.val5 < S.val6 then '2' else '1' end  else '1' end else '0' end +
        case when S.val6 <= S.val7   then case when S.val6  >= S.startvalue and S.val7  <= S.endvalue then case when S.val6 < S.val7 then '2' else '1' end  else '1' end else '0' end +
        case when S.val7 <= S.val8   then case when S.val8  >= S.startvalue and S.val8  <= S.endvalue then case when S.val7 < S.val8 then '2' else '1' end  else '1' end else '0' end +
        case when S.val8 <= S.val9   then case when S.val9  >= S.startvalue and S.val9  <= S.endvalue then case when S.val8 < S.val9 then '2' else '1' end  else '1' end else '0' end +
        case when S.val9 <= S.val10  then case when S.val10 >= S.startvalue and S.val10 <= S.endvalue then case when S.val9 < S.val10 then '2' else '1' end  else '1' end else '0' end +
        case when S.val10 <= S.val11 then case when S.val11 >= S.startvalue and S.val11 <= S.endvalue then case when S.val10 < S.val11 then '2' else '1' end  else '1' end else '0' end +
        case when S.val11 <= S.val12 then case when S.val12 >= S.startvalue and S.val12 <= S.endvalue then case when S.val11 < S.val12 then '2' else '1' end  else '1' end else '0' end  as resulttext
    from @sample_data as S) result

This case will transform each transition to:

'0' is value valN is higher than valN+1

'1' if value matches the limits but valN is equal to valN+1

and '2' if the transition from valN to vanN+1 matches all your
conditions

Than is just a matter of working with the result string.
Uncomment result.resulttext if you want to take a look at the 'transformed' result string.


问:
Facebook Share URL having hash
My single page website has some products, and product details appear as simple pop-up when clicked. For each product there is Facebook share. But when I Facebook-share the url say www.example.com#product1 in the shared url the #product1 get stripped.

```<code>FB.ui({
  method: 'share',
  href: 'http://example.com/#product1',
}, function(response){});
</code>```

When I share it comes as only http://example.com/   , not http://example.com/#product1.   I want the full URL to be shared like http://example.com/#product1. Its getting stripped off somehow.

How to avoid this?

答:
The share dialog now supports the hashtag parameter

```<code>  FB.ui({
    method: 'share',
    href: 'https://developers.facebook.com/docs/',
    hashtag: '#facebook'
  }, function(response){});
</code>```

see the fb docs:
https://developers.facebook.com/docs/sharing/reference/share-dialog/

Title: Facebook Share URL having hash

Body:
My single page website has some products, and product details appear as simple pop-up when clicked. For each product there is Facebook share. But when I Facebook-share the url say www.example.com#product1 in the shared url the #product1 get stripped.

FB.ui({
  method: 'share',
  href: 'http://example.com/#product1',
}, function(response){});

When I share it comes as only http://example.com/   , not http://example.com/#product1.   I want the full URL to be shared like http://example.com/#product1. Its getting stripped off somehow.

How to avoid this?

Body:
The share dialog now supports the hashtag parameter

  FB.ui({
    method: 'share',
    href: 'https://developers.facebook.com/docs/',
    hashtag: '#facebook'
  }, function(response){});

see the fb docs:
https://developers.facebook.com/docs/sharing/reference/share-dialog/