问:
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>```

}

答:
Well, the big difference I see is in the order in which objects are allocated.  When preparing after the constructor, your Container allocations are interleaved with your Thread allocations.  When preparing prior to execution, your Threads are all allocated first, then your Containers are all allocated.

I don't know a whole lot about memory issues in multi-processor environments, but if I had to guess, maybe in the second case the Container allocations are more likely to be allocated in the same memory page, and perhaps the processors are slowed down due to contention for the same memory page?

[edit] Following this line of thought, I'd be interested to see what happens if you don't try to write back to the variable, and only read from it, in the Thread's run method.  I would expect the timings difference to go away.

[edit2] See irreputable's answer; he explains it much better than I could

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();
        }
    }
}

}


来源: stackexchange

问:
How can I make my front end app access my node server apis
I have created a front end app by creat-react-app.

The command "npm run start" can create a webpack-dev-server and serve my

front end app for developing. Here is the problem comes:

My front end app must request some api from a node server I had created before.

By default create-react-app start a webpack-dev-server on port 3000

My node server was started on port 3001

Access port 3001 directly may cause cross-origin problems

How can I gracefully start my developing story from those problems !

答:
The easiest way to overcome CORS issues is to use npm module for cors.
Install it in your project using:

```<code>npm i cors
</code>```

Then include it in your app.js file like this:

```<code>const cors = require('cors');
</code>```

and then use it as a middleware in your app.js like this:

```<code>app.use(cors());
</code>```

And this should do!
Hope this helps!!

ContentLicense: CC BY-SA 4.0

Body:
The easiest way to overcome CORS issues is to use npm module for cors.
Install it in your project using:

npm i cors

Then include it in your app.js file like this:

const cors = require('cors');

and then use it as a middleware in your app.js like this:

app.use(cors());

And this should do!
Hope this helps!!


问:
Debug of Angular Dart stopped working in PhpStorm
I have quite big Angular Dart project in PhpStorm. I was able to debug it, but suddenly it doesn't work anymore (for few weeks). I'm not sure what's the reason as I upgraded PhpStorm, Dart Plugin and Dart. But I expect debug to be working with all updates.
I created the simpliest Angular Dart app (ToDo example) to see if it helps. It didn't.

```<code>Dart VM version: 2.3.1 (Tue May 21 19:28:38 2019 +0200) on "linux_x64"

PhpStorm 2019.1.2
Build #PS-191.7141.52, built on May 8, 2019
JRE: 1.8.0_202-release-1483-b49 amd64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Linux 5.0.17-300.fc30.x86_64

PhpStorm Dart plugin v191.7221

Google Chrome Version 74.0.3729.169 (Official build) (64bit)
</code>```

Dart is listening on port 53322 for HTTP connections from browser, PhpStorm is listening on debug port 63344 (and has a connection from Chrome), Chrome is listening on debug port 45389 (and has a connection from PhpStorm).

When I open http://localhost:53322/index.html I see the app, but the execution is not stopped on breakpoints.

I've found similar bugs (https://youtrack.jetbrains.com/issue/WEB-30593, Angular dart on WebStorm. Debug is no more working) but the provided solutions didn't help.

Is there a way to make debug working again? I'd like to avoid downgrading.

答:
Not specific to Angular - debugging web apps doesn't work with SDK 2.3.1. Please follow WEB-39095 for updates.

Workarounds:

Start debug session from WebStorm. Breakpoints won't work. Stop Debug
session.

Without closing the project go to Terminal and run pub global activate webdev 1.0.1.

Start debug session from WebStorm again. Breakpoints should work.

Or:

Run webdev server manually from Terminal explicitly specifying hostname, for example: pub global run webdev serve --hostname 127.0.0.1 web:53322

In the IDE create JavaScript Debug run configuration that opens webdev URL directly, e.g. http://localhost:53322/index.html, press Debug

Update: it was a bug in webdev (no sourcemaps on ipv4). Bug is fixed in webdev 2.0.7. No actions needed, WebStorm will auto-update webdev automatically to the latest version

Body:
I have quite big Angular Dart project in PhpStorm. I was able to debug it, but suddenly it doesn't work anymore (for few weeks). I'm not sure what's the reason as I upgraded PhpStorm, Dart Plugin and Dart. But I expect debug to be working with all updates.
I created the simpliest Angular Dart app (ToDo example) to see if it helps. It didn't.

Dart VM version: 2.3.1 (Tue May 21 19:28:38 2019 +0200) on "linux_x64"

PhpStorm 2019.1.2
Build #PS-191.7141.52, built on May 8, 2019
JRE: 1.8.0_202-release-1483-b49 amd64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Linux 5.0.17-300.fc30.x86_64

PhpStorm Dart plugin v191.7221

Google Chrome Version 74.0.3729.169 (Official build) (64bit)

Dart is listening on port 53322 for HTTP connections from browser, PhpStorm is listening on debug port 63344 (and has a connection from Chrome), Chrome is listening on debug port 45389 (and has a connection from PhpStorm).

When I open http://localhost:53322/index.html I see the app, but the execution is not stopped on breakpoints.

I've found similar bugs (https://youtrack.jetbrains.com/issue/WEB-30593, Angular dart on WebStorm. Debug is no more working) but the provided solutions didn't help.

Is there a way to make debug working again? I'd like to avoid downgrading.


问:
How to ping a website from Java Android Studio
I am currently developing an application with Android studio that needs an Internet connection to work. I would like to check the internet access at the start of the application by pinging my website. I already tried the method ConnectivityManager but it just checks if the user is connected to the wifi or mobile data. How could I ping any website to check if the phone has internet access?

答:
You can check different connection-types by using the TelephonyManager like so:

```<code>public boolean hasNetworkAccess() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getNetworkInfo(cm.getActiveNetwork());

        return info.isConnected();
    }

    public String connectionStrength() {
        if (!hasNetworkAccess()) {
            return "NOT_CONNECTED";
        }

        TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);

        // switch for different network types (e.g. 4G, EDGE, ...)
        switch (tm.getNetworkType()) {
            case TelephonyManager.NETWORK_TYPE_EDGE:
                // return a value that you want to identify the strength with
                return "EDGE";
            // ...
            default:
                return null;
        }
    }
</code>```

Dont forget to add the <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> in the manifest above the application tag

Body:
You can check different connection-types by using the TelephonyManager like so:

public boolean hasNetworkAccess() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getNetworkInfo(cm.getActiveNetwork());

        return info.isConnected();
    }

    public String connectionStrength() {
        if (!hasNetworkAccess()) {
            return "NOT_CONNECTED";
        }

        TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);

        // switch for different network types (e.g. 4G, EDGE, ...)
        switch (tm.getNetworkType()) {
            case TelephonyManager.NETWORK_TYPE_EDGE:
                // return a value that you want to identify the strength with
                return "EDGE";
            // ...
            default:
                return null;
        }
    }

Dont forget to add the <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> in the manifest above the application tag


问:
Django pagination returns all data after clicking any page number in search result
I paginated the search result. For the first, query set gives me perfect result , but when i click on any page number, it accepts search key as null and get all data from db. here is the code

Views.py

```<code>def youtube_search(request):

    query = request.GET.get('q')
    Q = SearchDetail.objects.all().filter(query = query).order_by('-datetime')

    if request.method=='GET':
        page_request_var = 'page'
        page = request.GET.get(page_request_var)
        paginator = Paginator(Q, 10)
        try:
            paginated_queryset = paginator.page(page)
        except PageNotAnInteger:
            paginated_queryset = paginator.page(1)
        except EmptyPage:
            paginated_queryset =     paginator.page(paginator.num_pages)

    context = {
        'queryset': paginated_queryset,
        'page_request_var': page_request_var,
        'searchKey':query
        }

    return render(request, 'home.html', context)
</code>```

here is my template

Home.html

```<code><!DOCTYPE html>
<html>
<body>
    <header>
        <h3 class="h6">Search the blog</h3>
    </header>
    <form action="{% url 'search' %}" class="search-form">
        <div class="form-group">
        <input type="text" name="q" placeholder="What are you looking for?">
        <button type="submit">search</button>
        </div>
    </form>

