问:
Mockito cannot mock this class: interface
I'm having an issue with mockito and powermock, I can mock an abstract class with a final static method with no problems. When trying to mock an Interface as with WebIServerSession I'm getting the stacktrace below. I've had a look at other issues in powermock github repo and it seems to be related with the jvm version. I've already upgraded to the latest 1.8 java version as stated in https://github.com/mockito/mockito/issues/636 and I'm still getting the same error. Might it be related with Powermock compatibility with Mockito 2?

```<code>import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.testng.PowerMockTestCase;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.doReturn;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.spy;
import static org.powermock.api.mockito.PowerMockito.verifyPrivate;
import static org.powermock.api.mockito.PowerMockito.whenNew;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;

@BeforeMethod
public void setup() throws Exception {
    mockStatic(ResourceBundle.class);
    mockStatic(WebObjectsFactory.class);
    WebObjectsFactory webObjectsFactory = mock(WebObjectsFactory.class);
    WebIServerSession webIServerSession = mock(WebIServerSession.class);

    PowerMockito.when(WebObjectsFactory.getInstance()).thenReturn(webObjectsFactory);
    PowerMockito.when(webObjectsFactory.getIServerSession()).thenReturn(webIServerSession);
    whenNew(ThreadLocal.class).withNoArguments().thenReturn(errorContainer);

    MockitoAnnotations.initMocks(this);
}

@Test
public void shouldBeTrue() {
    assertTrue(true);
}
</code>```

Maven dependencies:

```<code><dependencies>
    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>6.14.3</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>2.8.9</version>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-core</artifactId>
        <version>1.7.4</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-module-testng</artifactId>
        <version>1.7.4</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-api-mockito2</artifactId>
        <version>1.7.4</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-reflect</artifactId>
        <version>1.7.4</version>
        <scope>test</scope>
    </dependency>
</dependencies>
</code>```

Stacktrace:

```<code>org.mockito.exceptions.base.MockitoException:
Mockito cannot mock this class: interface com.microstrategy.web.objects.WebIServerSession.

Mockito can only mock non-private & non-final classes.
If you're not sure why you're getting this error, please report to the mailing list.

Java               : 1.8
JVM vendor name    : Oracle Corporation
JVM vendor version : 25.191-b12
JVM name           : Java HotSpot(TM) 64-Bit Server VM
JVM version        : 1.8.0_191-b12
JVM info           : mixed mode
OS name            : Mac OS X
OS version         : 10.14.1

Underlying exception : java.lang.IllegalArgumentException: Could not create type

    at com.myproject.SSOESMTest.setup(SSOESMTest.java:63)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
    at org.testng.internal.MethodInvocationHelper.invokeMethodConsideringTimeout(MethodInvocationHelper.java:59)
    at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:458)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:222)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:523)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:719)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:989)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
    at org.testng.TestRunner.privateRun(TestRunner.java:648)
    at org.testng.TestRunner.run(TestRunner.java:505)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)
    at org.testng.SuiteRunner.run(SuiteRunner.java:364)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1137)
    at org.testng.TestNG.runSuites(TestNG.java:1049)
    at org.testng.TestNG.run(TestNG.java:1017)
    at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:72)
    at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:123)
Caused by: java.lang.IllegalArgumentException: Could not create type
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:154)
    at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:365)
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:174)
    at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:376)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.mockClass(TypeCachingBytecodeGenerator.java:32)
    at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMockType(SubclassByteBuddyMockMaker.java:71)
    at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMock(SubclassByteBuddyMockMaker.java:42)
    at org.powermock.api.mockito.mockmaker.PowerMockMaker.createMock(PowerMockMaker.java:50)
    at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.createMethodInvocationControl(DefaultMockCreator.java:116)
    at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.createMock(DefaultMockCreator.java:69)
    at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.mock(DefaultMockCreator.java:46)
    at org.powermock.api.mockito.PowerMockito.mock(PowerMockito.java:138)
    ... 28 more
Caused by: java.lang.NoClassDefFoundError: com/microstrategy/utils/xml/SAXSupport
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
    at java.lang.Class.getDeclaredMethods(Class.java:1975)
    at net.bytebuddy.description.method.MethodList$ForLoadedMethods.<init>(MethodList.java:109)
    at net.bytebuddy.description.type.TypeDescription$ForLoadedType.getDeclaredMethods(TypeDescription.java:8426)
    at net.bytebuddy.description.type.TypeDescription$Generic$OfNonGenericType.getDeclaredMethods(TypeDescription.java:3654)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:634)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.analyze(MethodGraph.java:596)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:632)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.analyze(MethodGraph.java:596)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:632)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.analyze(MethodGraph.java:596)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:632)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.compile(MethodGraph.java:567)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$AbstractBase.compile(MethodGraph.java:465)
    at net.bytebuddy.dynamic.scaffold.MethodRegistry$Default.prepare(MethodRegistry.java:463)
    at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:198)
    at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:189)
    at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase.make(DynamicType.java:3394)
    at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase$Delegator.make(DynamicType.java:3583)
    at org.mockito.internal.creation.bytebuddy.SubclassBytecodeGenerator.mockClass(SubclassBytecodeGenerator.java:94)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:37)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:34)
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:152)
    ... 39 more
Caused by: java.lang.ClassNotFoundException: com.microstrategy.utils.xml.SAXSupport
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at org.powermock.core.classloader.MockClassLoader.loadModifiedClass(MockClassLoader.java:202)
    at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass1(DeferSupportingClassLoader.java:89)
    at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass(DeferSupportingClassLoader.java:79)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 63 more

Test ignored.

===============================================
Default Suite
Total tests run: 1, Failures: 0, Skips: 1
Configuration Failures: 1, Skips: 2
===============================================

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

答:
annotate your test class like this

```<code>@RunWith(PowerMockRunner.class)
@PrepareForTest({ResourceBundle.class, WebObjectsFactory.class, AnyOtherClassThatContainsStaticMethod.class, . . .})
</code>```

ref: https://github.com/powermock/powermock/wiki/mockstatic

Body:
I'm having an issue with mockito and powermock, I can mock an abstract class with a final static method with no problems. When trying to mock an Interface as with WebIServerSession I'm getting the stacktrace below. I've had a look at other issues in powermock github repo and it seems to be related with the jvm version. I've already upgraded to the latest 1.8 java version as stated in https://github.com/mockito/mockito/issues/636 and I'm still getting the same error. Might it be related with Powermock compatibility with Mockito 2?

import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.testng.PowerMockTestCase;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.doReturn;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.spy;
import static org.powermock.api.mockito.PowerMockito.verifyPrivate;
import static org.powermock.api.mockito.PowerMockito.whenNew;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;

@BeforeMethod
public void setup() throws Exception {
    mockStatic(ResourceBundle.class);
    mockStatic(WebObjectsFactory.class);
    WebObjectsFactory webObjectsFactory = mock(WebObjectsFactory.class);
    WebIServerSession webIServerSession = mock(WebIServerSession.class);

    PowerMockito.when(WebObjectsFactory.getInstance()).thenReturn(webObjectsFactory);
    PowerMockito.when(webObjectsFactory.getIServerSession()).thenReturn(webIServerSession);
    whenNew(ThreadLocal.class).withNoArguments().thenReturn(errorContainer);

    MockitoAnnotations.initMocks(this);
}

@Test
public void shouldBeTrue() {
    assertTrue(true);
}

Maven dependencies:

<dependencies>
    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>6.14.3</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>2.8.9</version>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-core</artifactId>
        <version>1.7.4</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-module-testng</artifactId>
        <version>1.7.4</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-api-mockito2</artifactId>
        <version>1.7.4</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-reflect</artifactId>
        <version>1.7.4</version>
        <scope>test</scope>
    </dependency>
</dependencies>

Stacktrace:

org.mockito.exceptions.base.MockitoException:
Mockito cannot mock this class: interface com.microstrategy.web.objects.WebIServerSession.

Mockito can only mock non-private & non-final classes.
If you're not sure why you're getting this error, please report to the mailing list.

Java               : 1.8
JVM vendor name    : Oracle Corporation
JVM vendor version : 25.191-b12
JVM name           : Java HotSpot(TM) 64-Bit Server VM
JVM version        : 1.8.0_191-b12
JVM info           : mixed mode
OS name            : Mac OS X
OS version         : 10.14.1

Underlying exception : java.lang.IllegalArgumentException: Could not create type

    at com.myproject.SSOESMTest.setup(SSOESMTest.java:63)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
    at org.testng.internal.MethodInvocationHelper.invokeMethodConsideringTimeout(MethodInvocationHelper.java:59)
    at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:458)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:222)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:523)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:719)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:989)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
    at org.testng.TestRunner.privateRun(TestRunner.java:648)
    at org.testng.TestRunner.run(TestRunner.java:505)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)
    at org.testng.SuiteRunner.run(SuiteRunner.java:364)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1137)
    at org.testng.TestNG.runSuites(TestNG.java:1049)
    at org.testng.TestNG.run(TestNG.java:1017)
    at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:72)
    at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:123)
Caused by: java.lang.IllegalArgumentException: Could not create type
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:154)
    at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:365)
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:174)
    at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:376)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.mockClass(TypeCachingBytecodeGenerator.java:32)
    at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMockType(SubclassByteBuddyMockMaker.java:71)
    at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMock(SubclassByteBuddyMockMaker.java:42)
    at org.powermock.api.mockito.mockmaker.PowerMockMaker.createMock(PowerMockMaker.java:50)
    at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.createMethodInvocationControl(DefaultMockCreator.java:116)
    at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.createMock(DefaultMockCreator.java:69)
    at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.mock(DefaultMockCreator.java:46)
    at org.powermock.api.mockito.PowerMockito.mock(PowerMockito.java:138)
    ... 28 more
Caused by: java.lang.NoClassDefFoundError: com/microstrategy/utils/xml/SAXSupport
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
    at java.lang.Class.getDeclaredMethods(Class.java:1975)
    at net.bytebuddy.description.method.MethodList$ForLoadedMethods.<init>(MethodList.java:109)
    at net.bytebuddy.description.type.TypeDescription$ForLoadedType.getDeclaredMethods(TypeDescription.java:8426)
    at net.bytebuddy.description.type.TypeDescription$Generic$OfNonGenericType.getDeclaredMethods(TypeDescription.java:3654)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:634)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.analyze(MethodGraph.java:596)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:632)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.analyze(MethodGraph.java:596)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:632)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.analyze(MethodGraph.java:596)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:632)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.compile(MethodGraph.java:567)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$AbstractBase.compile(MethodGraph.java:465)
    at net.bytebuddy.dynamic.scaffold.MethodRegistry$Default.prepare(MethodRegistry.java:463)
    at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:198)
    at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:189)
    at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase.make(DynamicType.java:3394)
    at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase$Delegator.make(DynamicType.java:3583)
    at org.mockito.internal.creation.bytebuddy.SubclassBytecodeGenerator.mockClass(SubclassBytecodeGenerator.java:94)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:37)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:34)
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:152)
    ... 39 more
Caused by: java.lang.ClassNotFoundException: com.microstrategy.utils.xml.SAXSupport
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at org.powermock.core.classloader.MockClassLoader.loadModifiedClass(MockClassLoader.java:202)
    at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass1(DeferSupportingClassLoader.java:89)
    at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass(DeferSupportingClassLoader.java:79)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 63 more

Test ignored.

===============================================
Default Suite
Total tests run: 1, Failures: 0, Skips: 1
Configuration Failures: 1, Skips: 2
===============================================

Process finished with exit code 0

Body:
annotate your test class like this

@RunWith(PowerMockRunner.class)
@PrepareForTest({ResourceBundle.class, WebObjectsFactory.class, AnyOtherClassThatContainsStaticMethod.class, . . .})

ref: https://github.com/powermock/powermock/wiki/mockstatic


来源: stackexchange

问:
How to trigger a Windows and L key Python-hotkey?
I am trying to run this code in Python.

```<code>import pyautogui
pyautogui.hotkey('win', 'l')
</code>```

So that when I run it it will trigger switch user in Windows but all it does is press l when I need it to press Win+l

答:
```<code>import pyautogui
pyautogui.hotkey('winleft', 'l')
</code>```

This is working in my laptop.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to run this code in Python.

import pyautogui
pyautogui.hotkey('win', 'l')

So that when I run it it will trigger switch user in Windows but all it does is press l when I need it to press Win+l

Body:
import pyautogui
pyautogui.hotkey('winleft', 'l')

This is working in my laptop.


问:
How do I invoke the debugger in a Rails functional test?
With Rails 3, Ruby 1.9, and Test::Unit, what's the right way to invoke the debugger on a functional test? I've tried adding "debugger" and then running rake:test:functionals:

```<code>class AdminControllerTest < ActionController::TestCase
    test "should get index" do
        debugger
        get :index
        assert_redirected_to welcome_url
    end
