问:
DateFormat works in native JUnit test, but not executed by Gradle
I have the following date, pattern and code to parse it:

```<code>String date = "Aug 9, 2019 10:07:59.999 AM";
String patt = "MMM dd, yyyy HH:mm:ss.SSS a";
SimpleDateFormat sdf = new SimpleDateFormat(patt);
Date d = sdf.parse(date);
</code>```

When running as JUnit test in Eclipse, it works. When executing as Gradle test on the same project the following error occurs:

```<code>java.text.ParseException: Unparseable date: "Aug 9, 2019 10:07:59.999 AM"
    at java.base/java.text.DateFormat.parse(DateFormat.java:396)
</code>```

I have already tried the following code:

```<code>SimpleDateFormat sdf = new SimpleDateFormat(patt, new Locale("de", "AT"));
sdf.setTimeZone(TimeZone.getTimeZone("Europe/Vienna"));
sdf.setLenient(false);
</code>```

But that did not bring any success. Any idea why JUnit works, but Gradle doesn't?

Version information:

```<code>------------------------------------------------------------
Gradle 6.4.1
------------------------------------------------------------

Build time:   2020-05-15 19:43:40 UTC
Revision:     1a04183c502614b5c80e33d603074e0b4a2777c5

Kotlin:       1.3.71
Groovy:       2.5.10
Ant:          Apache Ant(TM) version 1.10.7 compiled on September 1 2019
JVM:          14.0.1 (Azul Systems, Inc. 14.0.1+8)
OS:           Windows 10 10.0 amd64

------------------------------------------------------------

Eclipse IDE:  4.15.0.I20200305-0155
JDK in IDE:   zulu14.28.21-ca-jdk14.0.1-win_x64
</code>```

Gradle and Eclipse use the same JDK version running on Windows 10, 2004 64bit.

System language is "English (United Kingdom)", Timezone is "Europe/Vienna".

Full stack trace:

```<code>19:59:39.335 [Test worker] ERROR dateformat.DateFormat - Error.
java.text.ParseException: Unparseable date: "Aug 9, 2019 10:07:59.999 AM"
    at java.base/java.text.DateFormat.parse(DateFormat.java:396)
    at dateformat.DateFormat.format(DateFormat.java:28)
    at dateformat.DateFormatTest.test1(DateFormatTest.java:12)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:686)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
    at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:212)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:208)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:137)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:71)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1510)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1510)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:248)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$5(DefaultLauncher.java:211)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:226)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:199)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:132)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:99)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$000(JUnitPlatformTestClassProcessor.java:79)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:75)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
    at com.sun.proxy.$Proxy2.stop(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.stop(TestWorker.java:132)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:182)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:164)
    at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:413)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
    at java.base/java.lang.Thread.run(Thread.java:832)
</code>```

答:
I'm think there is problem with locale, try:

```<code>Date d = SimpleDateFormat(patt, Locale("en", "US"))
</code>```

For Locale("de", "AT"):

```<code>date = "Aug. 9, 2019 10:07:59.999 AM"
</code>```

dot :-).

Body:
I have the following date, pattern and code to parse it:

String date = "Aug 9, 2019 10:07:59.999 AM";
String patt = "MMM dd, yyyy HH:mm:ss.SSS a";
SimpleDateFormat sdf = new SimpleDateFormat(patt);
Date d = sdf.parse(date);

When running as JUnit test in Eclipse, it works. When executing as Gradle test on the same project the following error occurs:

java.text.ParseException: Unparseable date: "Aug 9, 2019 10:07:59.999 AM"
    at java.base/java.text.DateFormat.parse(DateFormat.java:396)

I have already tried the following code:

SimpleDateFormat sdf = new SimpleDateFormat(patt, new Locale("de", "AT"));
sdf.setTimeZone(TimeZone.getTimeZone("Europe/Vienna"));
sdf.setLenient(false);

But that did not bring any success. Any idea why JUnit works, but Gradle doesn't?

Version information:

------------------------------------------------------------
Gradle 6.4.1
------------------------------------------------------------

Build time:   2020-05-15 19:43:40 UTC
Revision:     1a04183c502614b5c80e33d603074e0b4a2777c5

Kotlin:       1.3.71
Groovy:       2.5.10
Ant:          Apache Ant(TM) version 1.10.7 compiled on September 1 2019
JVM:          14.0.1 (Azul Systems, Inc. 14.0.1+8)
OS:           Windows 10 10.0 amd64

------------------------------------------------------------

Eclipse IDE:  4.15.0.I20200305-0155
JDK in IDE:   zulu14.28.21-ca-jdk14.0.1-win_x64

Gradle and Eclipse use the same JDK version running on Windows 10, 2004 64bit.

System language is "English (United Kingdom)", Timezone is "Europe/Vienna".

Full stack trace:

19:59:39.335 [Test worker] ERROR dateformat.DateFormat - Error.
java.text.ParseException: Unparseable date: "Aug 9, 2019 10:07:59.999 AM"
    at java.base/java.text.DateFormat.parse(DateFormat.java:396)
    at dateformat.DateFormat.format(DateFormat.java:28)
    at dateformat.DateFormatTest.test1(DateFormatTest.java:12)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:686)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
    at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:212)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:208)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:137)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:71)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1510)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1510)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:248)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$5(DefaultLauncher.java:211)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:226)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:199)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:132)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:99)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$000(JUnitPlatformTestClassProcessor.java:79)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:75)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
    at com.sun.proxy.$Proxy2.stop(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.stop(TestWorker.java:132)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:182)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:164)
    at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:413)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
    at java.base/java.lang.Thread.run(Thread.java:832)

Body:
I'm think there is problem with locale, try:

Date d = SimpleDateFormat(patt, Locale("en", "US"))

For Locale("de", "AT"):

date = "Aug. 9, 2019 10:07:59.999 AM"

dot :-).


来源: stackexchange

问:
Download python from command prompt on windows
I am connected to a machine running Windows 8 from my linux machine using OpenSSH. I need to download python3 on the Windows machine but I only have access to the command prompt, not PowerShell. I also have sftp set up, but all the python downloads are installers which don't work through the command prompt. Does anybody know what I can do?</p>

答:
You can download using the curl program, if it's installed on your windows machine. Something like:

```<code>curl https://www.python.org/ftp/python/3.8.3/python-3.8.3-amd64.exe -o python_install.exe
</code>```

(or look for the Python version you want at https://www.python.org/downloads/windows/)

Then, you can run:

```<code>python_install.exe /quiet
</code>```

There are also zip file packages you can download from the URL above.

Note that a quiet install may not change your system's PATH, so you may need to locate the directory in which Python was installed, and call the program from there.

ContentLicense: CC BY-SA 4.0

Body:
You can download using the curl program, if it's installed on your windows machine. Something like:

curl https://www.python.org/ftp/python/3.8.3/python-3.8.3-amd64.exe -o python_install.exe

(or look for the Python version you want at https://www.python.org/downloads/windows/)

Then, you can run:

python_install.exe /quiet

There are also zip file packages you can download from the URL above.

Note that a quiet install may not change your system's PATH, so you may need to locate the directory in which Python was installed, and call the program from there.


问:
get node from firebase database to textviex with id
I would like to get "driverId" from "ride_info" and

if "driverId" is equal to a node in "Drivers" retrieve from this node "car", "license", "name", "phone",

and display it in a TEXTVIEW.

same for "customerId" get "name" and "phone"

i try this but it don't work it show me "null" on the textview

```<code>    DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
    Query lastQuery = ref.child("Users").orderByKey();
    lastQuery.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot ds : dataSnapshot.getChildren()){

                String value1_float = ds.child("Drivers").child("car").getValue(String.class);
                String value0_float = ds.child("Drivers").child("name").getValue(String.class);
                String carname = String.valueOf(value0_float);
                String namnam = String.valueOf(value1_float);
                carName = (TextView)findViewById(R.id.carname);
                carName.setText(carname);

                nameName = (TextView)findViewById(R.id.namName);
                nameName.setText(namnam);

            }
            /** mDate.setText(mRide.getDate());
             mDestination.setText(mRide.getDestination().getName());
             mPickup.setText(mRide.getPickup().getName());
             mCar.setText(mRide.getCar());**/

        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}
</code>```

screenshot of database

答:
It looks like you you missed one field. That's why it returns null.
It must be like

```<code>ds.child("Drivers").child("IDlK2HRy......").child("car").getValue(String.class);
</code>```

but this is also wrong because you used datasnapshot.getChildern() so Drivers child will be omited.

In case you don't know the in between child you can try like below for Drivers

```<code>Query lastQuery = ref.child("Users").child("Drivers").orderByKey();
    lastQuery.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot ds : dataSnapshot.getChildren()){

                carName = (TextView)findViewById(R.id.carname);
                nameName = (TextView)findViewById(R.id.namName);

                carName.setText(ds.child("name").getValue(String.class));
                nameName.setText(ds.child("car").getValue(String.class));
            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}
</code>```

Body:
I would like to get "driverId" from "ride_info" and

if "driverId" is equal to a node in "Drivers" retrieve from this node "car", "license", "name", "phone",

and display it in a TEXTVIEW.

same for "customerId" get "name" and "phone"

i try this but it don't work it show me "null" on the textview

    DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
    Query lastQuery = ref.child("Users").orderByKey();
    lastQuery.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot ds : dataSnapshot.getChildren()){

                String value1_float = ds.child("Drivers").child("car").getValue(String.class);
                String value0_float = ds.child("Drivers").child("name").getValue(String.class);
                String carname = String.valueOf(value0_float);
                String namnam = String.valueOf(value1_float);
                carName = (TextView)findViewById(R.id.carname);
                carName.setText(carname);

                nameName = (TextView)findViewById(R.id.namName);
                nameName.setText(namnam);

            }
            /** mDate.setText(mRide.getDate());
             mDestination.setText(mRide.getDestination().getName());
             mPickup.setText(mRide.getPickup().getName());
             mCar.setText(mRide.getCar());**/

        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}