{% for Q in queryset %}

    {{Q.title}}<br/>
    {{Q.description}}<br/>
    {{Q.datetime}}<br/>
    {{Q.thumbnail}}<br/>

{% endfor %}

<nav aria-label="Page navigation example">
          <ul class="pagination pagination-template d-flex justify-content-center">
            {% if queryset.has_previous %}
            <li class="page-item"><a href="?{{ page_request_var }}={{ queryset.previous_page_number }}" class="page-link"> <i class="fa fa-angle-left"></i></a></li>
            {% endif %}

                  {% for num in queryset.paginator.page_range %}

                        {% if queryset.number == num %}
                         <li class="page-item"><a href="?{{ page_request_var }}={{ queryset.number }}" class="page-link active">{{ num }}</a></li>

                        {% elif num > queryset.number|add:'-3' and num < queryset.number|add:'3' %}

                        <li class="page-item"><a href="?{{ page_request_var }}={{ num }}" class="page-link ">{{ num }}</a></li>

                        {% endif %}

                  {% endfor %}
            {% if queryset.has_next %}
            <li class="page-item"><a href="?{{ page_request_var }}={{ queryset.next_page_number }}" class="page-link"> <i class="fa fa-angle-right"></i></a></li>
            {% endif %}

          </ul>
        </nav>
</code>```

I searched stackoverflow for solutions.None of them answered my question
I tried every piece of code i got from google.help me solve this

答:
generic ListView:

```<code>from django.views.generic import ListView

class YoutubeSearchView(ListView):
    template_name = 'home.html'
    model = SearchDetail
    paginate_by = 10
    context_object_name = 'search_objects'

    def get_queryset(self):
        query = self.request.GET.get('q', None)
        if query:
            return SearchDetail.objects.filter(query__icontains=query).order_by('-datetime')
        return SearchDetail.objects.none()

    def get_context_data(self, **kwargs):
        context = super(YoutubeSearchView, self).get_context_data(**kwargs)
        context['searchKey'] = self.request.GET.get('q')
        return context
</code>```

home.html:

```<code>{% load mathfilters %}
<!DOCTYPE html>
<html>
<body>
    <header>
        <h3 class="h6">Search the blog</h3>
    </header>
    <form action="{% url 'search' %}" class="search-form">
        <div class="form-group">
        <input type="text" name="q" placeholder="What are you looking for?">
        <button type="submit">search</button>
        </div>
    </form>

{% for Q in search_objects %}
    {{Q.title}}<br/>
    {{Q.description}}<br/>
    {{Q.datetime}}<br/>
    {{Q.thumbnail}}<br/>
{% endfor %}