end
</code>```

but Ruby seems to ignore the call to debugger (the test goes ahead and runs normally). If I try running the test directly:

```<code>ruby -r debug test/functional/admin_controller_test.rb
</code>```

then Ruby can't find test_helper.rb.  If, following the answer below, I run:

```<code>ruby -I "lib:test" test/functional/admin_controller_test.rb
</code>```

then it finds test_helper but again runs the test to completion without invoking the debugger. My Gemfile does have:

```<code>gem 'ruby-debug19', :require => 'ruby-debug', :group => :development
</code>```

答:
I've always been able to debug tests using just:

```<code>ruby -I"lib:test" test/functional/admin_controller_test.rb
</code>```

I've got the following in my .rdebugrc file, if it helps:

```<code>set autolist
set autoeval
set autoreload
set forcestep
</code>```

ContentLicense: CC BY-SA 3.0

Body:
With Rails 3, Ruby 1.9, and Test::Unit, what's the right way to invoke the debugger on a functional test? I've tried adding "debugger" and then running rake:test:functionals:

class AdminControllerTest < ActionController::TestCase
    test "should get index" do
        debugger
        get :index
        assert_redirected_to welcome_url
    end
end

but Ruby seems to ignore the call to debugger (the test goes ahead and runs normally). If I try running the test directly:

ruby -r debug test/functional/admin_controller_test.rb

then Ruby can't find test_helper.rb.  If, following the answer below, I run:

ruby -I "lib:test" test/functional/admin_controller_test.rb

then it finds test_helper but again runs the test to completion without invoking the debugger. My Gemfile does have:

gem 'ruby-debug19', :require => 'ruby-debug', :group => :development

Body:
I've always been able to debug tests using just:

ruby -I"lib:test" test/functional/admin_controller_test.rb

I've got the following in my .rdebugrc file, if it helps:

set autolist
set autoeval
set autoreload
set forcestep


问:
Gracefully stop socket during blocking call to socket.recv()
I have a program which runs on 2 threads. The main thread is for its own work and the other thread keeps calling recv() on a UDP socket.

Basically, the code structure looks like this:

done = False

def run_sock():
   sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
   sock.bind(('localhost', 12345))
   while not done:  # receive data until work done
        data = sock.recv(1500)
        print(data)
   sock.close()

thread = threading.Thread(target=run_sock, daemon=True)
thread.start()

# Main thread
while not done:
    ... # Do work here
    if some_condition:  # Stop running, thread should as well
        done = True

thread.join()

```

I want to close the socket when the main thread changes done to True, but when that happens, the socket is still in its current blocking recv call and it has to receive another message before it finally stops.

Is there a way to gracefully close the socket (without having to handle errors)? I've tried sock.shutdown(socket.SHUT_RDWR), sock.setblocking(False) and but they all raise errors.

答:
So sock.recv(1500) will block until it receives something. If it receives nothing, then it waits.

But if you set a timeout then periodically that wait will throw an exception and you can do other stuff (like look at the done flag) before trying to read again.

```<code>sock.settimeout(1.0)
sock.bind(...)

while not done:
    try:
        data = sock.recv(1500)
    except timeout:
        continue
sock.close()
</code>```

Of course, if the remote end closes the connection that is different. Then you need to look at data to see if it is empty.

```<code>while not done:
    try:
        data = sock.recv(1500)
        if not data:
            break
    except timeout:
        continue
</code>```

Body:
I have a program which runs on 2 threads. The main thread is for its own work and the other thread keeps calling recv() on a UDP socket.

Basically, the code structure looks like this:

done = False

def run_sock():
   sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
   sock.bind(('localhost', 12345))
   while not done:  # receive data until work done
        data = sock.recv(1500)
        print(data)
   sock.close()

thread = threading.Thread(target=run_sock, daemon=True)
thread.start()

# Main thread
while not done:
    ... # Do work here
    if some_condition:  # Stop running, thread should as well
        done = True