screenshot of database

Body:
It looks like you you missed one field. That's why it returns null.
It must be like

ds.child("Drivers").child("IDlK2HRy......").child("car").getValue(String.class);

but this is also wrong because you used datasnapshot.getChildern() so Drivers child will be omited.

In case you don't know the in between child you can try like below for Drivers

Query lastQuery = ref.child("Users").child("Drivers").orderByKey();
    lastQuery.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot ds : dataSnapshot.getChildren()){

                carName = (TextView)findViewById(R.id.carname);
                nameName = (TextView)findViewById(R.id.namName);

                carName.setText(ds.child("name").getValue(String.class));
                nameName.setText(ds.child("car").getValue(String.class));
            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}


问:
Angular testing : RouterTestingModule
I'm new in Angular tests and I have an error on every component that is using a navigation Service :

```<code>Failed: StaticInjectorError(DynamicTestModule)[NavigationService -> Router]:
  StaticInjectorError(Platform: core)[NavigationService -> Router]:
    NullInjectorError: No provider for Router!
</code>```

The navigation Service uses the angular router. When I add the RoutertestingModule on the imports of a component's spec file, I don't have the error anymore. I was wondering if the solution was to add the RouterTestingModule on each component's spec file or if there was something I missed ?

navigation.service.spec.ts

```<code>import { TestBed, inject } from '@angular/core/testing';
import { NavigationService } from './navigation.service';
import { RouterTestingModule } from '@angular/router/testing';
import { HubConnectionService } from '../hub-connection/hub-connection.service';
import { LoaderService } from '../loader.service';

describe('NavigationService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports:[RouterTestingModule],
      providers: [NavigationService,HubConnectionService,LoaderService],
    });
  });

  it('should be created', inject([NavigationService], (service: NavigationService) => {
    expect(service).toBeTruthy();
  }));
});
</code>```

答:
You need to call .withRoutes(), for example like

imports: [RouterTestingModule.withRoutes([])],
```

Title: Angular testing : RouterTestingModule

Body:
I'm new in Angular tests and I have an error on every component that is using a navigation Service :

Failed: StaticInjectorError(DynamicTestModule)[NavigationService -> Router]:
  StaticInjectorError(Platform: core)[NavigationService -> Router]:
    NullInjectorError: No provider for Router!

The navigation Service uses the angular router. When I add the RoutertestingModule on the imports of a component's spec file, I don't have the error anymore. I was wondering if the solution was to add the RouterTestingModule on each component's spec file or if there was something I missed ?

navigation.service.spec.ts

import { TestBed, inject } from '@angular/core/testing';
import { NavigationService } from './navigation.service';
import { RouterTestingModule } from '@angular/router/testing';
import { HubConnectionService } from '../hub-connection/hub-connection.service';
import { LoaderService } from '../loader.service';

describe('NavigationService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports:[RouterTestingModule],
      providers: [NavigationService,HubConnectionService,LoaderService],
    });
  });

  it('should be created', inject([NavigationService], (service: NavigationService) => {
    expect(service).toBeTruthy();
  }));
});


问:
Creating C "Template" function
I'm currently working on a project that require me to use some linked lists.

I'm used to them but I really don't like the fact that I need to duplicate my code.
Here is what i mean :

```<code>struct A {
    struct A *prev;
    struct A *next;

    int i;
}

struct B {
    struct B *prev;
    struct B *next;

    char *str;
}
</code>```

If I want to  create a function that add an element to any of my liked list i would need to do something like :

```<code>void add_A_element(struct A *list, struct A *new_element) { [...] }

void add_B_element(struct B *list, struct B *new_element) { [...] }
</code>```

Here is my question, is there a way for me to have only one function for all my structures ?

I'm wondering if i could do so with an other structure like :

```<code>struct template {
    struct template *prev;
    struct template *next;
}
</code>```

Then the function to add my element would look like :

```<code>void add_element(void *list, void *new_element)
{
    struct template tmp_list = (struct template *)list;
    struct template tmp_new_element = (struct template *)new_element;

    for (struct template tmp = tmp_list; tmp != NULL; tmp = tmp->next) {
        if (tmp->next == NULL) {
            tmp->next = tmp_new_element;
            tmp_new_element->prev = tmp;
            break;
        }
    }
    return;
}
</code>```

Because we modify the same memory space, i guess this could work but i think some unexpected issue could happen.

I'm wondering if something that looks like a bit more like C++ template could exist in C.

Any help would be appreciate. Thanks

Edit : I managed to do it. I'm still planning on adding few things such as fifo/lifo queue but you can already get it on my Github

答:
I've got full solution with templates (macro) in C if you'd like to have a look, links in the end. Meanwhile, let me explain how to approach that problem:

You should use container_of strategy to abstractly traverse a linked list.

```<code>struct linked_list_head
{
    struct linked_list_head * next;
    struct linked_list_head * prev;
};

struct my_type {
 ...
 struct linked_list_head head;
}
</code>```

Then the code to get the next would be

```<code>struct linked_list_head next(struct linked_list_head * current) {
  return current->next;
}

struct my_type next = container_of(next(&current.head), struct my_type, head));

</code>```

What is the container_of macro?

Understanding container_of macro in the Linux kernel

If you want to see a full solution using templates implemented, I got a free to use (at your own risk) solution:

The library: https://github.com/flplv/fl-lib/blob/master/headers/linked_list.h

The Usage: https://github.com/flplv/fl-lib/blob/master/tests/test_linked_list.cpp

Title: Creating C "Template" function

Body:
I'm currently working on a project that require me to use some linked lists.

I'm used to them but I really don't like the fact that I need to duplicate my code.
Here is what i mean :

struct A {
    struct A *prev;
    struct A *next;

    int i;
}

struct B {
    struct B *prev;
    struct B *next;

    char *str;
}

If I want to  create a function that add an element to any of my liked list i would need to do something like :

void add_A_element(struct A *list, struct A *new_element) { [...] }

void add_B_element(struct B *list, struct B *new_element) { [...] }

Here is my question, is there a way for me to have only one function for all my structures ?

I'm wondering if i could do so with an other structure like :

struct template {
    struct template *prev;
    struct template *next;
}

Then the function to add my element would look like :

void add_element(void *list, void *new_element)
{
    struct template tmp_list = (struct template *)list;
    struct template tmp_new_element = (struct template *)new_element;

    for (struct template tmp = tmp_list; tmp != NULL; tmp = tmp->next) {
        if (tmp->next == NULL) {
            tmp->next = tmp_new_element;
            tmp_new_element->prev = tmp;
            break;
        }
    }
    return;
}

Because we modify the same memory space, i guess this could work but i think some unexpected issue could happen.

I'm wondering if something that looks like a bit more like C++ template could exist in C.

Any help would be appreciate. Thanks

Edit : I managed to do it. I'm still planning on adding few things such as fifo/lifo queue but you can already get it on my Github

Body:
I've got full solution with templates (macro) in C if you'd like to have a look, links in the end. Meanwhile, let me explain how to approach that problem:

You should use container_of strategy to abstractly traverse a linked list.

struct linked_list_head
{
    struct linked_list_head * next;
    struct linked_list_head * prev;
};

struct my_type {
 ...
 struct linked_list_head head;
}

Then the code to get the next would be

struct linked_list_head next(struct linked_list_head * current) {
  return current->next;
}

struct my_type next = container_of(next(&current.head), struct my_type, head));

What is the container_of macro?

Understanding container_of macro in the Linux kernel

If you want to see a full solution using templates implemented, I got a free to use (at your own risk) solution:

The library: https://github.com/flplv/fl-lib/blob/master/headers/linked_list.h

The Usage: https://github.com/flplv/fl-lib/blob/master/tests/test_linked_list.cpp


问:
How to convert characters such as \xe2\x80\x99 to normal apostrophe in html string
I have an html string like this "li Convenient \xe2\x80\x93 Pre-measured Bleach tablets /li"

How can I convert it properly while still preserving html tags in python? I want to do it for any of these characters not just those that represent an apostrophe.

答:
I'm not quite sure what you are looking for, but to decode a byte string you could do this:</p>

```<code>bstring = b"li Convenient \xe2\x80\x93 Pre-measured Bleach tablets /li"
string = bstring.decode('utf-8')
print(string)
>> 'li Convenient – Pre-measured Bleach tablets /li'
</code>```

Body:
I'm not quite sure what you are looking for, but to decode a byte string you could do this:

bstring = b"li Convenient \xe2\x80\x93 Pre-measured Bleach tablets /li"
string = bstring.decode('utf-8')
print(string)
>> 'li Convenient – Pre-measured Bleach tablets /li'


问:
Notice: Undefined index - Solving with isset?
```<code>Notice: Undefined index: extension  in /var/www/.. on line 187

    //185 - $f_name = $this->filename;
    //186 - $path_parts = pathinfo($f_name);
    //187 - $file_ext = $path_parts['extension'];