<nav aria-label="Page navigation example">
    <ul class="pagination pagination-template d-flex justify-content-center">
        {% if page_obj.has_previous %}
            <li class="page-item">
                <a href="?page={{ page_obj.previous_page_number }}" class="page-link">
                    <i class="fa fa-angle-left"></i>
                </a>
            </li>
        {% endif %}
            {% for num in page_obj.paginator.page_range %}
                {% if page_obj.number == num %}
                    <li class="page-item">
                        <a href="?page={{ page_obj.number }}" class="page-link active">
                            {{ num }}
                        </a>
                    </li>
                {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
                <li class="page-item">
                    <a href="?page={{ num }}" class="page-link ">
                        {{ num }}
                    </a>
                </li>
            {% endif %}
        {% endfor %}
        {% if page_obj.has_next %}
            <li class="page-item">
                <a href="?page={{ page_obj.next_page_number }}" class="page-link">
                    <i class="fa fa-angle-right"></i>
                </a>
            </li>
        {% endif %}
    </ul>
</nav>
</code>```

Body:
I paginated the search result. For the first, query set gives me perfect result , but when i click on any page number, it accepts search key as null and get all data from db. here is the code

Views.py

def youtube_search(request):

    query = request.GET.get('q')
    Q = SearchDetail.objects.all().filter(query = query).order_by('-datetime')

    if request.method=='GET':
        page_request_var = 'page'
        page = request.GET.get(page_request_var)
        paginator = Paginator(Q, 10)
        try:
            paginated_queryset = paginator.page(page)
        except PageNotAnInteger:
            paginated_queryset = paginator.page(1)
        except EmptyPage:
            paginated_queryset =     paginator.page(paginator.num_pages)

    context = {
        'queryset': paginated_queryset,
        'page_request_var': page_request_var,
        'searchKey':query
        }

    return render(request, 'home.html', context)

here is my template

Home.html

<!DOCTYPE html>

Search the blog

    <form action="{% url 'search' %}" class="search-form">

        <input type="text" name="q" placeholder="What are you looking for?">
        <button type="submit">search</button>

    </form>

{% for Q in queryset %}

    {{Q.title}}

    {{Q.description}}

    {{Q.datetime}}

    {{Q.thumbnail}}

{% endfor %}

            {% if queryset.has_previous %}

            {% endif %}

                  {% for num in queryset.paginator.page_range %}

                        {% if queryset.number == num %}

{{ num }}

                        {% elif num > queryset.number|add:'-3' and num < queryset.number|add:'3' %}

{{ num }}

                        {% endif %}

                  {% endfor %}
            {% if queryset.has_next %}

            {% endif %}

I searched stackoverflow for solutions.None of them answered my question
I tried every piece of code i got from google.help me solve this

Body:
generic ListView:

from django.views.generic import ListView

class YoutubeSearchView(ListView):
    template_name = 'home.html'
    model = SearchDetail
    paginate_by = 10
    context_object_name = 'search_objects'

    def get_queryset(self):
        query = self.request.GET.get('q', None)
        if query:
            return SearchDetail.objects.filter(query__icontains=query).order_by('-datetime')
        return SearchDetail.objects.none()

    def get_context_data(self, **kwargs):
        context = super(YoutubeSearchView, self).get_context_data(**kwargs)
        context['searchKey'] = self.request.GET.get('q')
        return context

home.html:

{% load mathfilters %}
<!DOCTYPE html>
<html>
<body>
    <header>
        <h3 class="h6">Search the blog</h3>
    </header>
    <form action="{% url 'search' %}" class="search-form">
        <div class="form-group">
        <input type="text" name="q" placeholder="What are you looking for?">
        <button type="submit">search</button>
        </div>
    </form>

{% for Q in search_objects %}
    {{Q.title}}<br/>
    {{Q.description}}<br/>
    {{Q.datetime}}<br/>
    {{Q.thumbnail}}<br/>
{% endfor %}

<nav aria-label="Page navigation example">
    <ul class="pagination pagination-template d-flex justify-content-center">
        {% if page_obj.has_previous %}
            <li class="page-item">
                <a href="?page={{ page_obj.previous_page_number }}" class="page-link">
                    <i class="fa fa-angle-left"></i>
                </a>
            </li>
        {% endif %}
            {% for num in page_obj.paginator.page_range %}
                {% if page_obj.number == num %}
                    <li class="page-item">
                        <a href="?page={{ page_obj.number }}" class="page-link active">
                            {{ num }}
                        </a>
                    </li>
                {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
                <li class="page-item">
                    <a href="?page={{ num }}" class="page-link ">
                        {{ num }}
                    </a>
                </li>
            {% endif %}
        {% endfor %}
        {% if page_obj.has_next %}
            <li class="page-item">
                <a href="?page={{ page_obj.next_page_number }}" class="page-link">
                    <i class="fa fa-angle-right"></i>
                </a>
            </li>
        {% endif %}
    </ul>
</nav>


问:
Copy same non contiguous data at same cell address from multiple worksheets and paste in one master worksheet
How to copy non contiguous cells(A2,B4,D5,E1,F3) from different sheets(sheet1 to sheet 4) and paste in one master sheets ("sheet5") row by row?

The output should look in a tabular form:

```<code>cell A2 cell B4 cell D5 cell E1 cell F3 sheet 1
cell A2 cell B4 cell D5 cell E1 cell F3 sheet 2
cell A2 cell B4 cell D5 cell E1 cell F3 sheet 3
cell A2 cell B4 cell D5 cell E1 cell F3 sheet 4
</code>```

Dim cel As Range, pasteRange As Range

Dim sht As Worksheet

Set pasteRange = ActiveWorkbook.Sheets("Sheet5").Range("A2")

   For Each sht In Sheets
      If sht.name <> "Sheet5" Then

        For Each cel In sht.Range("A2, B4, D5, E1, F3")

            pasteRange.Value = cel.Value

            Set pasteRange = pasteRange.Offset(0, 1)

        Next

    End If

Next
```

答:
See if this helps:

Dim cel As Range, pasteRange As Range
Dim X As Long, Z As Long
Dim wb As Workbook: Set wb = ActiveWorkbook

Set pasteRange = wb.Sheets("Sheet5").Range("A2")

For X = 1 To 4
    With wb.Sheets("Sheet" & X)
        For Each cel In .Range("A2, B4, D5, E1, F3")
            pasteRange.Offset(X - 1, Y).Value = cel.Value
            Y = Y + 1
        Next cel
    End With
    Y = 0
Next X
```

Body:
How to copy non contiguous cells(A2,B4,D5,E1,F3) from different sheets(sheet1 to sheet 4) and paste in one master sheets ("sheet5") row by row?

The output should look in a tabular form:

cell A2 cell B4 cell D5 cell E1 cell F3 sheet 1
cell A2 cell B4 cell D5 cell E1 cell F3 sheet 2
cell A2 cell B4 cell D5 cell E1 cell F3 sheet 3
cell A2 cell B4 cell D5 cell E1 cell F3 sheet 4

Dim cel As Range, pasteRange As Range

Dim sht As Worksheet

Set pasteRange = ActiveWorkbook.Sheets("Sheet5").Range("A2")

   For Each sht In Sheets
      If sht.name <> "Sheet5" Then

        For Each cel In sht.Range("A2, B4, D5, E1, F3")

            pasteRange.Value = cel.Value

            Set pasteRange = pasteRange.Offset(0, 1)

        Next

    End If

Next


问:
Complete list of React JSX component properties
Is there any particular website that contains a complete list of properties for all JSX components?

For example: <button> has onClick and much more.

答:
React exposes list of different SyntheticEvents. You can read all about them here

Also react has all DOM properties and attributes but they are all should be camelCased. You can read more about that here.

Also be sure you actually understand difference between JS, onclick DOM handler, and React synthetic event onClick:

JavaScript has nothing to do with DOM onclick handler. That API is given to JS by browsers but there are no mention about that handler in ES specification.

React has its own synthetic events. They are a little bit different from DOM events. Main difference is that React tried to make them cross-browser.


问:
Why this sprintf statement crashing?
```<code>char filebuf[256];
path current = current_path();
std::cout<<"CurrentWorking "<<current<<endl;
string _UserDir = "TTiTraceLogs";
sprintf(filebuf,"%s/%s",current,_UserDir); ///crashing here
</code>```

If I format only current, then it is ok.

```<code>sprintf(filebuf,"%s",current);
</code>```

Output:

```<code>CurrentWorking D:/working/eclipse_projects/sadftp/CollectTTiTraceSept10_1009_174
_higher/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/Release
</code>```

答:
Some of your code is unclear (e.g., what on earth is a path type?), but it looks like you're trying to print a std::string via a C-style string formatter (sprintf %s), which is totally invalid.

Look at std::stringstream.  Also, for simple concatenation, std::string provides a + operator overload.  So you could be doing simply:

```<code>current + "/" + whatever
</code>```

ContentLicense: CC BY-SA 3.0

Title: Why this sprintf statement crashing?

Body:
char filebuf[256];
path current = current_path();
std::cout<<"CurrentWorking "<<current<<endl;
string _UserDir = "TTiTraceLogs";
sprintf(filebuf,"%s/%s",current,_UserDir); ///crashing here

If I format only current, then it is ok.

sprintf(filebuf,"%s",current);

Output:

CurrentWorking D:/working/eclipse_projects/sadftp/CollectTTiTraceSept10_1009_174
_higher/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/Release

Body:
Some of your code is unclear (e.g., what on earth is a path type?), but it looks like you're trying to print a std::string via a C-style string formatter (sprintf %s), which is totally invalid.

Look at std::stringstream.  Also, for simple concatenation, std::string provides a + operator overload.  So you could be doing simply:

current + "/" + whatever


问:
Header Title not centered in React Native using native-base
I'm using native-base to create a React Native app:

I'm using the Header Component to display Body, Left and Right elements. According to the docs, the title should automatically center but it does not (as seen below).

Am I missing something simple here? Any help would be appreciated!

```<code>import {
    Container,
    Header,
    Content,
    Left,
    Right,
    Body,
    Title,
    Icon
} from "native-base"

export default class Seminars extends React.Component{

    render(){
        return(
            <Container style={styles.container}>
                <Header style={styles.header}>
                    <Left>
                        <Icon name='arrow-back' />
                    </Left>
                    <Body>
                        <Title>Seminars</Title>
                    </Body>
                    <Right>
                        <Icon name='menu' />
                    </Right>
                </Header>
                <Content contentContainerStyle={styles.content} >
                    <Text>Content Here</Text>
                </Content>
            </Container>
        )
    }
}
const styles = StyleSheet.create({
    container: {

    },
    header: {
        paddingRight: 15,
        paddingLeft: 15
    },
    content: {
        display: "flex",
        flex: 1,
        justifyContent: "center",
        padding: 15
    }
});
</code>```

答:
You can also try this one:</p>

```<code>      <Header>
          <Left style={{ flex: 1 }}>
            <Icon name="arrow-back" />
          </Left>
          <Body style={{ flex: 1 }}>
            <Title style={{ alignSelf: "center" }}>Seminars</Title>
          </Body>
          <Right style={{ flex: 1 }}>
            <Icon name="menu" />
          </Right>
        </Header>
</code>```

Body:
I'm using native-base to create a React Native app:

I'm using the Header Component to display Body, Left and Right elements. According to the docs, the title should automatically center but it does not (as seen below).

Am I missing something simple here? Any help would be appreciated!

import {
    Container,
    Header,
    Content,
    Left,
    Right,
    Body,
    Title,
    Icon
} from "native-base"

export default class Seminars extends React.Component{

    render(){
        return(
            <Container style={styles.container}>

                    <Left>
                        <Icon name='arrow-back' />
                    </Left>

                        <Title>Seminars</Title>

                    <Right>
                        <Icon name='menu' />
                    </Right>

                <Content contentContainerStyle={styles.content} >
                    <Text>Content Here</Text>
                </Content>
            </Container>
        )
    }
}
const styles = StyleSheet.create({
    container: {

    },
    header: {
        paddingRight: 15,
        paddingLeft: 15
    },
    content: {
        display: "flex",
        flex: 1,
        justifyContent: "center",
        padding: 15
    }
});

Body:
You can also try this one:

      <Header>
          <Left style={{ flex: 1 }}>
            <Icon name="arrow-back" />
          </Left>
          <Body style={{ flex: 1 }}>
            <Title style={{ alignSelf: "center" }}>Seminars</Title>
          </Body>
          <Right style={{ flex: 1 }}>
            <Icon name="menu" />
          </Right>
        </Header>


问:
How can I add a ViewController into my Header?
I want to add my ViewController into the header  of my OverViewController. I wrote an extension to add a Child View as a subview but I do not know how to add it into the header of my ViewController.

```<code>extension UIViewController {

    func add(_ child: UIViewController) {

        //add Child View controller
        addChildViewController(child)

        //add Child View as subview
        view.addSubview(child.view)

        //notify Child View Controller
        child.didMove(toParentViewController: self)
    }
}
</code>```

ViewController should be displayed in the header.

答:
You need to provide both the childController you want to add and the view of parentController in which you want to add the childController, i.e.

```<code>extension UIViewController {
    func addChild(_ controller: UIViewController, in containerView: UIView) {
        self.addChildViewController(controller)
        controller.view.frame = containerView.bounds
        containerView.addSubview(controller.view)
    }
}
</code>```

In the above code:

controller - it is the controller that you want to add as child to other controller

containerView - the view of parentController in which you want to add the childController

Usage:

```<code>class ViewController: UIViewController {
    @IBOutlet weak var containerView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        if let controller = self.storyboard?.instantiateViewController(withIdentifier: "VC") {
            self.addChild(controller, in: self.containerView)
        }
    }
}
</code>```

In the above code, I'm adding a controller with identifier - VC as child to containerView.

Body:
I want to add my ViewController into the header  of my OverViewController. I wrote an extension to add a Child View as a subview but I do not know how to add it into the header of my ViewController.

extension UIViewController {

    func add(_ child: UIViewController) {

        //add Child View controller
        addChildViewController(child)

        //add Child View as subview
        view.addSubview(child.view)

        //notify Child View Controller
        child.didMove(toParentViewController: self)
    }
}

ViewController should be displayed in the header.

Body:
You need to provide both the childController you want to add and the view of parentController in which you want to add the childController, i.e.

extension UIViewController {
    func addChild(_ controller: UIViewController, in containerView: UIView) {
        self.addChildViewController(controller)
        controller.view.frame = containerView.bounds
        containerView.addSubview(controller.view)
    }
}

In the above code:

controller - it is the controller that you want to add as child to other controller

containerView - the view of parentController in which you want to add the childController

Usage:

class ViewController: UIViewController {
    @IBOutlet weak var containerView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        if let controller = self.storyboard?.instantiateViewController(withIdentifier: "VC") {
            self.addChild(controller, in: self.containerView)
        }
    }
}

In the above code, I'm adding a controller with identifier - VC as child to containerView.


问:
Is there anyway to identify the touched node in ARKit?
I am using ARKit to project a 3D file. In that 3D there are multiple sub nodes. When a user touches on any node we have to display some information about the touched node.

Is there any way we could identify on which node the user touched?

答:
You can perform a hit test to identify which node user has touched. Assuming you have two nodes in your scene, for example:

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

    let scene = SCNScene()

    let node1 = SCNNode()
    node1.name = "node1"
    let node2 = SCNNode()
    node2.name = "node2"

    scene.rootNode.addChildNode(node1)
    scene.rootNode.addChildNode(node2)

    sceneView.scene = scene

    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapped))
    sceneView.addGestureRecognizer(tapGestureRecognizer)
}
</code>```