thread.join()

I want to close the socket when the main thread changes done to True, but when that happens, the socket is still in its current blocking recv call and it has to receive another message before it finally stops.

Is there a way to gracefully close the socket (without having to handle errors)? I've tried sock.shutdown(socket.SHUT_RDWR), sock.setblocking(False) and but they all raise errors.

Body:
So sock.recv(1500) will block until it receives something. If it receives nothing, then it waits.

But if you set a timeout then periodically that wait will throw an exception and you can do other stuff (like look at the done flag) before trying to read again.

sock.settimeout(1.0)
sock.bind(...)

while not done:
    try:
        data = sock.recv(1500)
    except timeout:
        continue
sock.close()

Of course, if the remote end closes the connection that is different. Then you need to look at data to see if it is empty.

while not done:
    try:
        data = sock.recv(1500)
        if not data:
            break
    except timeout:
        continue


问:
Is there a EASY way to use a variable in a PostgreSQL query?

Using: PostgreSQL10 & pgAdmin4

So this query is simple:

```<code>SELECT * FROM [schema_name].[table_name]
   WHERE [schema_name].[table_name].[field_name] = 'search_value';
</code>```

In Transact-SQL you can create a variable for "search_value":

```<code>DECLARE @find varchar(30) = 'search_value';

SELECT * FROM [schema_name].[table_name]
   WHERE [schema_name].[table_name].[field_name] = @find;
</code>```

And even re-use the variable:

```<code>SET @find = 'new_search_value';
</code>```

I have now tried everything to mimic this in PostgreSQL, but I can't get it working.

Any suggestions???

答:
You can do this with a custom configuration value:

```<code>SELECT set_config('vars.find', 'search_value', false);

SELECT * FROM schema_name.table_name
   WHERE schema_name.table_name.field_name = current_setting('vars.find');
</code>```

The name needs a namespace (vars in this case), but you can use any random string for this.

That last boolean parameter to set_config() determines whether the new value lasts for the rest of your session (false) or resets at the end of the current transaction (true).

Body:
Using: PostgreSQL10 & pgAdmin4

So this query is simple:

SELECT * FROM [schema_name].[table_name]
   WHERE [schema_name].[table_name].[field_name] = 'search_value';

In Transact-SQL you can create a variable for "search_value":

DECLARE @find varchar(30) = 'search_value';

SELECT * FROM [schema_name].[table_name]
   WHERE [schema_name].[table_name].[field_name] = @find;

And even re-use the variable:

SET @find = 'new_search_value';

I have now tried everything to mimic this in PostgreSQL, but I can't get it working.

Any suggestions???

Body:
You can do this with a custom configuration value:

SELECT set_config('vars.find', 'search_value', false);

SELECT * FROM schema_name.table_name
   WHERE schema_name.table_name.field_name = current_setting('vars.find');

The name needs a namespace (vars in this case), but you can use any random string for this.

That last boolean parameter to set_config() determines whether the new value lasts for the rest of your session (false) or resets at the end of the current transaction (true).


问:
JavaFX: Exception handling in an editable TextFieldTableCell
My TableView is editable, so I can update the price and quantity directly from the table without pressing any button. My price and quantity are Integers so, how can I handle an exception when I enter a String value? I want my program to show a DialogPane with a message or something like that?

```<code>import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.util.converter.IntegerStringConverter;
import model.Produs;
import service.Service;
import validator.ValidationException;

import javax.persistence.criteria.CriteriaBuilder;
import java.net.URL;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

public class ControllerAdmin implements Initializable  {

    @FXML
    private TableView<Produs> table;

    @FXML
    private TableColumn<Produs, String> colNume;

    @FXML
    private TableColumn<Produs, Integer> colPret;

    @FXML
    private TableColumn<Produs, Integer> colCantitate;

    @FXML
    private TextField lblNume;

    @FXML
    private TextField lblCant;

    @FXML
    private TextField lblPret;

    private ObservableList<Produs> observableList;

    private Service service;
    public ControllerAdmin(){}
    public void setService(Service service){
        this.service=service;
        observableList = FXCollections.observableList(StreamSupport.stream(service.getAllProducts().spliterator(), false).collect(Collectors.toList()));
        observableList.remove(new Produs("b",2,2));
        loadTables();
    }

    private void loadTables() {
        table.setItems(observableList);
        table.getSelectionModel().selectedItemProperty().addListener((observer, oldData, newData) -> showDetails(newData));
        table.setEditable(true);
        colPret.setCellFactory(TextFieldTableCell.forTableColumn(new IntegerStringConverter()));
        colCantitate.setCellFactory(TextFieldTableCell.forTableColumn(new IntegerStringConverter()));

    }

    private void showDetails(Produs t) {if(t!=null){
        lblNume.setText(t.getDenumire());
        lblCant.setText(String.valueOf(t.getCantitate()));
        lblPret.setText(String.valueOf(t.getPret()));
    }

    }

    public void clickAdd(ActionEvent event) {
        try {
            service.saveProduct(new Produs(lblNume.getText(), Integer.parseInt(lblPret.getText()), Integer.parseInt(lblCant.getText())));
            observableList.add(new Produs(lblNume.getText(), Integer.parseInt(lblPret.getText()), Integer.parseInt(lblCant.getText())));
            table.setItems(observableList);
        }catch (ValidationException e){
            showAllert(e);
        }
    }
    public void clickDelete(ActionEvent event) {
        try {
            Produs p = new Produs(lblNume.getText(), Integer.parseInt(lblPret.getText()), Integer.parseInt(lblCant.getText()));
            service.deleteProduct(p);
            observableList.clear();
            observableList = FXCollections.observableList(StreamSupport.stream(service.getAllProducts().spliterator(), false).collect(Collectors.toList()));
            table.setItems(observableList);
        }catch (ValidationException e){
            showAllert(e);
        }
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        colNume.setCellValueFactory(new PropertyValueFactory<model.Produs,String>("denumire"));
        colPret.setCellValueFactory(new PropertyValueFactory<model.Produs,Integer>("pret"));
        colCantitate.setCellValueFactory(new PropertyValueFactory<model.Produs,Integer>("cantitate"));

    }

    public void onPretChange(TableColumn.CellEditEvent<Produs, ?> pretIntegerCellEditEvent) {

        try{
            Produs produs=table.getSelectionModel().getSelectedItem();
            produs.setPret((Integer) pretIntegerCellEditEvent.getNewValue());
            service.updateProdus(produs);}
        catch (NumberFormatException e){
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("EroareMare");
            alert.setHeaderText(null);
            alert.setContentText("Pretul trebuie sa fie un numar natural");
            DialogPane dialogPane = alert.getDialogPane();
            dialogPane.getStylesheets().add(getClass().getResource("/cssDesign/myDialogs.css").toExternalForm());
            dialogPane.getStyleClass().add("myDialog");
            dialogPane.setHeader(null);
            alert.show();
        }
    }

    public void onCantitateChange(TableColumn.CellEditEvent<Produs, Integer> pretIntegerCellEditEvent) {

        try{
            Produs produs=table.getSelectionModel().getSelectedItem();
            produs.setCantitate(pretIntegerCellEditEvent.getNewValue());
            service.updateProdus(produs);}
        catch (NumberFormatException e){
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("EroareMare");
            alert.setHeaderText(null);
            alert.setContentText("Cantitatea trebuie sa fie un numar natural");
            DialogPane dialogPane = alert.getDialogPane();
            dialogPane.getStylesheets().add(getClass().getResource("/cssDesign/myDialogs.css").toExternalForm());
            dialogPane.getStyleClass().add("myDialog");
            dialogPane.setHeader(null);
            alert.show();
        }
    }

private void showAllert(ValidationException e){
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle("Eroare");
        alert.setHeaderText(null);
        alert.setContentText(e.getMessage());
        DialogPane dialogPane = alert.getDialogPane();
 dialogPane.getStylesheets().add(getClass().getResource("/cssDesign/myDialogs.css").toExternalForm());
        dialogPane.getStyleClass().add("myDialog");
        dialogPane.setHeader(null);
        alert.show();
    }
}
</code>```

The exception:

```<code>Exception in thread "JavaFX Application Thread" java.lang.NumberFormatException: For input string: "a"
        at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
        at java.base/java.lang.Integer.parseInt(Integer.java:652)
        at java.base/java.lang.Integer.valueOf(Integer.java:983)
        at javafx.base/javafx.util.converter.IntegerStringConverter.fromString(IntegerStringConverter.java:49)
        at javafx.base/javafx.util.converter.IntegerStringConverter.fromString(IntegerStringConverter.java:35)
        at javafx.controls/javafx.scene.control.cell.CellUtils.lambda$createTextField$1(CellUtils.java:255)
        at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
        at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
        at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
        at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
        at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
        at javafx.base/javafx.event.Event.fireEvent(Event.java:198)
        at javafx.graphics/javafx.scene.Node.fireEvent(Node.java:8865)
        at javafx.controls/com.sun.javafx.scene.control.behavior.TextFieldBehavior.fire(TextFieldBehavior.java:184)
        at javafx.controls/com.sun.javafx.scene.control.behavior.TextInputControlBehavior.lambda$keyMapping$62(TextInputControlBehavior.java:330)
        at javafx.controls/com.sun.javafx.scene.control.inputmap.InputMap.handle(InputMap.java:274)
        at javafx.base/com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
        at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
        at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
        at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
        at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
        at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
        at javafx.base/javafx.event.Event.fireEvent(Event.java:198)
        at javafx.graphics/javafx.scene.Scene$KeyHandler.process(Scene.java:4083)
        at javafx.graphics/javafx.scene.Scene$KeyHandler.access$1600(Scene.java:4029)
        at javafx.graphics/javafx.scene.Scene.processKeyEvent(Scene.java:2146)
        at javafx.graphics/javafx.scene.Scene$ScenePeerListener.keyEvent(Scene.java:2620)
        at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$KeyEventNotification.run(GlassViewEventHandler.java:217)
        at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$KeyEventNotification.run(GlassViewEventHandler.java:149)
        at java.base/java.security.AccessController.doPrivileged(Native Method)
        at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleKeyEvent$1(GlassViewEventHandler.java:248)
        at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
        at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.handleKeyEvent(GlassViewEventHandler.java:247)
        at javafx.graphics/com.sun.glass.ui.View.handleKeyEvent(View.java:547)
        at javafx.graphics/com.sun.glass.ui.View.notifyKey(View.java:971)
        at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
        at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:175)
        at java.base/java.lang.Thread.run(Thread.java:844)
</code>```

答:
You can write a custom IntegerStringConverter in your ControllerAdmin class:

```<code>public static class CustomIntegerStringConverter extends IntegerStringConverter {
    private final IntegerStringConverter converter = new IntegerStringConverter();

    @Override
    public String toString(Integer object) {
        try {
            return converter.toString(object);
        } catch (NumberFormatException e) {
            showAlert(e);
        }
        return null;
    }

    @Override
    public Integer fromString(String string) {
        try {
            return converter.fromString(string);
        } catch (NumberFormatException e) {
            showAlert(e);
        }
        return -1;
    }
}
</code>```

Then you can use it the same way as IntegerStringConverter:

```<code>colPret.setCellFactory(TextFieldTableCell.forTableColumn(new CustomIntegerStringConverter()));
colCantitate.setCellFactory(TextFieldTableCell.forTableColumn(new CustomIntegerStringConverter()));
</code>```

And make showAlert() take an Exception as a parameter instead of ValidationException:

```<code>private void showAlert(Exception e){
    /* show an alret */
}
</code>```

Body:
My TableView is editable, so I can update the price and quantity directly from the table without pressing any button. My price and quantity are Integers so, how can I handle an exception when I enter a String value? I want my program to show a DialogPane with a message or something like that?

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.util.converter.IntegerStringConverter;
import model.Produs;
import service.Service;
import validator.ValidationException;

import javax.persistence.criteria.CriteriaBuilder;
import java.net.URL;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

public class ControllerAdmin implements Initializable  {

    @FXML
    private TableView<Produs> table;

    @FXML
    private TableColumn<Produs, String> colNume;

    @FXML
    private TableColumn<Produs, Integer> colPret;

    @FXML
    private TableColumn<Produs, Integer> colCantitate;

    @FXML
    private TextField lblNume;

    @FXML
    private TextField lblCant;

    @FXML
    private TextField lblPret;

    private ObservableList<Produs> observableList;

    private Service service;
    public ControllerAdmin(){}
    public void setService(Service service){
        this.service=service;
        observableList = FXCollections.observableList(StreamSupport.stream(service.getAllProducts().spliterator(), false).collect(Collectors.toList()));
        observableList.remove(new Produs("b",2,2));
        loadTables();
    }

    private void loadTables() {
        table.setItems(observableList);
        table.getSelectionModel().selectedItemProperty().addListener((observer, oldData, newData) -> showDetails(newData));
        table.setEditable(true);
        colPret.setCellFactory(TextFieldTableCell.forTableColumn(new IntegerStringConverter()));
        colCantitate.setCellFactory(TextFieldTableCell.forTableColumn(new IntegerStringConverter()));

    }

    private void showDetails(Produs t) {if(t!=null){
        lblNume.setText(t.getDenumire());
        lblCant.setText(String.valueOf(t.getCantitate()));
        lblPret.setText(String.valueOf(t.getPret()));
    }

    }

    public void clickAdd(ActionEvent event) {
        try {
            service.saveProduct(new Produs(lblNume.getText(), Integer.parseInt(lblPret.getText()), Integer.parseInt(lblCant.getText())));
            observableList.add(new Produs(lblNume.getText(), Integer.parseInt(lblPret.getText()), Integer.parseInt(lblCant.getText())));
            table.setItems(observableList);
        }catch (ValidationException e){
            showAllert(e);
        }
    }
    public void clickDelete(ActionEvent event) {
        try {
            Produs p = new Produs(lblNume.getText(), Integer.parseInt(lblPret.getText()), Integer.parseInt(lblCant.getText()));
            service.deleteProduct(p);
            observableList.clear();
            observableList = FXCollections.observableList(StreamSupport.stream(service.getAllProducts().spliterator(), false).collect(Collectors.toList()));
            table.setItems(observableList);
        }catch (ValidationException e){
            showAllert(e);
        }
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        colNume.setCellValueFactory(new PropertyValueFactory<model.Produs,String>("denumire"));
        colPret.setCellValueFactory(new PropertyValueFactory<model.Produs,Integer>("pret"));
        colCantitate.setCellValueFactory(new PropertyValueFactory<model.Produs,Integer>("cantitate"));

    }

    public void onPretChange(TableColumn.CellEditEvent<Produs, ?> pretIntegerCellEditEvent) {

        try{
            Produs produs=table.getSelectionModel().getSelectedItem();
            produs.setPret((Integer) pretIntegerCellEditEvent.getNewValue());
            service.updateProdus(produs);}
        catch (NumberFormatException e){
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("EroareMare");
            alert.setHeaderText(null);
            alert.setContentText("Pretul trebuie sa fie un numar natural");
            DialogPane dialogPane = alert.getDialogPane();
            dialogPane.getStylesheets().add(getClass().getResource("/cssDesign/myDialogs.css").toExternalForm());
            dialogPane.getStyleClass().add("myDialog");
            dialogPane.setHeader(null);
            alert.show();
        }
    }

    public void onCantitateChange(TableColumn.CellEditEvent<Produs, Integer> pretIntegerCellEditEvent) {

        try{
            Produs produs=table.getSelectionModel().getSelectedItem();
            produs.setCantitate(pretIntegerCellEditEvent.getNewValue());
            service.updateProdus(produs);}
        catch (NumberFormatException e){
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("EroareMare");
            alert.setHeaderText(null);
            alert.setContentText("Cantitatea trebuie sa fie un numar natural");
            DialogPane dialogPane = alert.getDialogPane();
            dialogPane.getStylesheets().add(getClass().getResource("/cssDesign/myDialogs.css").toExternalForm());
            dialogPane.getStyleClass().add("myDialog");
            dialogPane.setHeader(null);
            alert.show();
        }
    }

private void showAllert(ValidationException e){
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle("Eroare");
        alert.setHeaderText(null);
        alert.setContentText(e.getMessage());
        DialogPane dialogPane = alert.getDialogPane();
 dialogPane.getStylesheets().add(getClass().getResource("/cssDesign/myDialogs.css").toExternalForm());
        dialogPane.getStyleClass().add("myDialog");
        dialogPane.setHeader(null);
        alert.show();
    }
}

The exception:

Exception in thread "JavaFX Application Thread" java.lang.NumberFormatException: For input string: "a"
        at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
        at java.base/java.lang.Integer.parseInt(Integer.java:652)
        at java.base/java.lang.Integer.valueOf(Integer.java:983)
        at javafx.base/javafx.util.converter.IntegerStringConverter.fromString(IntegerStringConverter.java:49)
        at javafx.base/javafx.util.converter.IntegerStringConverter.fromString(IntegerStringConverter.java:35)
        at javafx.controls/javafx.scene.control.cell.CellUtils.lambda$createTextField$1(CellUtils.java:255)
        at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
        at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
        at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
        at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
        at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
        at javafx.base/javafx.event.Event.fireEvent(Event.java:198)
        at javafx.graphics/javafx.scene.Node.fireEvent(Node.java:8865)
        at javafx.controls/com.sun.javafx.scene.control.behavior.TextFieldBehavior.fire(TextFieldBehavior.java:184)
        at javafx.controls/com.sun.javafx.scene.control.behavior.TextInputControlBehavior.lambda$keyMapping$62(TextInputControlBehavior.java:330)
        at javafx.controls/com.sun.javafx.scene.control.inputmap.InputMap.handle(InputMap.java:274)
        at javafx.base/com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
        at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
        at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
        at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
        at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
        at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
        at javafx.base/javafx.event.Event.fireEvent(Event.java:198)
        at javafx.graphics/javafx.scene.Scene$KeyHandler.process(Scene.java:4083)
        at javafx.graphics/javafx.scene.Scene$KeyHandler.access$1600(Scene.java:4029)
        at javafx.graphics/javafx.scene.Scene.processKeyEvent(Scene.java:2146)
        at javafx.graphics/javafx.scene.Scene$ScenePeerListener.keyEvent(Scene.java:2620)
        at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$KeyEventNotification.run(GlassViewEventHandler.java:217)
        at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$KeyEventNotification.run(GlassViewEventHandler.java:149)
        at java.base/java.security.AccessController.doPrivileged(Native Method)
        at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleKeyEvent$1(GlassViewEventHandler.java:248)
        at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
        at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.handleKeyEvent(GlassViewEventHandler.java:247)
        at javafx.graphics/com.sun.glass.ui.View.handleKeyEvent(View.java:547)
        at javafx.graphics/com.sun.glass.ui.View.notifyKey(View.java:971)
        at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
        at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:175)
        at java.base/java.lang.Thread.run(Thread.java:844)

Body:
You can write a custom IntegerStringConverter in your ControllerAdmin class:

public static class CustomIntegerStringConverter extends IntegerStringConverter {
    private final IntegerStringConverter converter = new IntegerStringConverter();

    @Override
    public String toString(Integer object) {
        try {
            return converter.toString(object);
        } catch (NumberFormatException e) {
            showAlert(e);
        }
        return null;
    }

    @Override
    public Integer fromString(String string) {
        try {
            return converter.fromString(string);
        } catch (NumberFormatException e) {
            showAlert(e);
        }
        return -1;
    }
}

Then you can use it the same way as IntegerStringConverter:

colPret.setCellFactory(TextFieldTableCell.forTableColumn(new CustomIntegerStringConverter()));
colCantitate.setCellFactory(TextFieldTableCell.forTableColumn(new CustomIntegerStringConverter()));

And make showAlert() take an Exception as a parameter instead of ValidationException:

private void showAlert(Exception e){
    /* show an alret */
}


问:
spark-structured steaming not displaying any data in "format("memory")
When i do below it is working fine

```<code>company_info_df.select(col("value"))
             .writeStream()
              .outputMode("append")
              .option("truncate", false)
              .format("console")
              .trigger(Trigger.ProcessingTime("4 seconds"))
              .start();
</code>```

But when I do as below i.e. ".format("memory") , it is not showing anything

```<code>company_info_df.select(col("value"))
             .writeStream()
              .outputMode("append")
              .option("truncate", false)
              .format("memory")
              .queryName("company_info")
              .option("checkpointLocation", checkpointDir + "\\console")
              .trigger(Trigger.ProcessingTime("4 seconds"))
              .start();

        Dataset<Row> company_inf = sparkSession.sql("select * from company_info");

        company_inf.show();
</code>```

What am I doing wrong here ?
what is the correct way for the same?

答:
Refer to the below code in spark-shell that works for a sample data:

```<code>import org.apache.spark.sql.functions._
import org.apache.spark.sql.SparkSession
val spark = SparkSession.builder.appName("StructuredNetworkWordCount").getOrCreate()
import spark.implicits._
import org.apache.spark.sql.types.{StructType, StructField, StringType, IntegerType};

val userSchema = new StructType().add("col1", "string").add("col2", "string").add("col3", "string").add("col4", "string").add("col5", "string").add("col6", "integer")
val csvDF = spark.readStream.option("sep", ",").schema(userSchema).csv("/user/Temp") //reads the stream as source files in a folder.
csvDF.createOrReplaceTempView("abcd");
val dbDf2 = spark.sql("select col2, sum(col6) from abcd group by col2");
dbDf2.writeStream.queryName("abcdquery").outputMode("complete").format("memory").start()
</code>```

In your code, try removing some of the options during write operation and see what is going wrong.

Body:
When i do below it is working fine

company_info_df.select(col("value"))
             .writeStream()
              .outputMode("append")
              .option("truncate", false)
              .format("console")
              .trigger(Trigger.ProcessingTime("4 seconds"))
              .start();

But when I do as below i.e. ".format("memory") , it is not showing anything

company_info_df.select(col("value"))
             .writeStream()
              .outputMode("append")
              .option("truncate", false)
              .format("memory")
              .queryName("company_info")
              .option("checkpointLocation", checkpointDir + "\\console")
              .trigger(Trigger.ProcessingTime("4 seconds"))
              .start();

        Dataset<Row> company_inf = sparkSession.sql("select * from company_info");

        company_inf.show();

What am I doing wrong here ?
what is the correct way for the same?

Body:
Refer to the below code in spark-shell that works for a sample data:

import org.apache.spark.sql.functions._
import org.apache.spark.sql.SparkSession
val spark = SparkSession.builder.appName("StructuredNetworkWordCount").getOrCreate()
import spark.implicits._
import org.apache.spark.sql.types.{StructType, StructField, StringType, IntegerType};

val userSchema = new StructType().add("col1", "string").add("col2", "string").add("col3", "string").add("col4", "string").add("col5", "string").add("col6", "integer")
val csvDF = spark.readStream.option("sep", ",").schema(userSchema).csv("/user/Temp") //reads the stream as source files in a folder.
csvDF.createOrReplaceTempView("abcd");
val dbDf2 = spark.sql("select col2, sum(col6) from abcd group by col2");
dbDf2.writeStream.queryName("abcdquery").outputMode("complete").format("memory").start()

In your code, try removing some of the options during write operation and see what is going wrong.


问:
firebaseAuth.logout workf for menu activity but not for profile activity
I may entangled myself in this but I can't seem to see any reason why this doesn't work.

In the MenuActivity the menu items and their functionalities work fine. Log out works perfectly. When I extent the MenuActivity to the ProfileActivity, for some reason the log out button doesn't work the same, the app crashes and displays the message "My application has stopped xClose the application".

Here are all the classes:

MenuActivity.java:

package com.example.myapplication;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

import com.google.firebase.auth.FirebaseAuth;

public class MenuActivity extends AppCompatActivity {

    private FirebaseAuth firebaseAuth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu);

        firebaseAuth = FirebaseAuth.getInstance();
    }

    private void Logout(){
        firebaseAuth.signOut();
        finish();
        startActivity(new Intent(MenuActivity.this, MainActivity.class));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflate = getMenuInflater();
        inflate.inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch(item.getItemId()){
            case R.id.logoutMenu:{
                Logout();
                return true;
            }
            case R.id.profileMenu:
                startActivity(new Intent(MenuActivity.this, ProfileActivity.class));
        }
        return super.onOptionsItemSelected(item);
    }

}
```

<p>ProfileActivity.java</p>

<pre class="lang-java prettyprint-override"><code>package com.example.myapplication;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

public class ProfileActivity extends MenuActivity {

    private TextView userName, userEmail, phoneNumber;
    private Button editProfile, btnChangePassword;
    private FirebaseAuth firebaseAuth;
    private FirebaseDatabase firebaseDatabase;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);
        userName = findViewById(R.id.tvName3);
        userEmail = findViewById(R.id.tvEmail3);
        phoneNumber = findViewById(R.id.tvPhone3);
        editProfile = findViewById(R.id.btnEditProfile);
        btnChangePassword = findViewById(R.id.btnChangePassword);

        firebaseAuth = FirebaseAuth.getInstance();
        firebaseDatabase = FirebaseDatabase.getInstance();

        final DatabaseReference databaseReference = firebaseDatabase.getReference(firebaseAuth.getUid());

        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                UserProfile userProfile = dataSnapshot.getValue(UserProfile.class);
                userName.setText("Name: " + userProfile.getUserName());
                userEmail.setText("Email: " + userProfile.getUserEmail());
                phoneNumber.setText("Phone: " + userProfile.getUserPhone());
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(ProfileActivity.this, databaseError.getCode(), Toast.LENGTH_SHORT);
            }
        });

        editProfile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(ProfileActivity.this, UpdateProfile.class));
            }
        });
        btnChangePassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(ProfileActivity.this, ChangePassword.class));
            }
        });
    }
}

</code>```