</code>```

After some googleing I've seen alot of Isset being used. But I'm in doubt, about how to use it, in this case? Is it even going to solve the problem?

答:
Since php 7.0, You can use null coalescing operator

```<code>$file_ext = $path_parts['extension'] ?? null;
</code>```

https://www.php.net/manual/en/migration70.new-features.php

ContentLicense: CC BY-SA 3.0

Body:
Notice: Undefined index: extension  in /var/www/.. on line 187

    //185 - $f_name = $this->filename;
    //186 - $path_parts = pathinfo($f_name);
    //187 - $file_ext = $path_parts['extension'];

After some googleing I've seen alot of Isset being used. But I'm in doubt, about how to use it, in this case? Is it even going to solve the problem?

Body:
Since php 7.0, You can use null coalescing operator

$file_ext = $path_parts['extension'] ?? null;

https://www.php.net/manual/en/migration70.new-features.php


问:
Create a string from object array
I have two arrays as below:

var product1 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "One Plus"
    }
  ];
var product2 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "Apple"
    }
  ];
```

<p>I want to loop through the array and print the following:</p>

<ol>
<li>If product 1, output <code>you have 2 One Plus</code></li>
<li>If product 2, output <code>you have 1 One Plus and 1 Apple</code></li>
</ol>

<p>Below is the code that I tried.</p>

<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 product1 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "One Plus"
    }
  ];
var product2 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "Apple"
    }
  ];

counter1 = {}
product1.forEach(function(obj) {
    var key = JSON.stringify(obj)
    counter1[key] = (counter1[key] || 0) + 1
});
console.log(counter1);
counter2 = {}
product2.forEach(function(obj) {
    var key = JSON.stringify(obj)
    counter2[key] = (counter2[key] || 0) + 1
});
console.log(counter2);</code>```

I’m able to get the JSON output, but how can I get it in the sentence format?

答:
How about this?

var product1 = [{
    "Brand": "One Plus"
  },
  {
    "Brand": "One Plus"
  }
];
var product2 = [{
    "Brand": "One Plus"
  },
  {
    "Brand": "Apple"
  }
];

function countProducts(arr) {
  let counter = arr.reduce((acc, val) =>
    (acc[val.Brand] = (acc[val.Brand] || 0) + 1, acc), {});
  let strings = Object.keys(counter).map(k => `${counter[k]} ${k}`);
  return `You have ${strings.join(' and ')}`;
}

console.log(countProducts(product1));

console.log(countProducts(product2));```

Title: Create a string from object array

Body:
I have two arrays as below:

var product1 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "One Plus"
    }
  ];
var product2 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "Apple"
    }
  ];

I want to loop through the array and print the following:

If product 1, output you have 2 One Plus

If product 2, output you have 1 One Plus and 1 Apple

Below is the code that I tried.

var product1 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "One Plus"
    }
  ];
var product2 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "Apple"
    }
  ];

counter1 = {}
product1.forEach(function(obj) {
    var key = JSON.stringify(obj)
    counter1[key] = (counter1[key] || 0) + 1
});
console.log(counter1);
counter2 = {}
product2.forEach(function(obj) {
    var key = JSON.stringify(obj)
    counter2[key] = (counter2[key] || 0) + 1
});
console.log(counter2);

I’m able to get the JSON output, but how can I get it in the sentence format?


问:
React Navigation; use image in header?
I'm using react navigation in a react native project and I want to customize the header with an image.

For a color I can use simple styling, but since react native doesn't support background images I need a different solution.

答:
Update for React Navigation v5! (making this post for future references)

For react navigation 5, I found this solution.

In StackNavigator.js class you can set a different image for each page (Stack.Screen):

```<code><Stack.Screen
    name='Home'
    component={HomeScreen}
    options={{
      title: <Image style={{ width: 250, height: 50 }}
      source = require('../images/yourimage.png')}/>
    }}
 />
</code>```

Then, you must adjust width, height, and position of the image, but it works! I think it's the simpliest way. Here's the output (yes, it's my image, before adjustments).

Don't forget to import Image!

```<code>import { Image } from 'react-native'
</code>```

Title: React Navigation; use image in header?

Body:
Update for React Navigation v5! (making this post for future references)

For react navigation 5, I found this solution.

In StackNavigator.js class you can set a different image for each page (Stack.Screen):

<Stack.Screen
    name='Home'
    component={HomeScreen}
    options={{
      title: <Image style={{ width: 250, height: 50 }}
      source = require('../images/yourimage.png')}/>
    }}
 />