In your tap handler, you can detect the touched node and perform any logic you need, like displaying some information about the node.

```<code>@objc func tapped(recognizer: UIGestureRecognizer) {
    guard let sceneView = recognizer.view as? SCNView else { return }
    let touchLocation = recognizer.location(in: sceneView)

    let results = sceneView.hitTest(touchLocation, options: [:])

    if results.count == 1 {
        let node = results[0].node
        print(node.name) // prints "node1" or "node2" if user touched either of them
        if node.name == "node1" {
            // display node1 information
        } else if node.name == "node2" {
            // display node2 information
        }
    }
}
</code>```

Body:
You can perform a hit test to identify which node user has touched. Assuming you have two nodes in your scene, for example:

override func viewDidLoad() {
    ...

    let scene = SCNScene()

    let node1 = SCNNode()
    node1.name = "node1"
    let node2 = SCNNode()
    node2.name = "node2"

    scene.rootNode.addChildNode(node1)
    scene.rootNode.addChildNode(node2)

    sceneView.scene = scene

    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapped))
    sceneView.addGestureRecognizer(tapGestureRecognizer)
}

In your tap handler, you can detect the touched node and perform any logic you need, like displaying some information about the node.

@objc func tapped(recognizer: UIGestureRecognizer) {
    guard let sceneView = recognizer.view as? SCNView else { return }
    let touchLocation = recognizer.location(in: sceneView)

    let results = sceneView.hitTest(touchLocation, options: [:])

    if results.count == 1 {
        let node = results[0].node
        print(node.name) // prints "node1" or "node2" if user touched either of them
        if node.name == "node1" {
            // display node1 information
        } else if node.name == "node2" {
            // display node2 information
        }
    }
}


问:
GDB Eigen Debugging with Conditional Breakpoints Failing
I'm trying to debug with GDB using conditional breakpoints on an Eigen object. For instance, I'd like to break when any values in my vector are nonzero. I would do this in GDB:

```<code>break cpp/File.cpp:143 if (v != 0).any()
</code>```

However, this doesn't work. GDB gives this:

```<code>Could not find operator!=
</code>```

even though this is perfectly valid syntax. Moreover, a conditional breakpoint like

```<code>break cpp/File.cpp:143 if v[0] != 0
</code>```

gives this error in GDB:

```<code>Error in testing breakpoint condition:
Couldn't get registers: No such process.
An error occurred while in a function called from GDB.
Evaluation of the expression containing the function
(Eigen::DenseCoeffsBase<Eigen::Array<int, 3, 1, 0, 3, 1>, 1>::operator[](long)) will be abandoned.
When the function is done executing, GDB will silently stop.
</code>```

The code was compiled with -O0 -g -fno-inline. How do I debug the contents of an Eigen object?

答:
According to this question, (sometimes) GDB seems to have problems with overloaded operators. You could try one of these alternatives:

```<code>if (! v.isZero())

if (! v.cwiseEqual(0).all())
</code>```

And instead of if v[0] != 0 you could try one of these:

```<code> if (v.data()[0] != 0)

 if (v.coeff(0) != 0)
</code>```

Body:
I'm trying to debug with GDB using conditional breakpoints on an Eigen object. For instance, I'd like to break when any values in my vector are nonzero. I would do this in GDB:

break cpp/File.cpp:143 if (v != 0).any()

However, this doesn't work. GDB gives this:

Could not find operator!=

even though this is perfectly valid syntax. Moreover, a conditional breakpoint like

break cpp/File.cpp:143 if v[0] != 0

gives this error in GDB:

Error in testing breakpoint condition:
Couldn't get registers: No such process.
An error occurred while in a function called from GDB.
Evaluation of the expression containing the function
(Eigen::DenseCoeffsBase<Eigen::Array<int, 3, 1, 0, 3, 1>, 1>::operator[](long)) will be abandoned.
When the function is done executing, GDB will silently stop.

The code was compiled with -O0 -g -fno-inline. How do I debug the contents of an Eigen object?

Body:
According to this question, (sometimes) GDB seems to have problems with overloaded operators. You could try one of these alternatives:

if (! v.isZero())

if (! v.cwiseEqual(0).all())

And instead of if v[0] != 0 you could try one of these:

 if (v.data()[0] != 0)

 if (v.coeff(0) != 0)


问:
write function not working properly in python
I wrote a code to produce the following output. It works fine when I use append function in marked line in code but when i use ''w' write function it, it only prints one line in the new created text file. Problem to use append function is if we run the code again it copies same output twice. I am not able to understand this . Please Help  Thanks in advance

Code I used:

```<code>import os
with open("input5.csv", 'r+') as fd:
    lines = fd.readlines()
    fd.seek(0)
    fd.writelines(line for line in lines if line.strip())
    fd.truncate()

lines = open('input5.csv').readlines()
open('output1.txt', 'w').writelines(lines[1:-2])

with open('output1.txt', 'r+') as m:
    newText = m.read()
    while ',' in newText:
        newText = newText.replace(',', '_')
with open('output1.txt', "w") as m:
    m.write(newText)

with open("output1.txt","r+") as fp:
    for cnt, line in enumerate(fp):
        line=line.replace('_',',',3)
        print(line)
        f = open('output7.txt', 'a') #THIS LINE
        for i in range(len(line)):
            f.write((line[i]))
        f.close()
os.remove("output1.txt")
</code>```

Input:

```<code>id,name,amount,subject
1,abc,55,"s1,s2,s3"
1,abc1,56,"s4,s5,s6"
1,abc2,57,"s7,s8,s9"
1,abc3,58,"s10,s11,s12"
1,abc4,59,"s13,s14,s15"
1,abc5,59,"s16,s17,s18"
1,abc6,59,"s13,s14,s15"
1,abc7,59,"s13,s14,s15"
1,abc8,59,"s13,s14,s15"
1,abc9,59,"s13,s14,s15"
this file is done
time taken; 22nd
</code>```

expected output:(This is the code i get when use append function marked line of the code)