and the menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    android:id="@+id/main_menu" >
    <item
        android:id="@+id/logoutMenu"
        android:orderInCategory="100"
        app:showAsAction="always"
        android:title="Logout">
    </item>

    <item
        android:id="@+id/profileMenu"
        android:orderInCategory="200"
        app:showAsAction="never"
        android:title="Profile">
    </item>

    <item
        android:id="@+id/refreshMenu"
        android:orderInCategory="300"
        app:showAsAction="never"
        android:title="Refresh">
    </item>
</menu>
```

<p>Here are the logcat messages</p>

<pre class="lang-java prettyprint-override"><code>2019-05-31 09:15:56.742 20660-20660/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication, PID: 20660
    android.content.res.Resources$NotFoundException: String resource ID #0xfffffffd
        at android.content.res.Resources.getText(Resources.java:338)
        at android.widget.Toast.makeText(Toast.java:304)
        at com.example.myapplication.ProfileActivity$1.onCancelled(ProfileActivity.java:58)
        at com.google.firebase.database.core.ValueEventRegistration.fireCancelEvent(com.google.firebase:firebase-database@@17.0.0:80)
        at com.google.firebase.database.core.view.CancelEvent.fire(com.google.firebase:firebase-database@@17.0.0:40)
        at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@17.0.0:55)
        at android.os.Handler.handleCallback(Handler.java:789)
        at android.os.Handler.dispatchMessage(Handler.java:98)
        at android.os.Looper.loop(Looper.java:169)
        at android.app.ActivityThread.main(ActivityThread.java:6585)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
</code>```

Is there something I did wrong in the ProfileActivity that interferes with the menu?

答:
According to me, I think you should add a check if there is a current user already logged in or not if the user is not logged in it will throw a null pointer exception.
Add a check like this</p>

```<code>if(FirebaseAuth.getCurrentUser()!=null){
   //Your sign out code
      }
</code>```

Body:
I may entangled myself in this but I can't seem to see any reason why this doesn't work.

In the MenuActivity the menu items and their functionalities work fine. Log out works perfectly. When I extent the MenuActivity to the ProfileActivity, for some reason the log out button doesn't work the same, the app crashes and displays the message "My application has stopped xClose the application".

Here are all the classes:

MenuActivity.java:

package com.example.myapplication;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

import com.google.firebase.auth.FirebaseAuth;

public class MenuActivity extends AppCompatActivity {

    private FirebaseAuth firebaseAuth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu);

        firebaseAuth = FirebaseAuth.getInstance();
    }

    private void Logout(){
        firebaseAuth.signOut();
        finish();
        startActivity(new Intent(MenuActivity.this, MainActivity.class));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflate = getMenuInflater();
        inflate.inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch(item.getItemId()){
            case R.id.logoutMenu:{
                Logout();
                return true;
            }
            case R.id.profileMenu:
                startActivity(new Intent(MenuActivity.this, ProfileActivity.class));
        }
        return super.onOptionsItemSelected(item);
    }

}

ProfileActivity.java

package com.example.myapplication;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

public class ProfileActivity extends MenuActivity {

    private TextView userName, userEmail, phoneNumber;
    private Button editProfile, btnChangePassword;
    private FirebaseAuth firebaseAuth;
    private FirebaseDatabase firebaseDatabase;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);
        userName = findViewById(R.id.tvName3);
        userEmail = findViewById(R.id.tvEmail3);
        phoneNumber = findViewById(R.id.tvPhone3);
        editProfile = findViewById(R.id.btnEditProfile);
        btnChangePassword = findViewById(R.id.btnChangePassword);

        firebaseAuth = FirebaseAuth.getInstance();
        firebaseDatabase = FirebaseDatabase.getInstance();

        final DatabaseReference databaseReference = firebaseDatabase.getReference(firebaseAuth.getUid());

        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                UserProfile userProfile = dataSnapshot.getValue(UserProfile.class);
                userName.setText("Name: " + userProfile.getUserName());
                userEmail.setText("Email: " + userProfile.getUserEmail());
                phoneNumber.setText("Phone: " + userProfile.getUserPhone());
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(ProfileActivity.this, databaseError.getCode(), Toast.LENGTH_SHORT);
            }
        });

        editProfile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(ProfileActivity.this, UpdateProfile.class));
            }
        });
        btnChangePassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(ProfileActivity.this, ChangePassword.class));
            }
        });
    }
}

and the menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    android:id="@+id/main_menu" >
    <item
        android:id="@+id/logoutMenu"
        android:orderInCategory="100"
        app:showAsAction="always"
        android:title="Logout">
    </item>

    <item
        android:id="@+id/profileMenu"
        android:orderInCategory="200"
        app:showAsAction="never"
        android:title="Profile">
    </item>

    <item
        android:id="@+id/refreshMenu"
        android:orderInCategory="300"
        app:showAsAction="never"
        android:title="Refresh">
    </item>
</menu>

Here are the logcat messages

2019-05-31 09:15:56.742 20660-20660/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication, PID: 20660
    android.content.res.Resources$NotFoundException: String resource ID #0xfffffffd
        at android.content.res.Resources.getText(Resources.java:338)
        at android.widget.Toast.makeText(Toast.java:304)
        at com.example.myapplication.ProfileActivity$1.onCancelled(ProfileActivity.java:58)
        at com.google.firebase.database.core.ValueEventRegistration.fireCancelEvent(com.google.firebase:firebase-database@@17.0.0:80)
        at com.google.firebase.database.core.view.CancelEvent.fire(com.google.firebase:firebase-database@@17.0.0:40)
        at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@17.0.0:55)
        at android.os.Handler.handleCallback(Handler.java:789)
        at android.os.Handler.dispatchMessage(Handler.java:98)
        at android.os.Looper.loop(Looper.java:169)
        at android.app.ActivityThread.main(ActivityThread.java:6585)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

Is there something I did wrong in the ProfileActivity that interferes with the menu?

Body:
According to me, I think you should add a check if there is a current user already logged in or not if the user is not logged in it will throw a null pointer exception.
Add a check like this

if(FirebaseAuth.getCurrentUser()!=null){
   //Your sign out code
      }


问:
pyspark.sql module error: Python in worker has different version 2.7 than that in driver 3.7, PySpark cannot run with different minor versions

df = spark.read.parquet('xxx')
tmstmp = df['timestamp']

spark.conf.set("spark.sql.session.timeZone", "Singapore")

time_df = spark.createDataFrame([('tmstmp',)], ['unix_time'])
time_df.select(from_unixtime('unix_time').alias('ts')).collect()

df['timestamp'] = time_df