Then, you must adjust width, height, and position of the image, but it works! I think it's the simpliest way. Here's the output (yes, it's my image, before adjustments).

Don't forget to import Image!

import { Image } from 'react-native'


问:
Use recode function with %like% operator
Is there anyway to use the recode function from dplyr with the %like% operator from DescTools, as well as with an 'other' statement? i.e. what is shown below:

```<code>library(tidyverse)
library(DescTools)

dat <- data.frame(NAME = c("Bill", "Billy", "Wibill", "Chris"))

dat %>%
  mutate(NAME_2 = recode(NAME, "%Bill%" = "Willhelm", "Other"))
</code>```

Desired output is:

```<code>NAME      NAME_2
Bill      Willhelm
Billy     Willhelm
Wibill    Willhelm
Chris     Other
</code>```

答:
That's not how recode() works; recode() matches specific values with specific replacements. However, your desired output is easy to achieve with mutate() and if_else():

```<code>dat %>%
    mutate(NAME_2 = if_else(NAME %like% "%[Bb]ill%", "Willhelm", "Other"))

    NAME   NAME_2
1   Bill Willhelm
2  Billy Willhelm
3 Wibill Willhelm
4  Chris    Other
</code>```

(Though you'll notice I've had to account for upper- or lower-case "Bill", which would be the case with any use of %like% if your desired output is not case sensitive in that way.)

Body:
Is there anyway to use the recode function from dplyr with the %like% operator from DescTools, as well as with an 'other' statement? i.e. what is shown below:

library(tidyverse)
library(DescTools)

dat <- data.frame(NAME = c("Bill", "Billy", "Wibill", "Chris"))

dat %>%
  mutate(NAME_2 = recode(NAME, "%Bill%" = "Willhelm", "Other"))

Desired output is:

NAME      NAME_2
Bill      Willhelm
Billy     Willhelm
Wibill    Willhelm
Chris     Other

Body:
That's not how recode() works; recode() matches specific values with specific replacements. However, your desired output is easy to achieve with mutate() and if_else():

dat %>%
    mutate(NAME_2 = if_else(NAME %like% "%[Bb]ill%", "Willhelm", "Other"))

    NAME   NAME_2
1   Bill Willhelm
2  Billy Willhelm
3 Wibill Willhelm
4  Chris    Other

(Though you'll notice I've had to account for upper- or lower-case "Bill", which would be the case with any use of %like% if your desired output is not case sensitive in that way.)


问:
How to know that the data on the clipboard is ready to be used?
My code copies a table, processes the copied data, copies another table, processes the copied data and so on ...

The problem is that sometimes some tables have a lot of data that take a long time to be copied, causing an error in the try/catch block.

Is there a way to start processing the copied data only after the data is ready on the clipboard?

```<code>   Private Sub Copy
      Clipboard.Clear()
            Try
                Win32.SetCursorPos(200,200)
                Win32.mouse_event(Win32.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
                Win32.mouse_event(Win32.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
                SendKeys.SendWait("^C")
            Catch ex As Exception
                Msgbox (ex.message)
            End Try

            'PROCESS THE COPIED DATA
        Try
            Dim clip() As String
            Dim col() As String
            clip = Clipboard.GetText().Split(Environment.NewLine)
            col = clip(i).Split(vbTab)
            'I test the data to see if it interests me
        Catch ex As Exception

        End Try

     Clipboard.Clear()
            Try
                Win32.SetCursorPos(600,200)
                Win32.mouse_event(Win32.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
                Win32.mouse_event(Win32.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
                SendKeys.SendWait("^C")
            Catch ex As Exception
                Msgbox (ex.message)
            End Try

            'PROCESS THE COPIED DATA

     Clipboard.Clear()
            Try
                Win32.SetCursorPos(400,200)
                Win32.mouse_event(Win32.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
                Win32.mouse_event(Win32.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
                SendKeys.SendWait("^C")
            Catch ex As Exception
                Msgbox (ex.message)
            End Try

            'PROCESS THE COPIED DATA

    End Sub
</code>```

答:
Here is a loop as per @jmcilhinney 's comment. No GoTo. Set the number of tries in the If ErrorCount > 3 Then. You were repeating your code. Usually not a good idea for maintenance. The only thing that changed was the left and top, so I passed those as parameters. The display of the message box will provide the pause. Your ProcessCopiedData should probably be a separate sub called from the Copy sub.

```<code>Private Sub Copy(left As Integer, top As Integer)
    Dim ErrorCount As Integer
    Do
        Clipboard.Clear()
        Try
            Win32.SetCursorPos(left, top)
            Win32.mouse_event(Win32.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
            Win32.mouse_event(Win32.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
            SendKeys.SendWait("^C")
            ErrorCount = 0
        Catch ex As Exception
            ErrorCount += 1
            MsgBox(ex.Message)
        End Try
        If ErrorCount > 3 Then
            MessageBox.Show("Exceeded # of Trys.")
            Exit Sub
        End If
    Loop Until ErrorCount < 1
    'Process Copied Data
End Sub
</code>```

Usage...

```<code>Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Copy(200, 200)
    Copy(600, 200)
    Copy(400, 200)
End Sub
</code>```

Body:
My code copies a table, processes the copied data, copies another table, processes the copied data and so on ...

The problem is that sometimes some tables have a lot of data that take a long time to be copied, causing an error in the try/catch block.

Is there a way to start processing the copied data only after the data is ready on the clipboard?

   Private Sub Copy
      Clipboard.Clear()
            Try
                Win32.SetCursorPos(200,200)
                Win32.mouse_event(Win32.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
                Win32.mouse_event(Win32.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
                SendKeys.SendWait("^C")
            Catch ex As Exception
                Msgbox (ex.message)
            End Try

            'PROCESS THE COPIED DATA
        Try
            Dim clip() As String
            Dim col() As String
            clip = Clipboard.GetText().Split(Environment.NewLine)
            col = clip(i).Split(vbTab)
            'I test the data to see if it interests me
        Catch ex As Exception

        End Try

     Clipboard.Clear()
            Try
                Win32.SetCursorPos(600,200)
                Win32.mouse_event(Win32.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
                Win32.mouse_event(Win32.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
                SendKeys.SendWait("^C")
            Catch ex As Exception
                Msgbox (ex.message)
            End Try

            'PROCESS THE COPIED DATA

     Clipboard.Clear()
            Try
                Win32.SetCursorPos(400,200)
                Win32.mouse_event(Win32.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
                Win32.mouse_event(Win32.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
                SendKeys.SendWait("^C")
            Catch ex As Exception
                Msgbox (ex.message)
            End Try

            'PROCESS THE COPIED DATA

    End Sub

Body:
Here is a loop as per @jmcilhinney 's comment. No GoTo. Set the number of tries in the If ErrorCount > 3 Then. You were repeating your code. Usually not a good idea for maintenance. The only thing that changed was the left and top, so I passed those as parameters. The display of the message box will provide the pause. Your ProcessCopiedData should probably be a separate sub called from the Copy sub.

Private Sub Copy(left As Integer, top As Integer)
    Dim ErrorCount As Integer
    Do
        Clipboard.Clear()
        Try
            Win32.SetCursorPos(left, top)
            Win32.mouse_event(Win32.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
            Win32.mouse_event(Win32.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
            SendKeys.SendWait("^C")
            ErrorCount = 0
        Catch ex As Exception
            ErrorCount += 1
            MsgBox(ex.Message)
        End Try
        If ErrorCount > 3 Then
            MessageBox.Show("Exceeded # of Trys.")
            Exit Sub
        End If
    Loop Until ErrorCount < 1
    'Process Copied Data
End Sub

Usage...

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Copy(200, 200)
    Copy(600, 200)
    Copy(400, 200)
End Sub


问:
Display data from database with Select Option Codeigniter
first I want to apologize because I just learned Codeigniter, I have problems to display data from the database by using the Select Option, there is no error but the data does not appear, for your information, i have joined 3 tables.

Here's my Controller

```<code>class Harga extends CI_Controller{

function __construct(){
parent::__construct();
  $this->load->model('m_harga');
  $this->load->helper('url');
  $this->load->database();
}

function index(){
  $this->load->helper('form');
  $data['tabel_harga'] = $this->m_harga->tampil_data();
  $this->load->view('v_harga',$data);
}
</code>```

Here's my Model

```<code>class M_harga extends CI_Model{
 function tampil_data(){
    $this->db->order_by('id_harga','ASC');
    return $this->db->from('tabel_harga')
    ->join('tabel_vendor','tabel_vendor.id_vendor=tabel_harga.id_vendor')
    ->join('tabel_hari','tabel_hari.id_hari=tabel_harga.id_hari')
    ->get()
    ->result();
}
</code>```

and Here's my Views

```<code><select class="form-control">
    <option value="">All</option>
      <?php
       foreach($tabel_harga as $u)
       {
        echo '<option value="'.$u['id_vendor'].'">'.$u['nama_vendor'].'</option>';
       }
      ?>
</select>
</code>```

I will be very grateful if you help me, thank you guys.

答:
try this

view

```<code><select class="form-control">
    <option value="">All</option>
      <?php
       foreach($tabel_harga as $u)
       {
        echo '<option value="'.$u->id_vendor.'">'.$u->nama_vendor.'</option>';
       }
      ?>
</select>
</code>```

Models

```<code>
class M_harga extends CI_Model{
 function tampil_data(){

     $this->db-join('tabel_vendor','tabel_vendor.id_vendor=tabel_harga.id_vendor')
     $this->db-join('tabel_hari','tabel_hari.id_hari=tabel_harga.id_hari')
     $this->db->order_by('id_harga','ASC');
     $sql = $this->db->get('tabel_harga');

     return $sql->result(); // returns an array of objects
}

</code>```

controller

```<code>class Harga extends CI_Controller{

function __construct(){
parent::__construct();
  $this->load->model('M_harga');
  $this->load->helper(array('url','form'));
}

function index(){

  $data['tabel_harga'] = $this->M_harga->tampil_data();
  $this->load->view('v_harga',$data);
}
</code>```

Body:
first I want to apologize because I just learned Codeigniter, I have problems to display data from the database by using the Select Option, there is no error but the data does not appear, for your information, i have joined 3 tables.

Here's my Controller

class Harga extends CI_Controller{

function __construct(){
parent::__construct();
  $this->load->model('m_harga');
  $this->load->helper('url');
  $this->load->database();
}

function index(){
  $this->load->helper('form');
  $data['tabel_harga'] = $this->m_harga->tampil_data();
  $this->load->view('v_harga',$data);
}

Here's my Model

class M_harga extends CI_Model{
 function tampil_data(){
    $this->db->order_by('id_harga','ASC');
    return $this->db->from('tabel_harga')
    ->join('tabel_vendor','tabel_vendor.id_vendor=tabel_harga.id_vendor')
    ->join('tabel_hari','tabel_hari.id_hari=tabel_harga.id_hari')
    ->get()
    ->result();
}

and Here's my Views

<select class="form-control">
    <option value="">All</option>
      <?php
       foreach($tabel_harga as $u)
       {
        echo '<option value="'.$u['id_vendor'].'">'.$u['nama_vendor'].'</option>';
       }
      ?>
</select>

I will be very grateful if you help me, thank you guys.

Body:
try this

view

<select class="form-control">
    <option value="">All</option>
      <?php
       foreach($tabel_harga as $u)
       {
        echo '<option value="'.$u->id_vendor.'">'.$u->nama_vendor.'</option>';
       }
      ?>
</select>

Models

class M_harga extends CI_Model{
 function tampil_data(){

     $this->db-join('tabel_vendor','tabel_vendor.id_vendor=tabel_harga.id_vendor')
     $this->db-join('tabel_hari','tabel_hari.id_hari=tabel_harga.id_hari')
     $this->db->order_by('id_harga','ASC');
     $sql = $this->db->get('tabel_harga');

     return $sql->result(); // returns an array of objects
}

controller

class Harga extends CI_Controller{

function __construct(){
parent::__construct();
  $this->load->model('M_harga');
  $this->load->helper(array('url','form'));
}

function index(){

  $data['tabel_harga'] = $this->M_harga->tampil_data();
  $this->load->view('v_harga',$data);
}


问:
Copy contents of cells and paste into another worksheet under correct date
I am making an entry sheet for items completed by a person for a date.

INPUT: the user enters a date and it populates the week (on a separate line). Then the user enters numbers under the dates for the week. The Names will always be the same, but the dates can change.

```<code>      |Jan 1|Jan 2|Jan 3|Jan 4|Jan 5|Jan 6|Jan 7|
Homer    1
Marge          2
Lisa                                        5
</code>```

DATA: This sheet will hold all the dates and names and the items completed.

```<code>         Homer|Marge|Lisa
 Jan 1 |
 Jan 2 |
 etc   |
</code>```

My problem is that I have a button that should copy the numbers in INPUT and place them in DATA that corresponds the the same date. I am fine if the data overwrites when they press the button more than once, I just need the data in the right cell.

So far I have snippets of code found on other websites and how to Move entire row base of call value but I had a hard time to understand it.

```<code>Worksheets("INPUT").Range("B2").Copy
Worksheet("DATA").Range("B2").End(xlDown).Offset(1,0).Insert
Selection.Pastespecial Paste:=xlPasteAll, Operation:=xlNone, Skipblanks:=_False, Transpose:=True
Application.CutCopyMode = False
</code>```

答:
A Data Transfer (Transpose)

For

```<code>Const srcFirstCell As String = "C3"
Const tgtFirstCell As String = "E2"
</code>```

The images are demonstrating the flexibility of the code:

Yellow: These are the first cells. You can change them as you see fit.
Orange: This is the date that is searched for in the Target Sheet (DATA). Only Jan 1 was manually written to the Target Sheet to show how vital it is that the dates are entered consecutively (one after the other). You will of course have all the dates and the names already written in the Target Sheet. Now you can press the button as many times as you like and the data will only be written to the appropriate cells which wouldn't have been possible with End(xlDown) or End(xlUp).

```<code>Option Explicit

' Assuming that the headers (Names horizontally, Dates vertically) are already
' written in the Target Sheet, the following code searches for the first
' occurrence of the first date in the Target Sheet and transposes the data
' appropriately. It is further assumed that the dates are consecutive.
Sub transposeData()

    Const srcName As String = "INPUT"
    Const tgtName As String = "DATA"
    Const srcFirstCell As String = "A1"
    Const tgtFirstCell As String = "A1"
    Const srcColumns As Long = 7

    ' Write values from Source Range to Source Array.
    Dim src As Worksheet: Set src = ThisWorkbook.Worksheets(srcName)
    With src
        Dim Criteria As Variant
        Criteria = .Range(srcFirstCell).Offset(, 1).Value
        Dim rng As Range
        Set rng = .Columns(.Range(srcFirstCell).Column) _
          .Find("*", , xlValues, , , xlPrevious)
        If rng Is Nothing Then Exit Sub
        If rng.Row < .Range(srcFirstCell).Row Then Exit Sub
        Debug.Print rng.Address
        Dim Source As Variant
        Debug.Print .Range(.Range(srcFirstCell).Offset(1, 1), rng.Offset(, 1)) _
          .Resize(, srcColumns).Address
        Source = .Range(.Range(srcFirstCell).Offset(1, 1), rng.Offset(, 1)) _
          .Resize(, srcColumns)
    End With

    ' Write transposed values from Source Array to Target Range.
    Dim tgt As Worksheet: Set tgt = ThisWorkbook.Worksheets(tgtName)
    Set rng = tgt.Columns(tgt.Range(tgtFirstCell).Column) _
      .Find(Criteria, , xlValues, xlWhole)
    If rng Is Nothing Then Exit Sub
    rng.Offset(, 1).Resize(UBound(Source, 2), UBound(Source)) _
      = Application.Transpose(Source)

    ' Inform user.
    MsgBox "Data transfer finished successfully.", vbInformation, "Success"

End Sub

' While assuming that the Target Sheet was empty I wrote the following code
' which transposes the complete data including headers.
Sub transposeDataComplete()

    Const srcName As String = "INPUT"
    Const tgtName As String = "DATA"
    Const srcFirstCell As String = "A1"
    Const tgtFirstCell As String = "A1"
    Const srcColumns As Long = 8 ' = 7 days + 1 for 'vertical' headers

    ' Write values from Source Range to Source Array.
    Dim src As Worksheet: Set src = ThisWorkbook.Worksheets(srcName)
    With src
        Dim rng As Range
        Set rng = .Columns(.Range(srcFirstCell).Column) _
          .Find("*", , xlValues, , , xlPrevious)
        If rng Is Nothing Then Exit Sub
        If rng.Row < .Range(srcFirstCell).Row Then Exit Sub
        Dim Source As Variant
        Source = .Range(.Range(srcFirstCell), rng).Resize(, srcColumns)
    End With
    Set rng = Nothing

    ' Write transposed values of Source Array to Target Range.
    Dim tgt As Worksheet: Set tgt = ThisWorkbook.Worksheets(tgtName)
    tgt.Range(tgtFirstCell).Resize(UBound(Source, 2), UBound(Source)) _
      = Application.Transpose(Source)

    ' Inform user.
    MsgBox "Data transfer finished successfully.", vbInformation, "Success"

End Sub
</code>```

Body:
I am making an entry sheet for items completed by a person for a date.

INPUT: the user enters a date and it populates the week (on a separate line). Then the user enters numbers under the dates for the week. The Names will always be the same, but the dates can change.

      |Jan 1|Jan 2|Jan 3|Jan 4|Jan 5|Jan 6|Jan 7|
Homer    1
Marge          2
Lisa                                        5

DATA: This sheet will hold all the dates and names and the items completed.

         Homer|Marge|Lisa
 Jan 1 |
 Jan 2 |
 etc   |

My problem is that I have a button that should copy the numbers in INPUT and place them in DATA that corresponds the the same date. I am fine if the data overwrites when they press the button more than once, I just need the data in the right cell.

So far I have snippets of code found on other websites and how to Move entire row base of call value but I had a hard time to understand it.

Worksheets("INPUT").Range("B2").Copy
Worksheet("DATA").Range("B2").End(xlDown).Offset(1,0).Insert
Selection.Pastespecial Paste:=xlPasteAll, Operation:=xlNone, Skipblanks:=_False, Transpose:=True
Application.CutCopyMode = False

Body:
A Data Transfer (Transpose)

For

Const srcFirstCell As String = "C3"
Const tgtFirstCell As String = "E2"

The images are demonstrating the flexibility of the code:

Yellow: These are the first cells. You can change them as you see fit.
Orange: This is the date that is searched for in the Target Sheet (DATA). Only Jan 1 was manually written to the Target Sheet to show how vital it is that the dates are entered consecutively (one after the other). You will of course have all the dates and the names already written in the Target Sheet. Now you can press the button as many times as you like and the data will only be written to the appropriate cells which wouldn't have been possible with End(xlDown) or End(xlUp).

Option Explicit

' Assuming that the headers (Names horizontally, Dates vertically) are already
' written in the Target Sheet, the following code searches for the first
' occurrence of the first date in the Target Sheet and transposes the data
' appropriately. It is further assumed that the dates are consecutive.
Sub transposeData()

    Const srcName As String = "INPUT"
    Const tgtName As String = "DATA"
    Const srcFirstCell As String = "A1"
    Const tgtFirstCell As String = "A1"
    Const srcColumns As Long = 7

    ' Write values from Source Range to Source Array.
    Dim src As Worksheet: Set src = ThisWorkbook.Worksheets(srcName)
    With src
        Dim Criteria As Variant
        Criteria = .Range(srcFirstCell).Offset(, 1).Value
        Dim rng As Range
        Set rng = .Columns(.Range(srcFirstCell).Column) _
          .Find("*", , xlValues, , , xlPrevious)
        If rng Is Nothing Then Exit Sub
        If rng.Row < .Range(srcFirstCell).Row Then Exit Sub
        Debug.Print rng.Address
        Dim Source As Variant
        Debug.Print .Range(.Range(srcFirstCell).Offset(1, 1), rng.Offset(, 1)) _
          .Resize(, srcColumns).Address
        Source = .Range(.Range(srcFirstCell).Offset(1, 1), rng.Offset(, 1)) _
          .Resize(, srcColumns)
    End With

    ' Write transposed values from Source Array to Target Range.
    Dim tgt As Worksheet: Set tgt = ThisWorkbook.Worksheets(tgtName)
    Set rng = tgt.Columns(tgt.Range(tgtFirstCell).Column) _
      .Find(Criteria, , xlValues, xlWhole)
    If rng Is Nothing Then Exit Sub
    rng.Offset(, 1).Resize(UBound(Source, 2), UBound(Source)) _
      = Application.Transpose(Source)

    ' Inform user.
    MsgBox "Data transfer finished successfully.", vbInformation, "Success"

End Sub

' While assuming that the Target Sheet was empty I wrote the following code
' which transposes the complete data including headers.
Sub transposeDataComplete()

    Const srcName As String = "INPUT"
    Const tgtName As String = "DATA"
    Const srcFirstCell As String = "A1"
    Const tgtFirstCell As String = "A1"
    Const srcColumns As Long = 8 ' = 7 days + 1 for 'vertical' headers

    ' Write values from Source Range to Source Array.
    Dim src As Worksheet: Set src = ThisWorkbook.Worksheets(srcName)
    With src
        Dim rng As Range
        Set rng = .Columns(.Range(srcFirstCell).Column) _
          .Find("*", , xlValues, , , xlPrevious)
        If rng Is Nothing Then Exit Sub
        If rng.Row < .Range(srcFirstCell).Row Then Exit Sub
        Dim Source As Variant
        Source = .Range(.Range(srcFirstCell), rng).Resize(, srcColumns)
    End With
    Set rng = Nothing

    ' Write transposed values of Source Array to Target Range.
    Dim tgt As Worksheet: Set tgt = ThisWorkbook.Worksheets(tgtName)
    tgt.Range(tgtFirstCell).Resize(UBound(Source, 2), UBound(Source)) _
      = Application.Transpose(Source)

    ' Inform user.
    MsgBox "Data transfer finished successfully.", vbInformation, "Success"

End Sub


问:
Iterate over all rows in dataframe and check all column values are in list
I have a dataframe with 7 columns and ~5.000 rows. I want to check that all the column values in a row are in my list and if so either add them to a new dataframe OR remove those where all values do not match, i.e. remove false rows (w/e is the easiest);

```<code>for row in df:
   for columns in row:
      if df.iloc[row, column].isin(MyList):
         ...*something*
</code>```

I could imagine that .apply and .all could be used, but I'm afraid my python skills are limited, any help?

答:
If I understood correctly, you can solve this by using apply with a lambda expression like:

```<code>df.loc[df.apply(lambda row: all(value in MyList for value in row), axis=1))]
</code>```

Body:
I have a dataframe with 7 columns and ~5.000 rows. I want to check that all the column values in a row are in my list and if so either add them to a new dataframe OR remove those where all values do not match, i.e. remove false rows (w/e is the easiest);

for row in df:
   for columns in row:
      if df.iloc[row, column].isin(MyList):
         ...*something*

I could imagine that .apply and .all could be used, but I'm afraid my python skills are limited, any help?

Body:
If I understood correctly, you can solve this by using apply with a lambda expression like:

df.loc[df.apply(lambda row: all(value in MyList for value in row), axis=1))]


问:
Accumulated count for each element in a range
I have a table x, where start and end are hour of the day.

x = data.table(start=c(5,7,9,12), end=c(12,14,15,20), val = 7:10)

I want the output table to be:

for each hour from  hour 4 (not 5) to the 21 (not 20), has the accumulated value such as:

```<code>hour total
4    0
5    7
6    7
7    15(7+8)
</code>```

答:
My understanding of the OP question is that each row in the input dataset x is a segment with start and an end. We need to compute for each value in the total interval the sum of the values corresponding to the segments in which the hour is included.

One possible solution with dplyr/purrr:

```<code>
library(dplyr)
## Create the data
x = data.frame(start=c(5,7,9,12), end=c(12,14,15,20), val = as.double(7:10))
## Extract possible values
values <- seq(from=min(x$start), to=max(x$end))
## Function for one given hour
cumval <- function(hour){
    tibble(
        hour=hour,
        total = x %>% mutate(tot=if_else( (hour>=start & hour<=end), val, 0)) %>%
        pull(tot) %>% sum
        )
}
## Iterate
values %>% purrr::map_dfr(cumval)
</code>```

The output is:

```<code># A tibble: 16 x 2
    hour total
   <int> <dbl>
 1     5     7
 2     6     7
 3     7    15
 4     8    15
 5     9    24
 6    10    24
 7    11    24
 8    12    34
 9    13    27
10    14    27
11    15    19
12    16    10
13    17    10
14    18    10
15    19    10
16    20    10
</code>```

Body:
I have a table x, where start and end are hour of the day.

x = data.table(start=c(5,7,9,12), end=c(12,14,15,20), val = 7:10)

I want the output table to be:

for each hour from  hour 4 (not 5) to the 21 (not 20), has the accumulated value such as:

hour total
4    0
5    7
6    7
7    15(7+8)

Body:
My understanding of the OP question is that each row in the input dataset x is a segment with start and an end. We need to compute for each value in the total interval the sum of the values corresponding to the segments in which the hour is included.

One possible solution with dplyr/purrr:

library(dplyr)
## Create the data
x = data.frame(start=c(5,7,9,12), end=c(12,14,15,20), val = as.double(7:10))
## Extract possible values
values <- seq(from=min(x$start), to=max(x$end))
## Function for one given hour
cumval <- function(hour){
    tibble(
        hour=hour,
        total = x %>% mutate(tot=if_else( (hour>=start & hour<=end), val, 0)) %>%
        pull(tot) %>% sum
        )
}
## Iterate
values %>% purrr::map_dfr(cumval)

The output is:

# A tibble: 16 x 2
    hour total
   <int> <dbl>
 1     5     7
 2     6     7
 3     7    15
 4     8    15
 5     9    24
 6    10    24
 7    11    24
 8    12    34
 9    13    27
10    14    27
11    15    19
12    16    10
13    17    10
14    18    10
15    19    10
16    20    10


问:
Displaying data from database issue
I'm trying to display all the rows in my data from my data of my specific user but its only displaying 1 row and not updating.
the code is -</p>

```<code>$user = $_SESSION["username"];
$sql = "SELECT * FROM transactions WHERE sender OR receiver = ?";
if ($sql = $conn->prepare($sql)) {
    $sql->bind_param("s",$user);
    if ($sql->execute()) {
        $result = $sql->get_result();
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                 echo "<br> sender: ". $row["sender"]. " - receiver: ". $row["receiver"]. " -amount:" . $row["amount"] . "<br>";
                }
            }
            $sql->close();
            $conn->close();
        }else{ echo "0 result"; }
    }

?>
</code>```

答:
You are using wrong SQL formation & passing just receiver value. I suggest below changes:

Replaced

1) WHERE sender OR receiver = ? with WHERE sender=? OR receiver = ?

2) $sql->bind_param("s",$user); with $sql->bind_param("ss",$user,$user);

```<code>$user = $_SESSION["username"];
$sql = "SELECT * FROM transactions WHERE sender=? OR receiver = ?";
if ($sql = $conn->prepare($sql)) {
    $sql->bind_param("ss",$user,$user);
    if ($sql->execute()) {
        $result = $sql->get_result();
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                 echo "<br> sender: ". $row["sender"]. " - receiver: ". $row["receiver"]. " -amount:" . $row["amount"] . "<br>";
                }
            }
            $sql->close();
            $conn->close();
        }else{ echo "0 result"; }
    }
</code>```

Title: Displaying data from database issue

Body:
I'm trying to display all the rows in my data from my data of my specific user but its only displaying 1 row and not updating.
the code is -

$user = $_SESSION["username"];
$sql = "SELECT * FROM transactions WHERE sender OR receiver = ?";
if ($sql = $conn->prepare($sql)) {
    $sql->bind_param("s",$user);
    if ($sql->execute()) {
        $result = $sql->get_result();
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                 echo "
 sender: ". $row["sender"]. " - receiver: ". $row["receiver"]. " -amount:" . $row["amount"] . "
";
                }
            }
            $sql->close();
            $conn->close();
        }else{ echo "0 result"; }
    }

?>

Body:
You are using wrong SQL formation & passing just receiver value. I suggest below changes:

Replaced

1) WHERE sender OR receiver = ? with WHERE sender=? OR receiver = ?

2) $sql->bind_param("s",$user); with $sql->bind_param("ss",$user,$user);

$user = $_SESSION["username"];
$sql = "SELECT * FROM transactions WHERE sender=? OR receiver = ?";
if ($sql = $conn->prepare($sql)) {
    $sql->bind_param("ss",$user,$user);
    if ($sql->execute()) {
        $result = $sql->get_result();
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                 echo "<br> sender: ". $row["sender"]. " - receiver: ". $row["receiver"]. " -amount:" . $row["amount"] . "<br>";
                }
            }
            $sql->close();
            $conn->close();
        }else{ echo "0 result"; }
    }


问:
Manage a 4 dimensional array or a 5 dimensional with foreach statement in php
I am having a really bad time right now, since everyone on the internet is saying that PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people. So I can't find someone to help me.

A very simple example below

```<code>  $documents = array(
    array(
         "name"=>"Markos",
        "lastname"=>"papadopoulos",
        "country"=>"Greece",
        "nationality"=>"greek",
        "job"=>"web developer",
        "hobbies"=>array(
                "sports"=>"boxing",
                "others"=>array(
                        "freetime"=>"watching Tv"
                )
        )

    )
);

foreach($documents as $document){
    echo $document['name']."<br>"
        .$document['lastname']."<br>"
        .$document['country']."<br>"
        .$document['nationality']."<br>"
        .$document['job']."<br>";

            foreach ($document['hobbies'] as $key=>$value){
                echo $key." ".$value."<br>";

                    foreach ($value['others'] as $subkey=>$subvalue){
                        echo $subkey['freetime'];
                    }

                }
}
</code>```

I am stuck, I can't display the "others"=>array("freetime"=>"watching tv") can anyone advice me? And if I had also another array in the "others"=>array("freetime"=>"watching tv"), how could I display that array to? I am trying to learn the logic.

答:
```<code>foreach ($documents as $key) {
echo $key['name']. '<br>';
echo $key['lastname']. '<br>';
echo $key['country']. '<br>';
echo $key['nationality']. '<br>';
echo $key['job']. '<br>';
echo $key['hobbies']['sports']. '<br>';
echo $key['hobbies']['others']['freetime']. '<br>';
}
</code>```

output will be
Markos
papadopoulos
Greece
greek
web developer
boxing
watching Tv

Body:
I am having a really bad time right now, since everyone on the internet is saying that PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people. So I can't find someone to help me.

A very simple example below

  $documents = array(
    array(
         "name"=>"Markos",
        "lastname"=>"papadopoulos",
        "country"=>"Greece",
        "nationality"=>"greek",
        "job"=>"web developer",
        "hobbies"=>array(
                "sports"=>"boxing",
                "others"=>array(
                        "freetime"=>"watching Tv"
                )
        )

    )
);

foreach($documents as $document){
    echo $document['name']."
"
        .$document['lastname']."
"
        .$document['country']."
"
        .$document['nationality']."
"
        .$document['job']."
";

            foreach ($document['hobbies'] as $key=>$value){
                echo $key." ".$value."
";

                    foreach ($value['others'] as $subkey=>$subvalue){
                        echo $subkey['freetime'];
                    }

                }
}

I am stuck, I can't display the "others"=>array("freetime"=>"watching tv") can anyone advice me? And if I had also another array in the "others"=>array("freetime"=>"watching tv"), how could I display that array to? I am trying to learn the logic.

Body:
foreach ($documents as $key) {
echo $key['name']. '<br>';
echo $key['lastname']. '<br>';
echo $key['country']. '<br>';
echo $key['nationality']. '<br>';
echo $key['job']. '<br>';
echo $key['hobbies']['sports']. '<br>';
echo $key['hobbies']['others']['freetime']. '<br>';
}

output will be
Markos
papadopoulos
Greece
greek
web developer
boxing
watching Tv


问:
Gradle Swagger CodeGen DefaultGenerator CodegenConfigurator Add Lombok
I have a swagger and the following build.gradle file

```<code>buildscript {
    ext {
        springBootVersion = '2.1.8.RELEASE'
    }
    repositories {
        maven {
            url "https://mavenrepo.schwab.com/nexus/content/groups/public"
        }
        maven {
            url "https://mavenrepo.schwab.com/nexus/content/repositories/releases/"
        }
    }
    dependencies {
        classpath("io.swagger:swagger-codegen:2.4.7")
        classpath "io.spring.gradle:dependency-management-plugin:1.0.8.RELEASE"
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
        classpath "org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:2.7"
    }
}

apply plugin: 'idea'
apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

repositories {
    maven {
        url "https://mavenrepo.schwab.com/nexus/content/groups/public"
    }
}

import io.swagger.codegen.DefaultGenerator
import io.swagger.codegen.config.CodegenConfigurator

def swaggerInput = "${rootDir}/api/POMOrchestrator.v1.json"
def swaggerOutputDir = file('application/')

task generateApi {
    inputs.file(swaggerInput)
    outputs.dir(swaggerOutputDir)
    doLast {
        def config = new CodegenConfigurator()
        config.setInputSpec(swaggerInput)
        config.setOutputDir(swaggerOutputDir.path)
        config.setIgnoreFileOverride(swaggerOutputDir.path)
        config.setLang('spring')
        config.setAdditionalProperties([
                'invokerPackage': 'com.schwab.brokerage.party.onborading',
                'modelPackage'  : 'com.schwab.brokerage.party.onborading.models.swagger',
                'apiPackage'    : 'com.schwab.brokerage.party.onborading.api.inbound.rest.controller',
                'dateLibrary'   : 'java8',
                'useTags'       : 'true',  // Use tags for the naming
                'interfaceOnly' : 'true'   // Generating the Controller API interface and the models only

        ])
        config.setImportMappings([
                'hello': 'com.schwab.cat.onbording.model.Hello'
        ])
        new DefaultGenerator().opts(config.toClientOptInput()).generate()
    }
}

clean.doFirst {
    delete(swaggerOutputDir)
}

configurations {
    swagger
}

sourceSets {
    swagger {
        compileClasspath = configurations.swaggerCompile
        java {
            srcDir file("${project.buildDir.path}/swagger/src/main/java")
        }
    }
    main {
        compileClasspath += swagger.output
        runtimeClasspath += swagger.output
    }
    test {
        compileClasspath += swagger.output
        runtimeClasspath += swagger.output
    }
}

compileSwaggerJava.dependsOn generateApi
classes.dependsOn swaggerClasses
compileJava.dependsOn compileSwaggerJava

ext {
    springBootVersion = '2.1.8.RELEASE'

    swaggerVersion = '2.7.0'
    springCloudServicesVersion = '2.1.2.RELEASE'
    springCloudVersion = 'Greenwich.RC1'
    cucumberVersion = '2.3.1'

    jackson_version = '2.4.2'
    jersey_version = '1.18'
    jodatime_version = '2.3'
    junit_version = '4.8.1'
}

dependencies {
    swaggerCompile "org.springframework.boot:spring-boot-starter-web:$springBootVersion"
    swaggerCompile 'io.swagger:swagger-annotations:1.5.16'
    swaggerCompile 'com.squareup.okhttp:okhttp:2.7.5'
    swaggerCompile 'com.squareup.okhttp:logging-interceptor:2.7.5'
    swaggerCompile 'com.google.code.gson:gson:2.8.1'

    compile sourceSets.swagger.output

    compile "com.sun.jersey:jersey-client:$jersey_version"
    compile "com.sun.jersey.contribs:jersey-multipart:$jersey_version"
    compile "com.fasterxml.jackson.core:jackson-core:$jackson_version"
    compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version"
    compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version"
    compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:2.1.5"
    compile "joda-time:joda-time:$jodatime_version"
    compile 'io.swagger:swagger-codegen:2.2.3'

    testCompile "junit:junit:$junit_version"

    runtime 'com.squareup.okhttp:okhttp:2.7.5'
    runtime 'com.squareup.okhttp:logging-interceptor:2.7.5'
    runtime 'com.google.code.gson:gson:2.8.1'
}
</code>```

This does a fine job of creating the models only they do not have lombok annotations and for my purposes it would be really helpful to be able to add @Data and @Builder at the top.  Is there a way to tell the code gen to add these (perhaps a setting)?

答:
The solution was to use Mustaches (see https://github.com/spullara/mustache.java).  Here is the pojo mustache that added the lombok annotation.</p>

```<code>import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.Getter;

/**
 * {{#description}}{{.}}{{/description}}{{^description}}{{classname}}{{/description}}
 */{{#description}}
@ApiModel(description = "{{{description}}}"){{/description}}
{{>generatedAnnotation}}{{#discriminator}}{{>typeInfoAnnotation}}{{/discriminator}}{{>xmlAnnotation}}{{>additionalModelTypeAnnotations}}
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}}{{^parent}}{{#hateoas}}extends RepresentationModel<{{classname}}> {{/hateoas}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} {
{{#serializableModel}}
  private static final long serialVersionUID = 1L;

{{/serializableModel}}
  {{#vars}}
    {{#isEnum}}
    {{^isContainer}}
{{>enumClass}}
    {{/isContainer}}
    {{#isContainer}}
    {{#mostInnerItems}}
{{>enumClass}}
    {{/mostInnerItems}}
    {{/isContainer}}
    {{/isEnum}}
  {{#jackson}}
  @JsonProperty("{{baseName}}"){{#withXml}}
  @JacksonXmlProperty({{#isXmlAttribute}}isAttribute = true, {{/isXmlAttribute}}{{#xmlNamespace}}namespace="{{xmlNamespace}}", {{/xmlNamespace}}localName = "{{#xmlName}}{{xmlName}}{{/xmlName}}{{^xmlName}}{{baseName}}{{/xmlName}}"){{/withXml}}
  {{/jackson}}
  {{#gson}}
  @SerializedName("{{baseName}}")
  {{/gson}}
  {{#isContainer}}
  {{#useBeanValidation}}@Valid{{/useBeanValidation}}
  private {{>nullableDataType}} {{name}};
  {{/isContainer}}
  {{^isContainer}}
  {{#isDate}}
  @org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE)
  {{/isDate}}
  {{#isDateTime}}
  @org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE_TIME)
  {{/isDateTime}}
  private {{>nullableDataType}} {{name}};
  {{/isContainer}}

  {{/vars}}

  /**
   * Convert the given object to string with each line indented by 4 spaces
   * (except the first line).
   */
  private String toIndentedString(java.lang.Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }
}
</code>```

Body:
I have a swagger and the following build.gradle file

buildscript {
    ext {
        springBootVersion = '2.1.8.RELEASE'
    }
    repositories {
        maven {
            url "https://mavenrepo.schwab.com/nexus/content/groups/public"
        }
        maven {
            url "https://mavenrepo.schwab.com/nexus/content/repositories/releases/"
        }
    }
    dependencies {
        classpath("io.swagger:swagger-codegen:2.4.7")
        classpath "io.spring.gradle:dependency-management-plugin:1.0.8.RELEASE"
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
        classpath "org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:2.7"
    }
}

apply plugin: 'idea'
apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

repositories {
    maven {
        url "https://mavenrepo.schwab.com/nexus/content/groups/public"
    }
}

import io.swagger.codegen.DefaultGenerator
import io.swagger.codegen.config.CodegenConfigurator

def swaggerInput = "${rootDir}/api/POMOrchestrator.v1.json"
def swaggerOutputDir = file('application/')

task generateApi {
    inputs.file(swaggerInput)
    outputs.dir(swaggerOutputDir)
    doLast {
        def config = new CodegenConfigurator()
        config.setInputSpec(swaggerInput)
        config.setOutputDir(swaggerOutputDir.path)
        config.setIgnoreFileOverride(swaggerOutputDir.path)
        config.setLang('spring')
        config.setAdditionalProperties([
                'invokerPackage': 'com.schwab.brokerage.party.onborading',
                'modelPackage'  : 'com.schwab.brokerage.party.onborading.models.swagger',
                'apiPackage'    : 'com.schwab.brokerage.party.onborading.api.inbound.rest.controller',
                'dateLibrary'   : 'java8',
                'useTags'       : 'true',  // Use tags for the naming
                'interfaceOnly' : 'true'   // Generating the Controller API interface and the models only

        ])
        config.setImportMappings([
                'hello': 'com.schwab.cat.onbording.model.Hello'
        ])
        new DefaultGenerator().opts(config.toClientOptInput()).generate()
    }
}

clean.doFirst {
    delete(swaggerOutputDir)
}

configurations {
    swagger
}

sourceSets {
    swagger {
        compileClasspath = configurations.swaggerCompile
        java {
            srcDir file("${project.buildDir.path}/swagger/src/main/java")
        }
    }
    main {
        compileClasspath += swagger.output
        runtimeClasspath += swagger.output
    }
    test {
        compileClasspath += swagger.output
        runtimeClasspath += swagger.output
    }
}

compileSwaggerJava.dependsOn generateApi
classes.dependsOn swaggerClasses
compileJava.dependsOn compileSwaggerJava

ext {
    springBootVersion = '2.1.8.RELEASE'

    swaggerVersion = '2.7.0'
    springCloudServicesVersion = '2.1.2.RELEASE'
    springCloudVersion = 'Greenwich.RC1'
    cucumberVersion = '2.3.1'

    jackson_version = '2.4.2'
    jersey_version = '1.18'
    jodatime_version = '2.3'
    junit_version = '4.8.1'
}

dependencies {
    swaggerCompile "org.springframework.boot:spring-boot-starter-web:$springBootVersion"
    swaggerCompile 'io.swagger:swagger-annotations:1.5.16'
    swaggerCompile 'com.squareup.okhttp:okhttp:2.7.5'
    swaggerCompile 'com.squareup.okhttp:logging-interceptor:2.7.5'
    swaggerCompile 'com.google.code.gson:gson:2.8.1'

    compile sourceSets.swagger.output

    compile "com.sun.jersey:jersey-client:$jersey_version"
    compile "com.sun.jersey.contribs:jersey-multipart:$jersey_version"
    compile "com.fasterxml.jackson.core:jackson-core:$jackson_version"
    compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version"
    compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version"
    compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:2.1.5"
    compile "joda-time:joda-time:$jodatime_version"
    compile 'io.swagger:swagger-codegen:2.2.3'

    testCompile "junit:junit:$junit_version"

    runtime 'com.squareup.okhttp:okhttp:2.7.5'
    runtime 'com.squareup.okhttp:logging-interceptor:2.7.5'
    runtime 'com.google.code.gson:gson:2.8.1'
}

This does a fine job of creating the models only they do not have lombok annotations and for my purposes it would be really helpful to be able to add @Data and @Builder at the top.  Is there a way to tell the code gen to add these (perhaps a setting)?

Body:
The solution was to use Mustaches (see https://github.com/spullara/mustache.java).  Here is the pojo mustache that added the lombok annotation.

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.Getter;

/**
 * {{#description}}{{.}}{{/description}}{{^description}}{{classname}}{{/description}}
 */{{#description}}
@ApiModel(description = "{{{description}}}"){{/description}}
{{>generatedAnnotation}}{{#discriminator}}{{>typeInfoAnnotation}}{{/discriminator}}{{>xmlAnnotation}}{{>additionalModelTypeAnnotations}}
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}}{{^parent}}{{#hateoas}}extends RepresentationModel<{{classname}}> {{/hateoas}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} {
{{#serializableModel}}
  private static final long serialVersionUID = 1L;

{{/serializableModel}}
  {{#vars}}
    {{#isEnum}}
    {{^isContainer}}
{{>enumClass}}
    {{/isContainer}}
    {{#isContainer}}
    {{#mostInnerItems}}
{{>enumClass}}
    {{/mostInnerItems}}
    {{/isContainer}}
    {{/isEnum}}
  {{#jackson}}
  @JsonProperty("{{baseName}}"){{#withXml}}
  @JacksonXmlProperty({{#isXmlAttribute}}isAttribute = true, {{/isXmlAttribute}}{{#xmlNamespace}}namespace="{{xmlNamespace}}", {{/xmlNamespace}}localName = "{{#xmlName}}{{xmlName}}{{/xmlName}}{{^xmlName}}{{baseName}}{{/xmlName}}"){{/withXml}}
  {{/jackson}}
  {{#gson}}
  @SerializedName("{{baseName}}")
  {{/gson}}
  {{#isContainer}}
  {{#useBeanValidation}}@Valid{{/useBeanValidation}}
  private {{>nullableDataType}} {{name}};
  {{/isContainer}}
  {{^isContainer}}
  {{#isDate}}
  @org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE)
  {{/isDate}}
  {{#isDateTime}}
  @org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE_TIME)
  {{/isDateTime}}
  private {{>nullableDataType}} {{name}};
  {{/isContainer}}

  {{/vars}}

  /**
   * Convert the given object to string with each line indented by 4 spaces
   * (except the first line).
   */
  private String toIndentedString(java.lang.Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }
}


问:
How do I check if an input is in fact in a column in pandas?
Example of the dataFrame:

```<code>df = {'column': 'hello'}
</code>```

The input should be an entry in the dataFrame

```<code>if 'hello' in df['column']:
   print("hello")
else:
  print("Couldn't find entry)
</code>```

What I would want as the output would be:

```<code>Hello
</code>```

However, the output comes out as:

```<code>Couldn't find entry
</code>```

I've checked and the value entered in the input is definitely inside that column of the dataFrame
I don't know if im doing anything incorrectly or why it is not working

答:
I ran your code and got the correct output:

```<code>df = {'column': 'hello'}

if 'hello' in df['column']:
   print("hello")
else:
  print("Couldn't find entry")
</code>```

Output:

```<code>hello
</code>```

Body:
Example of the dataFrame:

df = {'column': 'hello'}

The input should be an entry in the dataFrame

if 'hello' in df['column']:
   print("hello")
else:
  print("Couldn't find entry)

What I would want as the output would be:

Hello

However, the output comes out as:

Couldn't find entry

I've checked and the value entered in the input is definitely inside that column of the dataFrame
I don't know if im doing anything incorrectly or why it is not working

Body:
I ran your code and got the correct output:

df = {'column': 'hello'}

if 'hello' in df['column']:
   print("hello")
else:
  print("Couldn't find entry")

Output:

hello


问:
How to apply piecewise linear fit in Python?
I am trying to fit piecewise linear fit as shown in fig.1 for a data set

This figure was obtained by setting on the lines. I attempted to apply a piecewise linear fit using the code:

```<code>from scipy import optimize
import matplotlib.pyplot as plt
import numpy as np

x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ,11, 12, 13, 14, 15])
y = np.array([5, 7, 9, 11, 13, 15, 28.92, 42.81, 56.7, 70.59, 84.47, 98.36, 112.25, 126.14, 140.03])

def linear_fit(x, a, b):
    return a * x + b
fit_a, fit_b = optimize.curve_fit(linear_fit, x[0:5], y[0:5])[0]
y_fit = fit_a * x[0:7] + fit_b
fit_a, fit_b = optimize.curve_fit(linear_fit, x[6:14], y[6:14])[0]
y_fit = np.append(y_fit, fit_a * x[6:14] + fit_b)

figure = plt.figure(figsize=(5.15, 5.15))
figure.clf()
plot = plt.subplot(111)
ax1 = plt.gca()
plot.plot(x, y, linestyle = '', linewidth = 0.25, markeredgecolor='none', marker = 'o', label = r'\textit{y_a}')
plot.plot(x, y_fit, linestyle = ':', linewidth = 0.25, markeredgecolor='none', marker = '', label = r'\textit{y_b}')
plot.set_ylabel('Y', labelpad = 6)
plot.set_xlabel('X', labelpad = 6)
figure.savefig('test.pdf', box_inches='tight')
plt.close()
</code>```

But this gave me fitting of the form in fig. 2, I tried playing with the values but no change I can't get the fit of the upper line proper. The most important requirement for me is how can I get Python to get the gradient change point. In essence I want Python to recognize and fit two linear fits in the appropriate range. How can this be done in Python?

答:
I think that UnivariateSpline from scipy.interpolate would provide the simplest and very likely the fastest way to do piecewise fit. To add a bit of context, spline is a function defined piecewise by polynomials. In your case, you are looking for a linear spline which is defined by k=1 in UnivariateSpline. Also, s=0.5 is a smoothing factor which indicates how good the fit should be (check out the documentation for more info on it).

```<code>import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import UnivariateSpline

x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
y = np.array([5, 7, 9, 11, 13, 15, 28.92, 42.81, 56.7, 70.59, 84.47, 98.36, 112.25, 126.14, 140.03])

# Solution
spl = UnivariateSpline(x, y, k=1, s=0.5)
xs = np.linspace(x.min(), x.max(), 1000)

fig, ax = plt.subplots()
ax.scatter(x, y, color="red", s=20, zorder=20)
ax.plot(xs, spl(xs), linestyle="--", linewidth=1, color="blue", zorder=10)
ax.grid(color="grey", linestyle="--", linewidth=.5, alpha=.5)
ax.set_ylabel("Y")
ax.set_xlabel("X")
plt.show()
</code>```

Body:
I am trying to fit piecewise linear fit as shown in fig.1 for a data set

This figure was obtained by setting on the lines. I attempted to apply a piecewise linear fit using the code:

from scipy import optimize
import matplotlib.pyplot as plt
import numpy as np

x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ,11, 12, 13, 14, 15])
y = np.array([5, 7, 9, 11, 13, 15, 28.92, 42.81, 56.7, 70.59, 84.47, 98.36, 112.25, 126.14, 140.03])

def linear_fit(x, a, b):
    return a * x + b
fit_a, fit_b = optimize.curve_fit(linear_fit, x[0:5], y[0:5])[0]
y_fit = fit_a * x[0:7] + fit_b
fit_a, fit_b = optimize.curve_fit(linear_fit, x[6:14], y[6:14])[0]
y_fit = np.append(y_fit, fit_a * x[6:14] + fit_b)

figure = plt.figure(figsize=(5.15, 5.15))
figure.clf()
plot = plt.subplot(111)
ax1 = plt.gca()
plot.plot(x, y, linestyle = '', linewidth = 0.25, markeredgecolor='none', marker = 'o', label = r'\textit{y_a}')
plot.plot(x, y_fit, linestyle = ':', linewidth = 0.25, markeredgecolor='none', marker = '', label = r'\textit{y_b}')
plot.set_ylabel('Y', labelpad = 6)
plot.set_xlabel('X', labelpad = 6)
figure.savefig('test.pdf', box_inches='tight')
plt.close()

But this gave me fitting of the form in fig. 2, I tried playing with the values but no change I can't get the fit of the upper line proper. The most important requirement for me is how can I get Python to get the gradient change point. In essence I want Python to recognize and fit two linear fits in the appropriate range. How can this be done in Python?

Body:
I think that UnivariateSpline from scipy.interpolate would provide the simplest and very likely the fastest way to do piecewise fit. To add a bit of context, spline is a function defined piecewise by polynomials. In your case, you are looking for a linear spline which is defined by k=1 in UnivariateSpline. Also, s=0.5 is a smoothing factor which indicates how good the fit should be (check out the documentation for more info on it).

import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import UnivariateSpline

x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
y = np.array([5, 7, 9, 11, 13, 15, 28.92, 42.81, 56.7, 70.59, 84.47, 98.36, 112.25, 126.14, 140.03])

# Solution
spl = UnivariateSpline(x, y, k=1, s=0.5)
xs = np.linspace(x.min(), x.max(), 1000)

fig, ax = plt.subplots()
ax.scatter(x, y, color="red", s=20, zorder=20)
ax.plot(xs, spl(xs), linestyle="--", linewidth=1, color="blue", zorder=10)
ax.grid(color="grey", linestyle="--", linewidth=.5, alpha=.5)
ax.set_ylabel("Y")
ax.set_xlabel("X")
plt.show()