```<code>1,abc,55,"s1_s2_s3"
1,abc1,56,"s4_s5_s6"
1,abc2,57,"s7_s8_s9"
1,abc3,58,"s10_s11_s12"
1,abc4,59,"s13_s14_s15"
1,abc5,59,"s16_s17_s18"
1,abc6,59,"s13_s14_s15"
1,abc7,59,"s13_s14_s15"
1,abc8,59,"s13_s14_s15"
1,abc9,59,"s13_s14_s15"
</code>```

Output i get when I replace append with write function in marked line of code:

```<code>1,abc9,59,"s13_s14_s15"
</code>```

答:
On my machine (Ubuntu 18.04) with python 3.6.7 your example works as expected.

output7.txt contains

```<code>1,abc,55,"s1_s2_s3"
1,abc1,56,"s4_s5_s6"
1,abc2,57,"s7_s8_s9"
1,abc3,58,"s10_s11_s12"
1,abc4,59,"s13_s14_s15"
1,abc5,59,"s16_s17_s18"
1,abc6,59,"s13_s14_s15"
1,abc7,59,"s13_s14_s15"
</code>```

So, the write function does work properly. However, it is a good question, why doesn't it work for you.

Body:
I wrote a code to produce the following output. It works fine when I use append function in marked line in code but when i use ''w' write function it, it only prints one line in the new created text file. Problem to use append function is if we run the code again it copies same output twice. I am not able to understand this . Please Help  Thanks in advance

Code I used:

import os
with open("input5.csv", 'r+') as fd:
    lines = fd.readlines()
    fd.seek(0)
    fd.writelines(line for line in lines if line.strip())
    fd.truncate()

lines = open('input5.csv').readlines()
open('output1.txt', 'w').writelines(lines[1:-2])

with open('output1.txt', 'r+') as m:
    newText = m.read()
    while ',' in newText:
        newText = newText.replace(',', '_')
with open('output1.txt', "w") as m:
    m.write(newText)

with open("output1.txt","r+") as fp:
    for cnt, line in enumerate(fp):
        line=line.replace('_',',',3)
        print(line)
        f = open('output7.txt', 'a') #THIS LINE
        for i in range(len(line)):
            f.write((line[i]))
        f.close()
os.remove("output1.txt")

Input:

id,name,amount,subject
1,abc,55,"s1,s2,s3"
1,abc1,56,"s4,s5,s6"
1,abc2,57,"s7,s8,s9"
1,abc3,58,"s10,s11,s12"
1,abc4,59,"s13,s14,s15"
1,abc5,59,"s16,s17,s18"
1,abc6,59,"s13,s14,s15"
1,abc7,59,"s13,s14,s15"
1,abc8,59,"s13,s14,s15"
1,abc9,59,"s13,s14,s15"
this file is done
time taken; 22nd

expected output:(This is the code i get when use append function marked line of the code)

1,abc,55,"s1_s2_s3"
1,abc1,56,"s4_s5_s6"
1,abc2,57,"s7_s8_s9"
1,abc3,58,"s10_s11_s12"
1,abc4,59,"s13_s14_s15"
1,abc5,59,"s16_s17_s18"
1,abc6,59,"s13_s14_s15"
1,abc7,59,"s13_s14_s15"
1,abc8,59,"s13_s14_s15"
1,abc9,59,"s13_s14_s15"

Output i get when I replace append with write function in marked line of code:

1,abc9,59,"s13_s14_s15"

Body:
On my machine (Ubuntu 18.04) with python 3.6.7 your example works as expected.

output7.txt contains

1,abc,55,"s1_s2_s3"
1,abc1,56,"s4_s5_s6"
1,abc2,57,"s7_s8_s9"
1,abc3,58,"s10_s11_s12"
1,abc4,59,"s13_s14_s15"
1,abc5,59,"s16_s17_s18"
1,abc6,59,"s13_s14_s15"
1,abc7,59,"s13_s14_s15"

So, the write function does work properly. However, it is a good question, why doesn't it work for you.


问:
Filter dataframe with NA by a column condition in r
I have a dataframe :

```<code>df <- data.frame( Date = c("2017-02-23", "2017-02-23", "2017-02-24", "2017-02-24", "2017-02-25", "2017-02-25", "2017-02-25"),
                     var = c(2, NA, 1, 1,1, 7, 4))
</code>```

I want to filter by date where var == 7

I tried with:

```<code>df %>% filter(Date[var  == 7])
</code>```

But there is an error: Argument 2 filter condition does not evaluate to a logical vector

What is wrong with this code?

答:
You can use dplyr package

```<code>> df %>% filter(var == 7)

        Date  var
 1 2017-02-25   7
</code>```

Body:
I have a dataframe :

df <- data.frame( Date = c("2017-02-23", "2017-02-23", "2017-02-24", "2017-02-24", "2017-02-25", "2017-02-25", "2017-02-25"),
                     var = c(2, NA, 1, 1,1, 7, 4))

I want to filter by date where var == 7

I tried with:

df %>% filter(Date[var  == 7])

But there is an error: Argument 2 filter condition does not evaluate to a logical vector

What is wrong with this code?

Body:
You can use dplyr package

> df %>% filter(var == 7)

        Date  var
 1 2017-02-25   7


问:
Can't see Access control (IAM) under Subscriptions
I want to give an account access to an Azure account but I can't see "Access control (IAM)" in the subscriptions area. Why might this be? Does it disappear when Active Directory is in use on the account?</p>

答: When there are multiple subscriptions, you need to click through to an individual subscription to see this setting.</p>


问:
how to get iframe innerHTML to represent what is actually visible on the page?
So here's a crazy thing that happened to me.

I want to embed a Google form in a website. I need to automatically populate and hide one of the form fields.

Here is some html:

```<code><!DOCTYPE html>
<html>
  <head> </head>
  <body>
    <iframe
      src="https://docs.google.com/forms/d/e/1FAIpQLSdisob821_bYS5Ya_r460Bn0RHYSB5xqIW6Yz-z4WPwEVjxMQ/viewform?embedded=true"
      width="640"
      height="734"
      frameborder="0"
      marginheight="0"
      marginwidth="0"
      >Loading...</iframe
    >
  </body>
</html>
</code>```

Nice and simple. Now if I run that in my browser (currently Chrome) The form shows up just fine. I see it with my own eyes. I am not intoxicated in any way.

Now in my developer tools console I do this:

```<code>formFrame = document.querySelector("body > iframe");
formFrame.innerHTML;  // the value is "Loading..."
</code>```

So js believes we are still displaying placeholder text? Odd.
I dont really care to work directly with innerHTML. What I want is more like this:

```<code>inputContainers = document.querySelectorAll("div.freebirdFormviewerViewNumberedItemContainer");
</code>```

The length should be 2. It is 0

If I look at the html element tree in my dev tools everything seems to be there as it should be.

I use the "inspect element" function of my dev tools just to make sure the selectors I am using are correct.

I then execute formFrame.innerHTML again. I get the error Uncaught ReferenceError: formFrame is not defined. Gosh

I then execute this again:

```<code>inputContainers = document.querySelectorAll("div.freebirdFormviewerViewNumberedItemContainer")
</code>```

and it returns two elements.

Getting to the point

I assume my messing around with the "inspect element" functionality of my developer tools fired off an event that caused the dom to be populated properly. How do I make that happen from inside my code?

I'm very worried that I might be hitting against some security feature and I wont be able to use google forms in my application.

Any help or insight will be appreciated!

答: It turns out that this is not possible. It's a security feature</p>

Body:
So here's a crazy thing that happened to me.

I want to embed a Google form in a website. I need to automatically populate and hide one of the form fields.

Here is some html:

<!DOCTYPE html>

    Loading...

Nice and simple. Now if I run that in my browser (currently Chrome) The form shows up just fine. I see it with my own eyes. I am not intoxicated in any way.

Now in my developer tools console I do this:

formFrame = document.querySelector("body > iframe");
formFrame.innerHTML;  // the value is "Loading..."

So js believes we are still displaying placeholder text? Odd.
I dont really care to work directly with innerHTML. What I want is more like this:

inputContainers = document.querySelectorAll("div.freebirdFormviewerViewNumberedItemContainer");