spark.conf.unset("spark.sql.session.timeZone")
```

<p>there is an error at this line:</p>

```time_df.select(from_unixtime('unix_time').alias('ts')).collect()
```

with the exception error msg:

Exception: Python in worker has different version 2.7 than that in driver 3.7, PySpark cannot run with different minor versions.Please check environment variables PYSPARK_PYTHON and PYSPARK_DRIVER_PYTHON are correctly set.

答:
The exception that you are receiving is pretty clear in itself.
You have a cluster with two or more nodes. The server/node from where you submitted this command(master) has different version of python than your other nodes(worker).

Possible solution:

Bump up your worker nodes python version or set PYSPARK_PYTHON env to python3.7 installation.

change your  driver python version to match worker nodes version.

Body:
df = spark.read.parquet('xxx')
tmstmp = df['timestamp']

spark.conf.set("spark.sql.session.timeZone", "Singapore")

time_df = spark.createDataFrame([('tmstmp',)], ['unix_time'])
time_df.select(from_unixtime('unix_time').alias('ts')).collect()

df['timestamp'] = time_df

spark.conf.unset("spark.sql.session.timeZone")

there is an error at this line:

time_df.select(from_unixtime('unix_time').alias('ts')).collect()

with the exception error msg:

Exception: Python in worker has different version 2.7 than that in driver 3.7, PySpark cannot run with different minor versions.Please check environment variables PYSPARK_PYTHON and PYSPARK_DRIVER_PYTHON are correctly set.


问:
Merge two multidimensional arrays in PHP
Supposing I've this array:

```<code>Array
(
    [country] => Array
        (
            [0] => France
            [1] => Canada
        )
    [capital] => Array
        (
            [0] => Paris
            [1] => Ottawa
        )
    [other] => value
)
</code>```

Is it possible to merge the country and capital arrays ?

The desired output is the following:

```<code>Array
(
    [countries] => Array
        (
            Array
                (
                    [country] => France
                    [capital] => Paris
            )
            Array
                (
                    [country] => Canada
                    [capital] => Ottawa
            )
        )
    [other] => value
)
</code>```

What I tried:

```<code>$result = array();

foreach($arr as $key=>$array) {
    $result[$key] = array_merge($array, $arr2[$key]);
}
</code>```

答:
If countries -> capitals keys and length are the same and you need only those values to be combined you can simply increment through one of arrays. For example:

$result = ['countries' => [], 'other' => $arr['other']];
for ($i = 0; $i < count($arr['country']); $i++) {
    $result['countries'][] = [
        'country' => $arr['country'][$i],
        'capital' => $arr['capital'][$i]
    ];
}
```

Body:
Supposing I've this array:

Array
(
    [country] => Array
        (
            [0] => France
            [1] => Canada
        )
    [capital] => Array
        (
            [0] => Paris
            [1] => Ottawa
        )
    [other] => value
)

Is it possible to merge the country and capital arrays ?

The desired output is the following:

Array
(
    [countries] => Array
        (
            Array
                (
                    [country] => France
                    [capital] => Paris
            )
            Array
                (
                    [country] => Canada
                    [capital] => Ottawa
            )
        )
    [other] => value
)

What I tried:

$result = array();

foreach($arr as $key=>$array) {
    $result[$key] = array_merge($array, $arr2[$key]);
}


问:
Spark avoid creating _temporary directory in S3
I need to upload a dataframe to S3 bucket but I do not have delete permissions on the bucket. Is there any way I can avoid creating this _temporary directory on S3? Maybe any way in spark to use local FS for _temporary directory and then uploading final resulting file to S3 bucket or totally avoid _temporary directory.

Thanks in advance.

答:
Yes, you can avoid creating _temporary directory when uploading dataframe to s3.

When Spark appends data to an existing dataset, Spark uses FileOutputCommitter to manage staging output files and final output files.

By default, output committer algorithm uses version 1. In this version, FileOutputCommitter has two methods, commitTask and commitJob. commitTask moves data generated by a task from the task temporary directory to job temporary directory and when all tasks complete, commitJob moves data to from job temporary directory to the final destination.

However, when output committer algorithm uses version 2, commitTask moves data generated by a task directly to the final destination and commitJob is basically a no-op.

How do I set spark.hadoop.mapreduce.fileoutputcommitter.algorithm.version to 2?
You can set this config by using any of the following methods:

When you launch your cluster, you can put
spark.hadoop.mapreduce.fileoutputcommitter.algorithm.version 2 in the
Spark config.

spark.conf.set("mapreduce.fileoutputcommitter.algorithm.version",
"2")

When you write data using Dataset API, you can set it in
the option, i.e.
dataset.write.option("mapreduce.fileoutputcommitter.algorithm.version",
"2").

Read more about the output committer algorithm versions databricks-blog and mapred-default


问:
Angular 4: no component factory found,did you add it to @NgModule.entryComponents?
I'm using Angular 4 template with webpack
and I have this error when I try to use a component (ConfirmComponent):

No component factory found for ConfirmComponent.  Did you add it to
  @NgModule.entryComponents?

The component is declared in app.module.server.ts

@NgModule({
  bootstrap: [ AppComponent ],
  imports: [
    // ...
  ],
  entryComponents: [
    ConfirmComponent,
  ],
})
export class AppModule { }
```

I have also  app.module.browser.ts and app.module.shared.ts

How can I fix that?

答: For clarification here. In case you are not using ComponentFactoryResolver directly in component, and you want to abstract it to service, which is then injected into component you have to load it under providers for that module, since if lazy loaded it won't work.

Body:
I'm using Angular 4 template with webpack
and I have this error when I try to use a component (ConfirmComponent):

No component factory found for ConfirmComponent.  Did you add it to
  @NgModule.entryComponents?

The component is declared in app.module.server.ts

@NgModule({
  bootstrap: [ AppComponent ],
  imports: [
    // ...
  ],
  entryComponents: [
    ConfirmComponent,
  ],
})
export class AppModule { }

I have also  app.module.browser.ts and app.module.shared.ts

How can I fix that?


答:
If you have known field to modify use:

```<code>$arr = ["country" => ["France", "Canada"], "capital" => ["Paris", "Ottawa"], "other" => "value"];
$keys = ["country", "capital"];

foreach($arr as $k => $v) {
    if (in_array($k, $keys)) {
        $slice[] = $v; // get the array which need to be merge
        unset($arr[$k]); // remove him from the original array
    }
}

$arr["countries"] = array_map(function ($e) use ($keys) {return array_combine($keys, $e);}, array_map(null, ...$slice));
</code>```

And now $arr is set.

Notice the use of ... operator to explode the $slice array and the array_map with null which combine according to int keys.

This is the most generic way because if you want to change the field to merge you only need to do so in 1 place...

Title: Merge two multidimensional arrays in PHP

Body:
If you have known field to modify use:

$arr = ["country" => ["France", "Canada"], "capital" => ["Paris", "Ottawa"], "other" => "value"];
$keys = ["country", "capital"];

foreach($arr as $k => $v) {
    if (in_array($k, $keys)) {
        $slice[] = $v; // get the array which need to be merge
        unset($arr[$k]); // remove him from the original array
    }
}

$arr["countries"] = array_map(function ($e) use ($keys) {return array_combine($keys, $e);}, array_map(null, ...$slice));

And now $arr is set.

Notice the use of ... operator to explode the $slice array and the array_map with null which combine according to int keys.

This is the most generic way because if you want to change the field to merge you only need to do so in 1 place...


问:
Debugging Thorntail Services in Eclipse?
I've got several microservices projects that I'm developing using the Thorntail framework.  I'm writing my code using Eclipse.  In the past, I've done all of my development using the Wildfly app server, and Eclipse made debugging these apps dead simple.  Right Click->Debug As->Debug On Server.  Done.  Now that I'm using Thorntail, I'm not quite sure how to do it.

From the command line, I would start my Thorntail projects using:

```<code>mvn thorntail:run -Dthorntail.useUberJar # Project 1
mvn thorntail:run -Dthorntail.useUberJar -Dthorntail.port.offset=1000 # Project 2
</code>```

That gets everything up and running, and listening on ports 8080 and 9080.  However, the services are not in debug mode and I didn't launch these through Eclipse.

I know I can Right Click->Debug As->Maven Build... and then create a new debug configuration.  I've done so, with my goals corresponding to the mvn commands above.  However, when I do so no debugger is automatically attached, so breakpoints and such don't work.  I'm sure I'm missing a step somewhere, but this is functionality I haven't tried to use before so I'm lost.  Any recommendations?

答:
Execute the uberjar with the following parameters. Ensure that all the parameters are specified before the name of the uberjar on the line.

```<code>java -agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=$PORT_NUMBER -jar $UBERJAR_FILENAME
</code>```

$PORT_NUMBER is an unused port number of your choice. Remember this number for the remote debugger configuration.

$UBERJAR_FILENAME is the uberjar.

suspend=y ensures that JVM will pause and wait for remote debugger connection before it starts the application.

To remote debugging it using Eclipse IDE you have to open Eclipse, open source code of the targeted application and create a debug configuration ("Remote Java Application") by specifying the targeted host and port. After this, hit "Debug" button and proceed with the remote debugging.

Body:
I've got several microservices projects that I'm developing using the Thorntail framework.  I'm writing my code using Eclipse.  In the past, I've done all of my development using the Wildfly app server, and Eclipse made debugging these apps dead simple.  Right Click->Debug As->Debug On Server.  Done.  Now that I'm using Thorntail, I'm not quite sure how to do it.

From the command line, I would start my Thorntail projects using:

mvn thorntail:run -Dthorntail.useUberJar # Project 1
mvn thorntail:run -Dthorntail.useUberJar -Dthorntail.port.offset=1000 # Project 2

That gets everything up and running, and listening on ports 8080 and 9080.  However, the services are not in debug mode and I didn't launch these through Eclipse.

I know I can Right Click->Debug As->Maven Build... and then create a new debug configuration.  I've done so, with my goals corresponding to the mvn commands above.  However, when I do so no debugger is automatically attached, so breakpoints and such don't work.  I'm sure I'm missing a step somewhere, but this is functionality I haven't tried to use before so I'm lost.  Any recommendations?

Body:
Execute the uberjar with the following parameters. Ensure that all the parameters are specified before the name of the uberjar on the line.

java -agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=$PORT_NUMBER -jar $UBERJAR_FILENAME

$PORT_NUMBER is an unused port number of your choice. Remember this number for the remote debugger configuration.

$UBERJAR_FILENAME is the uberjar.

suspend=y ensures that JVM will pause and wait for remote debugger connection before it starts the application.

To remote debugging it using Eclipse IDE you have to open Eclipse, open source code of the targeted application and create a debug configuration ("Remote Java Application") by specifying the targeted host and port. After this, hit "Debug" button and proceed with the remote debugging.


问:
Windows 10 x64 does not recognize driver sign
I have rebuilt an opensource windwows driver. Than, I have signed it, but not myself, because in our company there is a web app for code signing. There is a digital signature in file, but windows 10 64 bit says that driver is unsigned. What may be wrong? Why can`t I use the driver without test mode ON?
File is here:
https://drive.google.com/open?id=1qYDieeAePgdIwbDhAHCQxOukHfkujZ0e</p>

答:
The signature must be from a trusted provider. You should add your certificate as a trusted root of the device.

Update. For kernel-mode drivers you must enable test signing mode.

https://learn.microsoft.com/en-us/windows-hardware/drivers/install/the-testsigning-boot-configuration-option


问:
How to display JavaScript function via HTML button
I want to display the smallest entered number using HTML button. HTML form gets 3 numbers from user and using JavaScript it displays the smallest number on button click.</p>

```<code><form id="3nr">
  <p><input type="number" placeholder="Numri i pare..."></p>
  <p><input type="number" placeholder="Numri i dyte..."></p>
  <p><input type="number" placeholder="Numri i trete..."></p>
  <p>Numri me i vogel = <output name="min"></output></p>

</form>

        <script type="text/javascript">
    const form = document.querySelector('form')
const inputs = form.querySelectorAll('input[type="number"]')
const out = document.querySelector('output')

form.addEventListener('input', e => {
  out.value = Math.min(...Array.prototype.map.call(inputs, input => input.value))
}, false)
        </script>
</code>```

答:
Just add a button to your form and attach an event-listener for the click event to it.

const action = document.getElementById('action');
const form = document.querySelector('form')
const inputs = form.querySelectorAll('input[type="number"]');
const out = document.querySelector('output');

action.addEventListener('click', e => {
  e.preventDefault(); // do not submit the form on click of our button
  out.value = Math.min(...Array.prototype.map.call(inputs, input => input.value))
}, false)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="3nr">
  <p><input type="number" placeholder="Numri i pare..."></p>
  <p><input type="number" placeholder="Numri i dyte..."></p>
  <p><input type="number" placeholder="Numri i trete..."></p>
  <p><button id="action">Display</button></p>
  <p>Numri me i vogel = <output name="min"></output></p>
</form></code>```

Body:
I want to display the smallest entered number using HTML button. HTML form gets 3 numbers from user and using JavaScript it displays the smallest number on button click.

<form id="3nr">

<input type="number" placeholder="Numri i pare...">

<input type="number" placeholder="Numri i dyte...">

<input type="number" placeholder="Numri i trete...">

Numri me i vogel = <output name="min"></output>

</form>

Body:
Just add a button to your form and attach an event-listener for the click event to it.

const action = document.getElementById('action');
const form = document.querySelector('form')
const inputs = form.querySelectorAll('input[type="number"]');
const out = document.querySelector('output');

action.addEventListener('click', e => {
  e.preventDefault(); // do not submit the form on click of our button
  out.value = Math.min(...Array.prototype.map.call(inputs, input => input.value))
}, false)

<form id="3nr">
  <p><input type="number" placeholder="Numri i pare..."></p>
  <p><input type="number" placeholder="Numri i dyte..."></p>
  <p><input type="number" placeholder="Numri i trete..."></p>
  <p><button id="action">Display</button></p>
  <p>Numri me i vogel = <output name="min"></output></p>
</form>


问:
Porting MS Access application
I have been asked by a friend to help him assess a number of quotes for porting a desktop application based on MS access and VBA to a web based app.  The application seems to have a relatively large amount of business logic coded into the VBA.

My question is very specific - are there any good tools or resources out there which could assist the porting from access, rather than doing a complete re-write?

The end technology used for the web app does not matter hugely, but would ideally be as mainstream as possible.

答:
Is there a reason why hosting the app on Windows Terminal Server would not suffice? This means zero changes to the app, no reprogramming cost and no danger of losing crucial business logic. If you use the Citrix extensions, you can run it in a web browser (though I guess that only works with IE -- I've never used them). But the RDP client comes in versions for Mac and Linux as well as Windows, so you can basically support anybody as long as they install the RDP client for their OS.

Yes, it's more installation on the client end, but it's a helluva lot cheaper and easier on the development and avoids the problem of losing important things coded into the Access app.

Of course, supporting large user populations on WTS/Citrix can get expensive and if the Access app is in need of re-engineering, anyway, it can change the balance. But it's something that you should consider. It's really easy to set up WTS, in fact, and provisioning a server for it basically a matter of adding RAM and Internet bandwidth (though RDP is really efficient to begin with).

One key mistake many people make when trying to run an Access app on WTS:

YOU MUST SPLIT THE DATABASE (front with forms/reports/etc., back end with data tables only), and each user must have their own copy of the front end (stored in user profile on the WTS, or in a folder on your WTS server's data partition with appropriate permissions assigned to the user groups authorized to use the app). Tony Toews's front-end updater is very useful in this context, and explicitly engineered to work in a Terminal Server environment.

OwnerDisplayName: Rob Y

ContentLicense: CC BY-SA 2.5

Title: Porting MS Access application

OwnerDisplayName: David W. Fenton


问:
sp_executesql parameter not recognized
I have a storedProcedure

```<code>CREATE PROCEDURE dbo.Employee_GetEmployeeByID
    @employeeID int
AS
    select EM.EmployeeID,EM.FullName, GM.Gender,EM.PhoneNumber
    from EmployeesMaster EM
    JOIN GenderMaster GM ON EM.GenderID = GM.GenderID
    where (EM.EmployeeID = @employeeID )
</code>```

I'm trying to execute (generated by ado.net code)

```<code>exec sp_executesql N'Employee_GetEmployeeByID',N'@employeeID int',@employeeID=7
</code>```

But, I'm getting an error like

```<code>Msg 201, Level 16, State 4, Procedure Employee_GetEmployeeByID, Line 0
Procedure or function 'Employee_GetEmployeeByID' expects parameter '@employeeID', which was not supplied.
</code>```

答:
Did you declare the variable first?

DECLARE @employeeID int = 7
exec sp_executesql N'Employee_GetEmployeeByID',N'@employeeID int',@employeeID

Title: sp_executesql parameter not recognized

Body:
I have a storedProcedure

CREATE PROCEDURE dbo.Employee_GetEmployeeByID
    @employeeID int
AS
    select EM.EmployeeID,EM.FullName, GM.Gender,EM.PhoneNumber
    from EmployeesMaster EM
    JOIN GenderMaster GM ON EM.GenderID = GM.GenderID
    where (EM.EmployeeID = @employeeID )

I'm trying to execute (generated by ado.net code)

exec sp_executesql N'Employee_GetEmployeeByID',N'@employeeID int',@employeeID=7

But, I'm getting an error like

Msg 201, Level 16, State 4, Procedure Employee_GetEmployeeByID, Line 0
Procedure or function 'Employee_GetEmployeeByID' expects parameter '@employeeID', which was not supplied.