The length should be 2. It is 0

If I look at the html element tree in my dev tools everything seems to be there as it should be.

I use the "inspect element" function of my dev tools just to make sure the selectors I am using are correct.

I then execute formFrame.innerHTML again. I get the error Uncaught ReferenceError: formFrame is not defined. Gosh

I then execute this again:

inputContainers = document.querySelectorAll("div.freebirdFormviewerViewNumberedItemContainer")

and it returns two elements.

Getting to the point

I assume my messing around with the "inspect element" functionality of my developer tools fired off an event that caused the dom to be populated properly. How do I make that happen from inside my code?

I'm very worried that I might be hitting against some security feature and I wont be able to use google forms in my application.

Any help or insight will be appreciated!


问:
Numpy vectorization: Find intersection between list and list of lists
I am trying to find the intersection between a list and a list of lists. This is trivially solved with a simple for loop:

```<code>def find_intersec(x,y):
    result = []

    for i in range(len(y)):
        if set(x).intersection(set(y[i])):
            result.append(y[i])

    return(result)

x = [1,2,3,4,5,6]
y = [[1,2,3], [4,5,6], [9,10,11]]

find_intersec(x,y)
</code>```

How can I change the above into a numpy vectorization solution? I have tried numpy.intersect1d() with no success.

答:
You can have a function like this:

```<code>import numpy as np

def find_intersec_vec(x, y):
    y_all = np.concatenate(y)
    y_all_in = np.isin(y_all, x)
    splits = np.cumsum([0] + [len(lst) for lst in y])
    y_in = np.logical_or.reduceat(y_all_in, splits[:-1])
    return [lst for lst, isin in zip(y, y_in) if isin]
</code>```

Test:

```<code>x = [1, 2, 3, 4, 5, 6]
y = [[1, 2, 3], [4, 5], [6, 7], [8, 9, 10, 11]]
print(find_intersec(x, y))
# [[1, 2, 3], [4, 5], [6, 7]]
print(find_intersec_vec(x, y))
# [[1, 2, 3], [4, 5], [6, 7]]
</code>```

Body:
I am trying to find the intersection between a list and a list of lists. This is trivially solved with a simple for loop:

def find_intersec(x,y):
    result = []

    for i in range(len(y)):
        if set(x).intersection(set(y[i])):
            result.append(y[i])

    return(result)

x = [1,2,3,4,5,6]
y = [[1,2,3], [4,5,6], [9,10,11]]

find_intersec(x,y)

How can I change the above into a numpy vectorization solution? I have tried numpy.intersect1d() with no success.

Body:
You can have a function like this:

import numpy as np

def find_intersec_vec(x, y):
    y_all = np.concatenate(y)
    y_all_in = np.isin(y_all, x)
    splits = np.cumsum([0] + [len(lst) for lst in y])
    y_in = np.logical_or.reduceat(y_all_in, splits[:-1])
    return [lst for lst, isin in zip(y, y_in) if isin]

Test:

x = [1, 2, 3, 4, 5, 6]
y = [[1, 2, 3], [4, 5], [6, 7], [8, 9, 10, 11]]
print(find_intersec(x, y))
# [[1, 2, 3], [4, 5], [6, 7]]
print(find_intersec_vec(x, y))
# [[1, 2, 3], [4, 5], [6, 7]]


问:
HTML unordered list sucks in IE7
I've created a HTML ordered list which looks fine in FF, but pretty awful in IE.
My specific problems with the way IE displays the list are:

List markers are missing

Vertical spacing between list items is very uneven

It seems the superscripts are the cause of (2), but I'm not sure how I can fix this problem (without removing the superscripts).

EDIT: I gave up on my single-list dreams and split the list into 3 separate lists. I've removed the link from the text above to avoid confusing future readers.

Thanks,
Don

答: You might see if the bullets are disappearing because you're coupling float-left with padding - not sure how IE counts the bullets as part of the size calcs.</p>

OwnerDisplayName: Don

ContentLicense: CC BY-SA 2.5

Title: HTML unordered list sucks in IE7

LastEditorDisplayName: Don


问:
Problem with loading image in java with FileChooser
I have write a class filechooser where I can choose files. I had searched for a class that loads images but nothing. My filechooser class  can made a panel with button open and save. When I press button open I can search in my documents and when I'm going to open the image my image load class not responding I need some class that can synchronize with me filechooser and load my image from my documents and show it in the panel.

```<code>package project;

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.*;

public class FileChooserDemo extends JPanel
                         implements ActionListener {
    static private final String newline = "\n";
    JButton openButton, saveButton;
    JTextArea log;
    JFileChooser fc;

public FileChooserDemo() {
    super(new BorderLayout());

    //Create the log first, because the action listeners
    //need to refer to it.
    log = new JTextArea(5,20);
    log.setMargin(new Insets(5,5,5,5));
    log.setEditable(false);
    JScrollPane logScrollPane = new JScrollPane(log);

    //Create a file chooser
    fc = new JFileChooser();

    openButton = new JButton("Open a File...");

    openButton.addActionListener(this);

    //Create the save button.  We use the image from the JLF
    //Graphics Repository (but we extracted it from the jar).
    saveButton = new JButton("Save a File...");

    saveButton.addActionListener(this);

    //For layout purposes, put the buttons in a separate panel
    JPanel buttonPanel = new JPanel(); //use FlowLayout
    buttonPanel.add(openButton);
    buttonPanel.add(saveButton);

    //Add the buttons and the log to this panel.
    add(buttonPanel, BorderLayout.PAGE_START);
    add(logScrollPane, BorderLayout.CENTER);
}

public void actionPerformed(ActionEvent e) {

    //Handle open button action.
    if (e.getSource() == openButton) {
        int returnVal = fc.showOpenDialog(FileChooserDemo.this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            //This is where a real application would open the file.
            log.append("Opening: " + file.getName() + "." + newline);

        } else {
            log.append("Open command cancelled by user." + newline);
        }
        log.setCaretPosition(log.getDocument().getLength());

    //Handle save button action.
    } else if (e.getSource() == saveButton) {
        int returnVal = fc.showSaveDialog(FileChooserDemo.this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            //This is where a real application would save the file.
            log.append("Saving: " + file.getName() + "." + newline);
        } else {
            log.append("Save command cancelled by user." + newline);
        }
        log.setCaretPosition(log.getDocument().getLength());
    }
}

/**
 * Create the GUI and show it.  For thread safety,
 * this method should be invoked from the
 * event dispatch thread.
 */
public static void createLoad() {
    //Create and set up the window.
    JFrame frame = new JFrame("FileChooserDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Add content to the window.
    frame.add(new FileChooserDemo());

    //Display the window.
    frame.pack();
    frame.setVisible(true);
}

}
</code>```

this is the class file chooser i need a class that can load the picture i open

and this is the imageload code.

```<code>  import java.awt.*;
  import java.awt.event.*;
  import java.awt.image.*;
  import java.io.*;
  import javax.imageio.*;
  import javax.swing.*;

/**
 * This class demonstrates how to load an Image from an external file
*/
public class LoadImageApp extends Component {

   BufferedImage img;

public void paint(Graphics g) {
    g.drawImage(img, 0, 0, null);
}

public LoadImageApp() {
   try {
       img = ImageIO.read(new File("strawberry.jpg"));
   } catch (IOException e) {
   }

}

public Dimension getPreferredSize() {
    if (img == null) {
         return new Dimension(100,100);
    } else {
       return new Dimension(img.getWidth(null), img.getHeight(null));
   }
}

public static void main(String[] args) {

    JFrame f = new JFrame("Load Image Sample");

    f.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

    f.add(new LoadImageApp());
    f.pack();
    f.setVisible(true);
}
}
</code>```

what i want is the image code read the file.aboslutepath and load the picture when i click it

答:
To get the selected file you should use the getSelectedFile after JFileChooser stop.

To display it:

You can also use a component wich render a Image on it.

This one I made and is under my project is a JPanel extension and let you add components on it (over image)

https://github.com/MarkyVasconcelos/Towel/wiki/JImagePanel

Body:
I have write a class filechooser where I can choose files. I had searched for a class that loads images but nothing. My filechooser class  can made a panel with button open and save. When I press button open I can search in my documents and when I'm going to open the image my image load class not responding I need some class that can synchronize with me filechooser and load my image from my documents and show it in the panel.

package project;

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.*;

public class FileChooserDemo extends JPanel
                         implements ActionListener {
    static private final String newline = "\n";
    JButton openButton, saveButton;
    JTextArea log;
    JFileChooser fc;

public FileChooserDemo() {
    super(new BorderLayout());

    //Create the log first, because the action listeners
    //need to refer to it.
    log = new JTextArea(5,20);
    log.setMargin(new Insets(5,5,5,5));
    log.setEditable(false);
    JScrollPane logScrollPane = new JScrollPane(log);

    //Create a file chooser
    fc = new JFileChooser();

    openButton = new JButton("Open a File...");

    openButton.addActionListener(this);

    //Create the save button.  We use the image from the JLF
    //Graphics Repository (but we extracted it from the jar).
    saveButton = new JButton("Save a File...");

    saveButton.addActionListener(this);

    //For layout purposes, put the buttons in a separate panel
    JPanel buttonPanel = new JPanel(); //use FlowLayout
    buttonPanel.add(openButton);
    buttonPanel.add(saveButton);

    //Add the buttons and the log to this panel.
    add(buttonPanel, BorderLayout.PAGE_START);
    add(logScrollPane, BorderLayout.CENTER);
}

public void actionPerformed(ActionEvent e) {

    //Handle open button action.
    if (e.getSource() == openButton) {
        int returnVal = fc.showOpenDialog(FileChooserDemo.this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            //This is where a real application would open the file.
            log.append("Opening: " + file.getName() + "." + newline);

        } else {
            log.append("Open command cancelled by user." + newline);
        }
        log.setCaretPosition(log.getDocument().getLength());

    //Handle save button action.
    } else if (e.getSource() == saveButton) {
        int returnVal = fc.showSaveDialog(FileChooserDemo.this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            //This is where a real application would save the file.
            log.append("Saving: " + file.getName() + "." + newline);
        } else {
            log.append("Save command cancelled by user." + newline);
        }
        log.setCaretPosition(log.getDocument().getLength());
    }
}

/**
 * Create the GUI and show it.  For thread safety,
 * this method should be invoked from the
 * event dispatch thread.
 */
public static void createLoad() {
    //Create and set up the window.
    JFrame frame = new JFrame("FileChooserDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Add content to the window.
    frame.add(new FileChooserDemo());

    //Display the window.
    frame.pack();
    frame.setVisible(true);
}

}

this is the class file chooser i need a class that can load the picture i open

and this is the imageload code.

  import java.awt.*;
  import java.awt.event.*;
  import java.awt.image.*;
  import java.io.*;
  import javax.imageio.*;
  import javax.swing.*;

/**
 * This class demonstrates how to load an Image from an external file
*/
public class LoadImageApp extends Component {

   BufferedImage img;

public void paint(Graphics g) {
    g.drawImage(img, 0, 0, null);
}

public LoadImageApp() {
   try {
       img = ImageIO.read(new File("strawberry.jpg"));
   } catch (IOException e) {
   }

}

public Dimension getPreferredSize() {
    if (img == null) {
         return new Dimension(100,100);
    } else {
       return new Dimension(img.getWidth(null), img.getHeight(null));
   }
}

public static void main(String[] args) {

    JFrame f = new JFrame("Load Image Sample");

    f.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

    f.add(new LoadImageApp());
    f.pack();
    f.setVisible(true);
}
}

what i want is the image code read the file.aboslutepath and load the picture when i click it


问:
How to ensure referential integrity which relies on values
Suppose I have a table Level1:

```<code>Id int PK
Deleted bit
</code>```

and another table Level2:

```<code>Id int
Deleted bit
Level1id int
</code>```

I can add a FK to Level2 to match the Level1id with Level1.Id That works fine in ensuring the parent exists.

However, what If I want to ensure that records can only be INSERTed in Level2 when the matching record in Level1 has Deleted bit = 0 ?

Furthermore, how can I prevent the Deleted flag in Level1 from being set = 1 when any child records in Level2 have their Deleted bit = 0 ?
i.e. all child records must have Deleted = 1 before the Parent record can have Deleted = 1

I'm guessing that I might have to write a Trigger, but am hoping there's a more elegant solution...

答:
As mentioned by others, you could implement this logic in an application, or in stored procedures, but to do it in the database, the following functions and CHECK constraints should give you what you're looking for.

These will only run/check for the row you're interested in when you do an INSERT/UPDATE.

```<code>CREATE FUNCTION Level1Deleted (@Id int, @Deleted bit)
RETURNS bit
AS

BEGIN

    IF @Deleted = 1

        RETURN 0

    ELSE

        RETURN
        (
            SELECT L1.Deleted
            FROM
                Level2 L2
                JOIN Level1 L1 ON L2.Level1Id = L1.Id
            WHERE L2.Id = @Id
        )

    ;

END
GO

ALTER TABLE Level2
WITH CHECK
ADD CONSTRAINT CHK_Level1Deleted
CHECK (Level1Deleted(Id, Deleted) = 0)
GO

CREATE FUNCTION Level2NotFullyDeleted (@Id int, @Deleted bit)
RETURNS bit
AS

BEGIN

    IF @Deleted = 0

        RETURN 0

    ELSE

        RETURN
        (
            SELECT CAST(COUNT(*) AS bit)
            FROM
                Level1 L1
                JOIN Level2 L2 ON L1.Id = L2.Level1id
            WHERE
                L1.Id = @Id
                AND L2.Deleted = 0
        )

    ;

END
GO

ALTER TABLE Level1
WITH CHECK
ADD CONSTRAINT CHK_Level2FullyDeleted
CHECK (Level2NotFullyDeleted(Id, Deleted) = 0)
GO
</code>```

Body:
Suppose I have a table Level1:

Id int PK
Deleted bit

and another table Level2:

Id int
Deleted bit
Level1id int

I can add a FK to Level2 to match the Level1id with Level1.Id That works fine in ensuring the parent exists.

However, what If I want to ensure that records can only be INSERTed in Level2 when the matching record in Level1 has Deleted bit = 0 ?

Furthermore, how can I prevent the Deleted flag in Level1 from being set = 1 when any child records in Level2 have their Deleted bit = 0 ?
i.e. all child records must have Deleted = 1 before the Parent record can have Deleted = 1

I'm guessing that I might have to write a Trigger, but am hoping there's a more elegant solution...

Body:
As mentioned by others, you could implement this logic in an application, or in stored procedures, but to do it in the database, the following functions and CHECK constraints should give you what you're looking for.

These will only run/check for the row you're interested in when you do an INSERT/UPDATE.

CREATE FUNCTION Level1Deleted (@Id int, @Deleted bit)
RETURNS bit
AS

BEGIN

    IF @Deleted = 1

        RETURN 0

    ELSE

        RETURN
        (
            SELECT L1.Deleted
            FROM
                Level2 L2
                JOIN Level1 L1 ON L2.Level1Id = L1.Id
            WHERE L2.Id = @Id
        )

    ;

END
GO

ALTER TABLE Level2
WITH CHECK
ADD CONSTRAINT CHK_Level1Deleted
CHECK (Level1Deleted(Id, Deleted) = 0)
GO

CREATE FUNCTION Level2NotFullyDeleted (@Id int, @Deleted bit)
RETURNS bit
AS

BEGIN

    IF @Deleted = 0

        RETURN 0

    ELSE

        RETURN
        (
            SELECT CAST(COUNT(*) AS bit)
            FROM
                Level1 L1
                JOIN Level2 L2 ON L1.Id = L2.Level1id
            WHERE
                L1.Id = @Id
                AND L2.Deleted = 0
        )

    ;

END
GO

ALTER TABLE Level1
WITH CHECK
ADD CONSTRAINT CHK_Level2FullyDeleted
CHECK (Level2NotFullyDeleted(Id, Deleted) = 0)
GO


问:
Formatting Time/Date from different time zones in Powershell
I need to convert UTC time/date output to Eastern Standard Time in ISO 8601 (or similar) format using Powershell for use in a DOS Batch file.

I have very little experience with Powershell, but have previously modified existing Powershell commands for various DOS batch files.  Powershell can easily output time/date from numerous time zones, but it's not clear if it can readily display that output in a numerical format.

In a DOS batch file, Powershell can be called to display UTC time in this format --

```<code>echo | powershell (get-date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss')
</code>```

I need to call upon other time zones, but the output is 'FullDateTimePattern' which is spelled out --

```<code>echo | Powershell [System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), 'Line Islands Standard Time')
</code>```

I was hoping that the previous commands could (somehow) be merged together, or if one of the 'Get-Date -format' specifiers could be applied to the second code sample, or if an offset value could be applied to the UTC time/date output, or if there is some other easy code solution (or utility) that I could incorporate into a DOS batch file.

答:
To convert the current UTC [datetime] instant to Eastern Standard Time with the specified format:

```<code>powershell.exe -c "[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId([datetime]::UtcNow, 'Eastern Standard Time').ToString('yyyy-MM-ddTHH:mm:ss')"
</code>```

Note the following additional improvements:

No need for echo |: When PowerShell is invoked with a command with (possibly implied) -Command / -c, it automatically exits after completing that command. (As an aside, echo | doesn't send just a newline, it sends the string ECHO is on., followed by a newline; to send just a newline, you'd have to use echo. |

Option -c (-Command) is used explicitly, not just to make the intent clearer, but also to ease potential later transition to PowerShell Core, where -Command is no longer the default (-File is).

While your specific command would work without the enclosing double quotes ("..."), it's generally better to use them, so that commands that include cmd.exe metacharacter - e.g., & - don't break.

Body:
I need to convert UTC time/date output to Eastern Standard Time in ISO 8601 (or similar) format using Powershell for use in a DOS Batch file.

I have very little experience with Powershell, but have previously modified existing Powershell commands for various DOS batch files.  Powershell can easily output time/date from numerous time zones, but it's not clear if it can readily display that output in a numerical format.

In a DOS batch file, Powershell can be called to display UTC time in this format --

echo | powershell (get-date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss')

I need to call upon other time zones, but the output is 'FullDateTimePattern' which is spelled out --

echo | Powershell [System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), 'Line Islands Standard Time')

I was hoping that the previous commands could (somehow) be merged together, or if one of the 'Get-Date -format' specifiers could be applied to the second code sample, or if an offset value could be applied to the UTC time/date output, or if there is some other easy code solution (or utility) that I could incorporate into a DOS batch file.

Body:
To convert the current UTC [datetime] instant to Eastern Standard Time with the specified format:

powershell.exe -c "[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId([datetime]::UtcNow, 'Eastern Standard Time').ToString('yyyy-MM-ddTHH:mm:ss')"

Note the following additional improvements:

No need for echo |: When PowerShell is invoked with a command with (possibly implied) -Command / -c, it automatically exits after completing that command. (As an aside, echo | doesn't send just a newline, it sends the string ECHO is on., followed by a newline; to send just a newline, you'd have to use echo. |

Option -c (-Command) is used explicitly, not just to make the intent clearer, but also to ease potential later transition to PowerShell Core, where -Command is no longer the default (-File is).

While your specific command would work without the enclosing double quotes ("..."), it's generally better to use them, so that commands that include cmd.exe metacharacter - e.g., & - don't break.


问:
keras.layers.Input: AttributeError: 'OpDefLibrary' object has no attribute '_apply_op_helper'
I use spider (python 3.6) on Mac.

I try to use keras to create some input, and I typed in the following code:

```<code>from keras.layers import Input
input_target = Input(shape=(1,))
</code>```

Then I got the following error:

```<code>File "<ipython-input-33-804299fafc3c>", line 1, in <module>
  input_target = Input(shape=(1,))

File "~/anaconda3/lib/python3.6/site-packages/keras/engine/topology.py", line 1457, in Input
  input_tensor=tensor)

File "~/anaconda3/lib/python3.6/site-packages/keras/legacy/interfaces.py", line 91, in wrapper
  return func(*args, **kwargs)

File "~/anaconda3/lib/python3.6/site-packages/keras/engine/topology.py", line 1366, in __init__
  name=self.name)

File "~/anaconda3/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py", line 508, in placeholder
  x = tf.placeholder(dtype, shape=shape, name=name)

File "~/anaconda3/lib/python3.6/site-packages/tensorflow/python/ops/array_ops.py", line 1507, in placeholder
  # Matrix with two batch dimensions.

File "~/anaconda3/lib/python3.6/site-packages/tensorflow/python/ops/gen_array_ops.py", line 1997, in _placeholder
  the images. Must be: `[1, stride_rows, stride_cols, 1]`.

File "~/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py", line 327, in apply_op
  output_structure, is_stateful, op = self._apply_op_helper(

AttributeError: 'OpDefLibrary' object has no attribute '_apply_op_helper'
</code>```

I looked at the topology.py file where it gives an error:

```<code>if not batch_shape and tensor is None:
    assert shape is not None, ('Please provide to Input either a `shape`'
                               ' or a `batch_shape` argument. Note that '
                               '`shape` does not include the batch '
                               'dimension.')
if shape is not None and not batch_shape:
    batch_shape = (None,) + tuple(shape)
if not dtype:
    dtype = K.floatx()
input_layer = InputLayer(batch_input_shape=batch_shape,
                         name=name, dtype=dtype,
                         sparse=sparse,
                         input_tensor=tensor)
</code>```

I don't know what might cause the problem. Anything to do with the way how keras and its backend tensorflow define shape? I installed keras and tensorflow from Conda, and then installed tensorflow from Conda. It should be a pretty simple code using keras, and I don't understand why it cannot run.

答:
Same problem with environment: Python 3.6, tensorflow 1.13.1, Spyder 3.3.4.

I solved this problem by

installing tensorflow-eigen with anaconda (still not working while not restarted Spyder),

then restarted Spyder.

Body:
I use spider (python 3.6) on Mac.

I try to use keras to create some input, and I typed in the following code:

from keras.layers import Input
input_target = Input(shape=(1,))

Then I got the following error:

File "<ipython-input-33-804299fafc3c>", line 1, in <module>
  input_target = Input(shape=(1,))

File "~/anaconda3/lib/python3.6/site-packages/keras/engine/topology.py", line 1457, in Input
  input_tensor=tensor)

File "~/anaconda3/lib/python3.6/site-packages/keras/legacy/interfaces.py", line 91, in wrapper
  return func(*args, **kwargs)

File "~/anaconda3/lib/python3.6/site-packages/keras/engine/topology.py", line 1366, in __init__
  name=self.name)

File "~/anaconda3/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py", line 508, in placeholder
  x = tf.placeholder(dtype, shape=shape, name=name)

File "~/anaconda3/lib/python3.6/site-packages/tensorflow/python/ops/array_ops.py", line 1507, in placeholder
  # Matrix with two batch dimensions.

File "~/anaconda3/lib/python3.6/site-packages/tensorflow/python/ops/gen_array_ops.py", line 1997, in _placeholder
  the images. Must be: `[1, stride_rows, stride_cols, 1]`.

File "~/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py", line 327, in apply_op
  output_structure, is_stateful, op = self._apply_op_helper(

AttributeError: 'OpDefLibrary' object has no attribute '_apply_op_helper'

I looked at the topology.py file where it gives an error:

if not batch_shape and tensor is None:
    assert shape is not None, ('Please provide to Input either a `shape`'
                               ' or a `batch_shape` argument. Note that '
                               '`shape` does not include the batch '
                               'dimension.')
if shape is not None and not batch_shape:
    batch_shape = (None,) + tuple(shape)
if not dtype:
    dtype = K.floatx()
input_layer = InputLayer(batch_input_shape=batch_shape,
                         name=name, dtype=dtype,
                         sparse=sparse,
                         input_tensor=tensor)

I don't know what might cause the problem. Anything to do with the way how keras and its backend tensorflow define shape? I installed keras and tensorflow from Conda, and then installed tensorflow from Conda. It should be a pretty simple code using keras, and I don't understand why it cannot run.