问:
> Failed to apply plugin [id 'kotlin'] > For input string: ""
I am currently getting a strange error running a gradle-script on one computer (the same worked there already and still works on another computer) Looks like some cache problem - but deleting .gradle did not help and I do not know how to delete the other one
FAILURE: Build failed with an exception.

```<code>➜  kontinuum git:(ligi_wip2) ✗ ./gradlew clean run --stacktrace
Parallel execution is an incubating feature.

* Where:
Build file '/home/ligi/kontinuum/build.gradle' line: 15

* What went wrong:
A problem occurred evaluating root project 'kontinuum'.
> Failed to apply plugin [id 'kotlin']
   > For input string: ""

* Try:
Run with --info or --debug option to get more log output.

* Exception is:
org.gradle.api.GradleScriptException: A problem occurred evaluating root project 'kontinuum'.
        at org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.java:92)
        at org.gradle.configuration.DefaultScriptPluginFactory$ScriptPluginImpl$2.run(DefaultScriptPluginFactory.java:176)
        at org.gradle.configuration.ProjectScriptTarget.addConfiguration(ProjectScriptTarget.java:77)
        at org.gradle.configuration.DefaultScriptPluginFactory$ScriptPluginImpl.apply(DefaultScriptPluginFactory.java:181)
        at org.gradle.configuration.project.BuildScriptProcessor.execute(BuildScriptProcessor.java:39)
        at org.gradle.configuration.project.BuildScriptProcessor.execute(BuildScriptProcessor.java:26)
        at org.gradle.configuration.project.ConfigureActionsProjectEvaluator.evaluate(ConfigureActionsProjectEvaluator.java:34)
        at org.gradle.configuration.project.LifecycleProjectEvaluator.doConfigure(LifecycleProjectEvaluator.java:70)
        at org.gradle.configuration.project.LifecycleProjectEvaluator.access$000(LifecycleProjectEvaluator.java:33)
        at org.gradle.configuration.project.LifecycleProjectEvaluator$1.execute(LifecycleProjectEvaluator.java:53)
        at org.gradle.configuration.project.LifecycleProjectEvaluator$1.execute(LifecycleProjectEvaluator.java:50)
        at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:61)
        at org.gradle.configuration.project.LifecycleProjectEvaluator.evaluate(LifecycleProjectEvaluator.java:50)
        at org.gradle.api.internal.project.DefaultProject.evaluate(DefaultProject.java:599)
        at org.gradle.api.internal.project.DefaultProject.evaluate(DefaultProject.java:125)
        at org.gradle.execution.TaskPathProjectEvaluator.configure(TaskPathProjectEvaluator.java:35)
        at org.gradle.execution.TaskPathProjectEvaluator.configureHierarchy(TaskPathProjectEvaluator.java:60)
        at org.gradle.configuration.DefaultBuildConfigurer.configure(DefaultBuildConfigurer.java:38)
        at org.gradle.initialization.DefaultGradleLauncher$ConfigureBuildAction.execute(DefaultGradleLauncher.java:233)
        at org.gradle.initialization.DefaultGradleLauncher$ConfigureBuildAction.execute(DefaultGradleLauncher.java:230)
        at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:56)
        at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:160)
        at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:119)
        at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:102)
        at org.gradle.launcher.exec.GradleBuildController.run(GradleBuildController.java:71)
        at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
        at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:41)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:75)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:49)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:49)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:31)
        at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:47)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
        at org.gradle.util.Swapper.swap(Swapper.java:38)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:60)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:72)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
        at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:297)
        at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
        at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:46)
Caused by: org.gradle.api.internal.plugins.PluginApplicationException: Failed to apply plugin [id 'kotlin']
        at org.gradle.api.internal.plugins.DefaultPluginManager.doApply(DefaultPluginManager.java:155)
        at org.gradle.api.internal.plugins.DefaultPluginManager.apply(DefaultPluginManager.java:112)
        at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction.applyType(DefaultObjectConfigurationAction.java:113)
        at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction.access$200(DefaultObjectConfigurationAction.java:36)
        at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction$3.run(DefaultObjectConfigurationAction.java:80)
        at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction.execute(DefaultObjectConfigurationAction.java:136)
        at org.gradle.api.internal.project.AbstractPluginAware.apply(AbstractPluginAware.java:44)
        at org.gradle.api.internal.project.ProjectScript.apply(ProjectScript.java:34)
        at org.gradle.api.Script$apply$0.callCurrent(Unknown Source)
        at build_59bsa4g28e7wfd7hj9y0560h5.run(/home/ligi/kontinuum/build.gradle:15)
        at org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.java:90)
        ... 62 more
Caused by: java.lang.NumberFormatException: For input string: ""
        at org.jetbrains.kotlin.incremental.CacheVersion.getActualVersion(CacheVersion.kt:44)
        at org.jetbrains.kotlin.incremental.CacheVersion.checkVersion(CacheVersion.kt:57)
        at org.jetbrains.kotlin.incremental.BuildCacheStorage.<init>(BuildCacheStorage.kt:83)
        at org.jetbrains.kotlin.gradle.plugin.KotlinGradleBuildServices.<init>(KotlinGradleBuildServices.kt:68)
        at org.jetbrains.kotlin.gradle.plugin.KotlinGradleBuildServices.<init>(KotlinGradleBuildServices.kt:34)
        at org.jetbrains.kotlin.gradle.plugin.KotlinGradleBuildServices$Companion.getInstance(KotlinGradleBuildServices.kt:54)
        at org.jetbrains.kotlin.gradle.plugin.KotlinBasePluginWrapper.apply(KotlinPluginWrapper.kt:41)
        at org.jetbrains.kotlin.gradle.plugin.KotlinBasePluginWrapper.apply(KotlinPluginWrapper.kt:34)
        at org.gradle.api.internal.plugins.ImperativeOnlyPluginApplicator.applyImperative(ImperativeOnlyPluginApplicator.java:35)
        at org.gradle.api.internal.plugins.RuleBasedPluginApplicator.applyImperative(RuleBasedPluginApplicator.java:43)
        at org.gradle.api.internal.plugins.DefaultPluginManager.doApply(DefaultPluginManager.java:139)
        ... 72 more
</code>```

EDIT:
 * rm -rf .gradle did not help
 * executing it with another user works fine.

答: I had this problem, and found that deleting the build folder and then rerunning the build fixed it.

Body:
I am currently getting a strange error running a gradle-script on one computer (the same worked there already and still works on another computer) Looks like some cache problem - but deleting .gradle did not help and I do not know how to delete the other one
FAILURE: Build failed with an exception.

➜  kontinuum git:(ligi_wip2) ✗ ./gradlew clean run --stacktrace
Parallel execution is an incubating feature.

* Where:
Build file '/home/ligi/kontinuum/build.gradle' line: 15

* What went wrong:
A problem occurred evaluating root project 'kontinuum'.
> Failed to apply plugin [id 'kotlin']
   > For input string: ""

* Try:
Run with --info or --debug option to get more log output.

* Exception is:
org.gradle.api.GradleScriptException: A problem occurred evaluating root project 'kontinuum'.
        at org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.java:92)
        at org.gradle.configuration.DefaultScriptPluginFactory$ScriptPluginImpl$2.run(DefaultScriptPluginFactory.java:176)
        at org.gradle.configuration.ProjectScriptTarget.addConfiguration(ProjectScriptTarget.java:77)
        at org.gradle.configuration.DefaultScriptPluginFactory$ScriptPluginImpl.apply(DefaultScriptPluginFactory.java:181)
        at org.gradle.configuration.project.BuildScriptProcessor.execute(BuildScriptProcessor.java:39)
        at org.gradle.configuration.project.BuildScriptProcessor.execute(BuildScriptProcessor.java:26)
        at org.gradle.configuration.project.ConfigureActionsProjectEvaluator.evaluate(ConfigureActionsProjectEvaluator.java:34)
        at org.gradle.configuration.project.LifecycleProjectEvaluator.doConfigure(LifecycleProjectEvaluator.java:70)
        at org.gradle.configuration.project.LifecycleProjectEvaluator.access$000(LifecycleProjectEvaluator.java:33)
        at org.gradle.configuration.project.LifecycleProjectEvaluator$1.execute(LifecycleProjectEvaluator.java:53)
        at org.gradle.configuration.project.LifecycleProjectEvaluator$1.execute(LifecycleProjectEvaluator.java:50)
        at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:61)
        at org.gradle.configuration.project.LifecycleProjectEvaluator.evaluate(LifecycleProjectEvaluator.java:50)
        at org.gradle.api.internal.project.DefaultProject.evaluate(DefaultProject.java:599)
        at org.gradle.api.internal.project.DefaultProject.evaluate(DefaultProject.java:125)
        at org.gradle.execution.TaskPathProjectEvaluator.configure(TaskPathProjectEvaluator.java:35)
        at org.gradle.execution.TaskPathProjectEvaluator.configureHierarchy(TaskPathProjectEvaluator.java:60)
        at org.gradle.configuration.DefaultBuildConfigurer.configure(DefaultBuildConfigurer.java:38)
        at org.gradle.initialization.DefaultGradleLauncher$ConfigureBuildAction.execute(DefaultGradleLauncher.java:233)
        at org.gradle.initialization.DefaultGradleLauncher$ConfigureBuildAction.execute(DefaultGradleLauncher.java:230)
        at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:56)
        at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:160)
        at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:119)
        at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:102)
        at org.gradle.launcher.exec.GradleBuildController.run(GradleBuildController.java:71)
        at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
        at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:41)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:75)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:49)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:49)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:31)
        at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:47)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
        at org.gradle.util.Swapper.swap(Swapper.java:38)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:60)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:72)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
        at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:297)
        at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
        at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:46)
Caused by: org.gradle.api.internal.plugins.PluginApplicationException: Failed to apply plugin [id 'kotlin']
        at org.gradle.api.internal.plugins.DefaultPluginManager.doApply(DefaultPluginManager.java:155)
        at org.gradle.api.internal.plugins.DefaultPluginManager.apply(DefaultPluginManager.java:112)
        at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction.applyType(DefaultObjectConfigurationAction.java:113)
        at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction.access$200(DefaultObjectConfigurationAction.java:36)
        at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction$3.run(DefaultObjectConfigurationAction.java:80)
        at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction.execute(DefaultObjectConfigurationAction.java:136)
        at org.gradle.api.internal.project.AbstractPluginAware.apply(AbstractPluginAware.java:44)
        at org.gradle.api.internal.project.ProjectScript.apply(ProjectScript.java:34)
        at org.gradle.api.Script$apply$0.callCurrent(Unknown Source)
        at build_59bsa4g28e7wfd7hj9y0560h5.run(/home/ligi/kontinuum/build.gradle:15)
        at org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.java:90)
        ... 62 more
Caused by: java.lang.NumberFormatException: For input string: ""
        at org.jetbrains.kotlin.incremental.CacheVersion.getActualVersion(CacheVersion.kt:44)
        at org.jetbrains.kotlin.incremental.CacheVersion.checkVersion(CacheVersion.kt:57)
        at org.jetbrains.kotlin.incremental.BuildCacheStorage.<init>(BuildCacheStorage.kt:83)
        at org.jetbrains.kotlin.gradle.plugin.KotlinGradleBuildServices.<init>(KotlinGradleBuildServices.kt:68)
        at org.jetbrains.kotlin.gradle.plugin.KotlinGradleBuildServices.<init>(KotlinGradleBuildServices.kt:34)
        at org.jetbrains.kotlin.gradle.plugin.KotlinGradleBuildServices$Companion.getInstance(KotlinGradleBuildServices.kt:54)
        at org.jetbrains.kotlin.gradle.plugin.KotlinBasePluginWrapper.apply(KotlinPluginWrapper.kt:41)
        at org.jetbrains.kotlin.gradle.plugin.KotlinBasePluginWrapper.apply(KotlinPluginWrapper.kt:34)
        at org.gradle.api.internal.plugins.ImperativeOnlyPluginApplicator.applyImperative(ImperativeOnlyPluginApplicator.java:35)
        at org.gradle.api.internal.plugins.RuleBasedPluginApplicator.applyImperative(RuleBasedPluginApplicator.java:43)
        at org.gradle.api.internal.plugins.DefaultPluginManager.doApply(DefaultPluginManager.java:139)
        ... 72 more

EDIT:
 * rm -rf .gradle did not help
 * executing it with another user works fine.


来源: stackexchange

问:
Why can't I reference a character in a string that was previously cast to void?
To use pthreads, I used as input a char* that was cast to void* as input. If it's later cast to (char*) it can be printed and used normally ( (char*)var ). However, if one does (char*)var[i], where 'i' will help us reference a character, it doesn't. Why?

e.g. MS says 'expression must be a pointer to a complete object type'.

答:
Because of operator precedence: the cast comes after the subscript operator.

You have to write ((char*)var)[i];.

ContentLicense: CC BY-SA 2.5


问:
How to access an object defined in a function from another function?
I am building a simple GUI app to manage priorities. I'm stuck with accessing an object defined in a function from another function, in this instance accessing root in the function createWindow from display(). The window opens but there is no label, and this is what it gives me when I quit the program:

/usr/bin/python3.5 /home/cali/PycharmProjects/priorities/priorities.py
  Traceback (most recent call last):   File
  "/home/cali/PycharmProjects/priorities/priorities.py", line 34, in

      c.main()   File "/home/cali/PycharmProjects/priorities/priorities.py", line 31, in
  main
      g.display()   File "/home/cali/PycharmProjects/priorities/priorities.py", line 22, in
  display
      Label(root, NameError: name 'root' is not defined

Process finished with exit code 1

Here is what I have done so far:

```<code># priorities.py
#   GUI program to manage priorities

from tkinter import *

class Priority:
    pass

class GuiPart:

    def createWindow(self):

        root = Tk()
        root.resizable(width = False, height = False)
        root.title = "Priorities"
        root.mainloop()

        return root

    def display(self):

        Label(root,
              text = "testes").grid(row = 0, column = 1)

class Client:

    def main(self):

        g = GuiPart()
        g.createWindow()
        g.display()

c = Client()
c.main()
</code>```

I'm using Python 3.6.

答:
You want to use class attributes here, like this

```<code>class GuiPart:
    def createWindow(self):
        root = Tk()
        root.resizable(width=False, height=False)
        root.title = "Priorities"
        root.mainloop()

        self.root = root

        return root

    def display(self):
        Label(self.root,
              text="testes").grid(row=0, column=1)
</code>```

Note how the value of root gets assigned to self.root, and later read from self.root again. self can be used for storing object attributes on for the lifetime of an object.

ContentLicense: CC BY-SA 3.0

Body:
I am building a simple GUI app to manage priorities. I'm stuck with accessing an object defined in a function from another function, in this instance accessing root in the function createWindow from display(). The window opens but there is no label, and this is what it gives me when I quit the program:

/usr/bin/python3.5 /home/cali/PycharmProjects/priorities/priorities.py
  Traceback (most recent call last):   File
  "/home/cali/PycharmProjects/priorities/priorities.py", line 34, in

      c.main()   File "/home/cali/PycharmProjects/priorities/priorities.py", line 31, in
  main
      g.display()   File "/home/cali/PycharmProjects/priorities/priorities.py", line 22, in
  display
      Label(root, NameError: name 'root' is not defined

Process finished with exit code 1

Here is what I have done so far:

# priorities.py
#   GUI program to manage priorities

from tkinter import *

class Priority:
    pass

class GuiPart:

    def createWindow(self):

        root = Tk()
        root.resizable(width = False, height = False)
        root.title = "Priorities"
        root.mainloop()

        return root

    def display(self):

        Label(root,
              text = "testes").grid(row = 0, column = 1)

class Client:

    def main(self):

        g = GuiPart()
        g.createWindow()
        g.display()

c = Client()
c.main()

I'm using Python 3.6.

Body:
You want to use class attributes here, like this

class GuiPart:
    def createWindow(self):
        root = Tk()
        root.resizable(width=False, height=False)
        root.title = "Priorities"
        root.mainloop()

        self.root = root

        return root

    def display(self):
        Label(self.root,
              text="testes").grid(row=0, column=1)

Note how the value of root gets assigned to self.root, and later read from self.root again. self can be used for storing object attributes on for the lifetime of an object.


问:
SQL - retrieve maximum date from other related table
I have  table T1 with data:

```<code>ID GROUP
1  L1
2  L1
3  L2
4  L3
</code>```

I have table T2 with data:

```<code>ID  GROUP  DATE
1   L1     03.03.2017
1   L2     01.01.2017
2   L1     03.03.2017
2   L2     02.02.2017
2   L1     01.01.2017
3   L2     03.03.2017
3   L1     02.02.2017
4   L3     05.03.2017
4   L2     02.02.2017
4   L3     05.01.2017
4   L1     01.01.2017
</code>```

As result I want to get a full list from T1 (ID and current group value) but to have additional column which will be populated only if current GROUP from T1 is not L1 and in that column I want to have maximum DATE from T2 for that ID where GROUP is not L1 and it matches with GROUP value from T1.

So result of the SELECT (joined L1 and L2) should be:

```<code>ID GROUP DATE
1  L1    null
2  L1    null
3  L2    03.03.2017
4  L3    05.03.2017
</code>```

I tried with this sql but it throws error:

```<code>        select t1.id,t1.group,t21.date from t1
        left outer join t2
     AS T21 on t21.id=t1.id and t1.group=t21.group
     and T21.group not in ('L1')
        AND T21.DATE IN (SELECT MAX(T22.DATE)
     FROM t2 AS T22
WHERE T22.id=T21.id and T21.group=t22.group)
</code>```

答:
try something like this</p>

```<code>Select T1.*, T2.Date1 from
T1 left outer join
(select max(Date) as Date1
,[Group] as Group1 FROM T2
WHERE [Group]  !='L1'
group by [Group] ) T3
on t1.[GROUP] = T3.Group1
</code>```

Body:
I have  table T1 with data:

ID GROUP
1  L1
2  L1
3  L2
4  L3

I have table T2 with data:

ID  GROUP  DATE
1   L1     03.03.2017
1   L2     01.01.2017
2   L1     03.03.2017
2   L2     02.02.2017
2   L1     01.01.2017
3   L2     03.03.2017
3   L1     02.02.2017
4   L3     05.03.2017
4   L2     02.02.2017
4   L3     05.01.2017
4   L1     01.01.2017

As result I want to get a full list from T1 (ID and current group value) but to have additional column which will be populated only if current GROUP from T1 is not L1 and in that column I want to have maximum DATE from T2 for that ID where GROUP is not L1 and it matches with GROUP value from T1.

So result of the SELECT (joined L1 and L2) should be:

ID GROUP DATE
1  L1    null
2  L1    null
3  L2    03.03.2017
4  L3    05.03.2017

I tried with this sql but it throws error:

        select t1.id,t1.group,t21.date from t1
        left outer join t2
     AS T21 on t21.id=t1.id and t1.group=t21.group
     and T21.group not in ('L1')
        AND T21.DATE IN (SELECT MAX(T22.DATE)
     FROM t2 AS T22
WHERE T22.id=T21.id and T21.group=t22.group)

Body:
try something like this

Select T1.*, T2.Date1 from
T1 left outer join
(select max(Date) as Date1
,[Group] as Group1 FROM T2
WHERE [Group]  !='L1'
group by [Group] ) T3
on t1.[GROUP] = T3.Group1


问:
Custom partitioner in SPARK (pyspark)
I am trying to create a custom partitioner in a spark job using PySpark, say, I have of list of some integers [10,20,30,40,50,10,20,35]. Now I want a scenario where I have two partitions say p1 and p2. p1 contains all the list elements < 30 and p2 contains all the elements above 30.

```<code>elements = sc.parallelize([10,20,30,40,50,10,20,35]).map(lambda x : (float(x)/10,x)).partitionBy(2).glom().collect()
</code>```

The above code partitions the list according to the hash of the arbitrary key I am passing. Is there anyway of partitioning the list according to a particular scenario ? Like the value is less than x or anything like that ?

答:
First map your entries with key as themselves like ( (10,10), (20,20))  to get tupled key-value pair. Then use custom partitioner which will decide based on key value to which partition element  is going.

Try implement such class in python:

```<code>class ExactPartitioner[V](partitions: Int, elements: Int) extends Partitioner {
  def getPartition(key: Any): Int = {
    val k = key.asInstanceOf[Int]
    //0 and 1 are partition number
    return ( k < 30 )? 0 : 1
  }
}
</code>```

Title: Custom partitioner in SPARK (pyspark)

Body:
I am trying to create a custom partitioner in a spark job using PySpark, say, I have of list of some integers [10,20,30,40,50,10,20,35]. Now I want a scenario where I have two partitions say p1 and p2. p1 contains all the list elements < 30 and p2 contains all the elements above 30.

elements = sc.parallelize([10,20,30,40,50,10,20,35]).map(lambda x : (float(x)/10,x)).partitionBy(2).glom().collect()

The above code partitions the list according to the hash of the arbitrary key I am passing. Is there anyway of partitioning the list according to a particular scenario ? Like the value is less than x or anything like that ?

Body:
First map your entries with key as themselves like ( (10,10), (20,20))  to get tupled key-value pair. Then use custom partitioner which will decide based on key value to which partition element  is going.

Try implement such class in python:

class ExactPartitioner[V](partitions: Int, elements: Int) extends Partitioner {
  def getPartition(key: Any): Int = {
    val k = key.asInstanceOf[Int]
    //0 and 1 are partition number
    return ( k < 30 )? 0 : 1
  }
}


问:
Do I need to add async await if I am returning the return parameter of an async method?
If I have a class that inherits a base class, and both classes inherit this interface

```<code>public interface BaseClass
{
    Task<object> GetAsync();
}
</code>```

If the base class implements its method as:

```<code>public async Task<object> GetAsync()
{
    object o = async DoSomethingAsync();
    return o;
}
</code>```

And the class that inherits the base class overrides the method but calls the base class method still, does it matter if you put async await?
e.g?

```<code>// Option 1
public async Task<object> GetAsync()
{
    DoSomethingElse();
    return await base.GetAsync();
}

// Option 2
public Task<object> GetAsync()
{
    DoSomethingElse();
    return base.GetAsync();
}
</code>```

What is the difference between the two?  Is there any?

答: Calling base class method is no different than calling method from different class in this regard, you should still add 'await'. Without it your derived method will be executed synchronously.</p>

Body:
If I have a class that inherits a base class, and both classes inherit this interface

public interface BaseClass
{
    Task<object> GetAsync();
}

If the base class implements its method as:

public async Task<object> GetAsync()
{
    object o = async DoSomethingAsync();
    return o;
}

And the class that inherits the base class overrides the method but calls the base class method still, does it matter if you put async await?
e.g?

// Option 1
public async Task<object> GetAsync()
{
    DoSomethingElse();
    return await base.GetAsync();
}

// Option 2
public Task<object> GetAsync()
{
    DoSomethingElse();
    return base.GetAsync();
}

What is the difference between the two?  Is there any?


答:
Despite it appearing to be part of the signature, async is in fact an implementation detail of the method that it decorates1. There is no need to decorate a method with async just because it's overriding a method that is implemented using it.

Option 2 is fine.

There's a github issue relating to automatically re-writing Option 1 to be Option 2, but I'm not sure if/when that will arrive, since there are some arguments against it (notably in the face of exceptions)

1As further evidence that it's not part of the signature, you're not even allowed to use async when defining interface members.

Title: Do I need to add async await if I am returning the return parameter of an async method?


问:
Not receiving Push Notification in iOS after getting register the device in IBM MobileFirst Platform 8
I am implementing Push Notification in a Cordova App. On Android, Push Notification working fine. But on iPhone, I am not receiving notifications.

I am able to register the iPhone device successfully for push notifications and I am also getting all tags that I created via the MFP server. While sending notification for iOS, I do get the delivery success message taht is
"the notification message was accepted for delivery."

But I do not get any notification on the iPhone.

I am using
IBM MobileFirst Foundation 8.0.0-2016121916

Developer Kit version: 8.0.0.00-20161122-002317

Code :

```<code>function wlCommonInit(){

//initialize app for push notification
    MFPPush.initialize (
        function(successResponse) {
            alert("Push Notification Successfully intialized");
            MFPPush.registerNotificationsCallback(notificationReceived);
        },
        function(failureResponse) {
            alert("Failed to initialize");
        }
    );

    //Check device is Supported for push notification
    MFPPush.isPushSupported (
        function(successResponse) {
            alert("Device is Push Supported");
        },
        function(failureResponse) {
            alert("Failed to get push support status");
        }
    );

    //regiser app for push notification
    MFPPush.registerDevice( null,
        function(successResponse) {
                alert("Device Successfully registered");
        },
        function(failureResponse) {
            alert("Failed to register");
        }
    );

    var notificationReceived = function(message) {
        alert(JSON.stringify(message));
    };
}
</code>```

Server log

```<code>2017-03-30 10:27:26.864028 MyProject[585:100605] [DEBUG] [OCLogger] Analytics data successfully sent to server.
2017-03-30 10:27:26.874357 MyProject[585:100605] Response Content : {"createdTime":"2017-03-29T14:27:31Z","lastUpdatedTime":"2017-03-30T04:54:33Z","createdMode":"API","deviceId":"20D322D5-781B-4C2C-82CE-673648AAB6FD","userId":"anonymous","token":"8c6c071ee6095e0ef5888abf8b885984fc02860c8a837f58be8118df8c353227","platform":"A","href":"http://192.168.10.126:9080/imfpush/v1/apps/com.MyProject.mobile/devices/20D322D5-781B-4C2C-82CE-673648AAB6FD"}
2017-03-30 10:27:48.280985 MyProject[585:100651] [] nw_coretls_read_one_record tls_handshake_process: [-9802]
2017-03-30 10:27:49.021119 MyProject[585:100651] [] nw_coretls_read_one_record tls_handshake_process: [-9802]
2017-03-30 10:27:49.026982 MyProject[585:100657] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9802)
2017-03-30 10:28:21.129769 MyProject[585:100682] void SendDelegateMessage(NSInvocation *): delegate (webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame:) failed to return after waiting 10 seconds. main run loop mode: kCFRunLoopDefaultMode
2017-03-30 10:28:21.212950 MyProject[585:100605] Finished load of: file:///var/containers/Bundle/Application/03675139-9EBE-4F42-B07D-45C98D40A440/MyProject.app/www/index.html#/appTour
2017-03-30 10:28:32.822257 MyProject[585:100832] Inside sendRequest : WLRequestBuilder
2017-03-30 10:28:33.171541 MyProject[585:100605] Response Content : {"subscribed":[{"tagName":"promotional","userId":"anonymous","subscriptionId":"528","deviceId":"20D322D5-781B-4C2C-82CE-673648AAB6FD","href":"http://192.168.10.126:9080/imfpush/v1/apps/com.MyProject.mobile/subscriptions"},{"tagName":"transectional","userId":"anonymous","subscriptionId":"529","deviceId":"20D322D5-781B-4C2C-82CE-673648AAB6FD","href":"http://192.168.10.126:9080/imfpush/v1/apps/com.MyProject.mobile/subscriptions"},{"tagName":"yy","userId":"anonymous","subscriptionId":"530","deviceId":"20D322D5-781B-4C2C-82CE-673648AAB6FD","href":"http://192.168.10.126:9080/imfpush/v1/apps/com.MyProject.mobile/subscriptions"}],"subscriptionExists":[],"tagsNotFound":{"code":"FPWSE0001E","message":"Not Found - The target resource 'tagNames' does not exist. Check the 'tags' parameter.","tags":[]}}
2017-03-30 10:28:33.176354 MyProject[585:100605] [DEBUG] [OCLogger] The log file is empty. There are no persisted logs to send.
2017-03-30 10:28:33.183157 MyProject[585:100605] Inside sendRequest : WLRequestBuilder
2017-03-30 10:28:33.298817 MyProject[585:100605] Response Content :
2017-03-30 10:28:33.300344 MyProject[585:100605] [DEBUG] [OCLogger] Analytics data successfully sent to server.
2017-03-30 10:28:37.770125 MyProject[585:100605] WL.JSONStore success
</code>```

答:
From the logs, it is evident that your MFP server cannot communicate to APNS. Connection from MFP server to APNS is timing out.

Verify that your network rules or firewall is configured to allow outbound access from MFP server to APNS. Ensure all the required ports are open and allow inbound and outbound communication. While at it, make sure you allow access for APNS hostnames and not specifically whitelist IP's.

For more details on the ports and domains refer to this link.

Body:
I am implementing Push Notification in a Cordova App. On Android, Push Notification working fine. But on iPhone, I am not receiving notifications.

I am able to register the iPhone device successfully for push notifications and I am also getting all tags that I created via the MFP server. While sending notification for iOS, I do get the delivery success message taht is
"the notification message was accepted for delivery."

But I do not get any notification on the iPhone.

I am using
IBM MobileFirst Foundation 8.0.0-2016121916

Developer Kit version: 8.0.0.00-20161122-002317

Code :

function wlCommonInit(){

//initialize app for push notification
    MFPPush.initialize (
        function(successResponse) {
            alert("Push Notification Successfully intialized");
            MFPPush.registerNotificationsCallback(notificationReceived);
        },
        function(failureResponse) {
            alert("Failed to initialize");
        }
    );

    //Check device is Supported for push notification
    MFPPush.isPushSupported (
        function(successResponse) {
            alert("Device is Push Supported");
        },
        function(failureResponse) {
            alert("Failed to get push support status");
        }
    );

    //regiser app for push notification
    MFPPush.registerDevice( null,
        function(successResponse) {
                alert("Device Successfully registered");
        },
        function(failureResponse) {
            alert("Failed to register");
        }
    );

    var notificationReceived = function(message) {
        alert(JSON.stringify(message));
    };
}

Server log

2017-03-30 10:27:26.864028 MyProject[585:100605] [DEBUG] [OCLogger] Analytics data successfully sent to server.
2017-03-30 10:27:26.874357 MyProject[585:100605] Response Content : {"createdTime":"2017-03-29T14:27:31Z","lastUpdatedTime":"2017-03-30T04:54:33Z","createdMode":"API","deviceId":"20D322D5-781B-4C2C-82CE-673648AAB6FD","userId":"anonymous","token":"8c6c071ee6095e0ef5888abf8b885984fc02860c8a837f58be8118df8c353227","platform":"A","href":"http://192.168.10.126:9080/imfpush/v1/apps/com.MyProject.mobile/devices/20D322D5-781B-4C2C-82CE-673648AAB6FD"}
2017-03-30 10:27:48.280985 MyProject[585:100651] [] nw_coretls_read_one_record tls_handshake_process: [-9802]
2017-03-30 10:27:49.021119 MyProject[585:100651] [] nw_coretls_read_one_record tls_handshake_process: [-9802]
2017-03-30 10:27:49.026982 MyProject[585:100657] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9802)
2017-03-30 10:28:21.129769 MyProject[585:100682] void SendDelegateMessage(NSInvocation *): delegate (webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame:) failed to return after waiting 10 seconds. main run loop mode: kCFRunLoopDefaultMode
2017-03-30 10:28:21.212950 MyProject[585:100605] Finished load of: file:///var/containers/Bundle/Application/03675139-9EBE-4F42-B07D-45C98D40A440/MyProject.app/www/index.html#/appTour
2017-03-30 10:28:32.822257 MyProject[585:100832] Inside sendRequest : WLRequestBuilder
2017-03-30 10:28:33.171541 MyProject[585:100605] Response Content : {"subscribed":[{"tagName":"promotional","userId":"anonymous","subscriptionId":"528","deviceId":"20D322D5-781B-4C2C-82CE-673648AAB6FD","href":"http://192.168.10.126:9080/imfpush/v1/apps/com.MyProject.mobile/subscriptions"},{"tagName":"transectional","userId":"anonymous","subscriptionId":"529","deviceId":"20D322D5-781B-4C2C-82CE-673648AAB6FD","href":"http://192.168.10.126:9080/imfpush/v1/apps/com.MyProject.mobile/subscriptions"},{"tagName":"yy","userId":"anonymous","subscriptionId":"530","deviceId":"20D322D5-781B-4C2C-82CE-673648AAB6FD","href":"http://192.168.10.126:9080/imfpush/v1/apps/com.MyProject.mobile/subscriptions"}],"subscriptionExists":[],"tagsNotFound":{"code":"FPWSE0001E","message":"Not Found - The target resource 'tagNames' does not exist. Check the 'tags' parameter.","tags":[]}}
2017-03-30 10:28:33.176354 MyProject[585:100605] [DEBUG] [OCLogger] The log file is empty. There are no persisted logs to send.
2017-03-30 10:28:33.183157 MyProject[585:100605] Inside sendRequest : WLRequestBuilder
2017-03-30 10:28:33.298817 MyProject[585:100605] Response Content :
2017-03-30 10:28:33.300344 MyProject[585:100605] [DEBUG] [OCLogger] Analytics data successfully sent to server.
2017-03-30 10:28:37.770125 MyProject[585:100605] WL.JSONStore success


问:
Does order of dataLayer matter in Google Tag Manager?
If I create a tag which is triggered on 'page view' in GTM, can I push data to this tag after the tag has been fired?

This is the event type I'm using (page view)

```<code><script>
    window.dataLayer = window.dataLayer || []; //dataLayer object is instantiated
</script>

<script>
    var data = {page data, user data etc.}
    dataLayer.push(data);
</script>

<script>
    GoogleTagManager container code
</script>

// Will dataLayer.push(moreData) get caputured in the page view event?
</code>```

It's my understanding that using dataLayer.push will update the dataLayer on events, however as the pageview event fires on the pageview, it means only information in the dataLayer before the GTM container code is captured in this event.

Is this correct, or can I use dataLayer.push to update the pageview information?

答: You can always use another trigger, such as gtm.dom or gtm.load to read in any more info that you've pushed in to the dataLayer after the Pageview event has fired. But I always recommed that you push in an event along with any additional data and use that event to trigger your tag because you may not necessarily want to wait until the DOM has loaded or until the page has entirely loaded.

Body:
If I create a tag which is triggered on 'page view' in GTM, can I push data to this tag after the tag has been fired?

This is the event type I'm using (page view)

// Will dataLayer.push(moreData) get caputured in the page view event?

It's my understanding that using dataLayer.push will update the dataLayer on events, however as the pageview event fires on the pageview, it means only information in the dataLayer before the GTM container code is captured in this event.

Is this correct, or can I use dataLayer.push to update the pageview information?


问:
Restart Kubernetes pod when change happens on another
Two pods app and postgres are successfully created and are able to communicate through each other's services in a node. In the current process, the two pods get created at the same time, but that can be changed to have them be created/started in a sequence.

Initially, the database container in the postgres pod is empty and needs to be seeded. The seed process goes through the app pod and so, it needs to be up and running too. Once postgres is seeded, app still is not aware of this new data, and needs to be restarted. This is a flaw in app itself, that I have low control over.

Right now, the process is:

```<code>kubectl create -f pods.yaml       # creates `app` and `postgres` pods
kubectl exec app -- bash -c "<seed command>"
kubectl delete pod app
sleep 45                          # takes a while for `app` to terminate
kubectl create -f pods.yaml       # Ignore the "postgres pod and service already exist" error
</code>```

Is there a better way of automatically co-ordinating a restart of app once postgres reaches a seeded state?

Perhaps there is some aspect/feature set of Kubernetes that I'm missing entirely which helps with such a circumstance....

答:
If the app doesn't need to run during the seeding process and you can make the seeding process idempotent then init containers can help you.

The is a good example available.

Body:
Two pods app and postgres are successfully created and are able to communicate through each other's services in a node. In the current process, the two pods get created at the same time, but that can be changed to have them be created/started in a sequence.

Initially, the database container in the postgres pod is empty and needs to be seeded. The seed process goes through the app pod and so, it needs to be up and running too. Once postgres is seeded, app still is not aware of this new data, and needs to be restarted. This is a flaw in app itself, that I have low control over.

Right now, the process is:

kubectl create -f pods.yaml       # creates `app` and `postgres` pods
kubectl exec app -- bash -c "<seed command>"
kubectl delete pod app
sleep 45                          # takes a while for `app` to terminate
kubectl create -f pods.yaml       # Ignore the "postgres pod and service already exist" error

Is there a better way of automatically co-ordinating a restart of app once postgres reaches a seeded state?

Perhaps there is some aspect/feature set of Kubernetes that I'm missing entirely which helps with such a circumstance....


问:
How to distribute Beam Tasks evenly on Spark?
I have a simple pipeline that reads records both both a text file and mysql and tries to reconcile them, i.e. insert records when they don't exist in the DB, update records in the DB with the file, and do some other updates to records in the DB that do not exist in the file.

A problem that arises when run with 2M records in Spark is the following:

My hunch is that the following code is producing that imbalance

```<code>        final TupleTag<FileRecord> fileTag = new TupleTag<>();
        final TupleTag<MysqlRecord> mysqlTag = new TupleTag<>();
        PCollection<KV<Integer, CoGbkResult>> joinedRawCollection =
                KeyedPCollectionTuple.of(fileTag, fileRecords)
                        .and(mysqlTag, mysqlRecords)
                        .apply(CoGroupByKey.create());
</code>```

Here is the Spark Executor DAG visualization

Eventually the one worker will run out of memory. I know in Spark natively, one can specify Partitioners to help distribute the workload across workers. However, how do I do that in Beam?

EDIT:

I suspected that JDBCIo couldn't properly distribute the one query so I split it up into multiple PCollections and then flattened them later. I read much faster from Mysql, but eventually ran into the same problem.

Here are the stages that are being worked on:

But each stage still suffers from that imbalance?:

答: To answer my own question with the realization of my own failure to differentiate between Spark Stages and task. The tasks were indeed spread out, I just actually did not allocate enough memory to the driver program.</p>

Body:
I have a simple pipeline that reads records both both a text file and mysql and tries to reconcile them, i.e. insert records when they don't exist in the DB, update records in the DB with the file, and do some other updates to records in the DB that do not exist in the file.

A problem that arises when run with 2M records in Spark is the following:

My hunch is that the following code is producing that imbalance

        final TupleTag<FileRecord> fileTag = new TupleTag<>();
        final TupleTag<MysqlRecord> mysqlTag = new TupleTag<>();
        PCollection<KV<Integer, CoGbkResult>> joinedRawCollection =
                KeyedPCollectionTuple.of(fileTag, fileRecords)
                        .and(mysqlTag, mysqlRecords)
                        .apply(CoGroupByKey.create());

Here is the Spark Executor DAG visualization

Eventually the one worker will run out of memory. I know in Spark natively, one can specify Partitioners to help distribute the workload across workers. However, how do I do that in Beam?

EDIT:

I suspected that JDBCIo couldn't properly distribute the one query so I split it up into multiple PCollections and then flattened them later. I read much faster from Mysql, but eventually ran into the same problem.

Here are the stages that are being worked on:

But each stage still suffers from that imbalance?:


问:
Jquery image bookmarklet not working in Django
Im working through Django By Example and in one chapter a Jquery bookmarklet is built within a Django app so that a user can easily save jpg images from a website into their user profile area within the Django app.

Im not an experienced JS or Jquery programmer but I did some JS some years back and can read the code however the tutorial does give exact instructions on what to do which I have followed and although I have managed to get the bookmarklet button to appear in my bookmarks bar in Chrome, nothing happens when I click it when browsing a webpage with jpg images.

This is my local Django dashboard where the bookmarklet button is added to the bookmarks bar and this part works fine

and this is what it should look like when clicked on, this is the part where nothing happens for me

these are the relevant js files

https://github.com/davejonesbkk/bookmarks/blob/master/images/templates/bookmarklet_launcher.js

https://github.com/davejonesbkk/bookmarks/blob/master/images/static/js/bookmarklet.js

the only thing I can see that is different with these compared to the files that came with the book is the indentation is a bit off but for some reason the indentation does seem to have changed a bit when I uploaded to Git and they dont look like that locally. Is indentation important in JS?

答: Make sure you're trying to use it on a HTTP site only. Since you're serving from same protocol. HTTPS site would always tell say: There is a problem loadingbyour jquery. That's how I solved mine.</p>


问:
where to find source code link
i want to dowmload android source  as repo init -u git://android.git.kernel.org/platform/manifest.git -b android-2.2_r1,i know the method of downloads ,but i donot know  where to find "android-2.2_r1" ,if i want to find 2.1, how to modify the  parameter after -b,could you give a link that tell me which versions may be download. thanks </p>

答:
From repo guide

Using topic branches

To assign the
  branch to a particular project:

```<code>$ repo start branch name project
</code>```

To switch back and forth among
  branches that you have created in your
  local work environment:

```<code>$ git checkout branchname
</code>```

To see a list of existing branches:

```<code>$ git branch
</code>```

or...

```<code>$ repo branches
</code>```

Title: where to find source code link

Body:
From repo guide

Using topic branches

To assign the
  branch to a particular project:

$ repo start branch name project

To switch back and forth among
  branches that you have created in your
  local work environment:

$ git checkout branchname

To see a list of existing branches:

$ git branch

or...

$ repo branches


问:
Generating HTML Tables from Tuple Python
I have a tuple list of individuals. I would like to generate a HTML table for each person. I'm sure there is a simple way of doing this, but I dont know what that would be. I put together some code that I think is close, but probably not an efficient way of doing it.

Desired Output:

```<code><html>
<table>
<tr><td>Andrew</td><td>10</td><td>20</td></tr>
<tr><td>Andrew</td><td>54</td><td>56</td></tr>
</table>
<table>
<tr><td>Jim</td><td>20</td><td>12</td></tr>
<tr><td>Jim</td><td>23</td><td>15</td></tr>
</table>
<table>
<tr><td>Sarah</td><td>30</td><td>43</td></tr>
</table>
</code>```

My Code:

```<code>mytuple = [('Andrew','10','20'),('Jim',"20",'12'),("Sarah","30",'43'),("Jim","23",'15'),("Andrew","54",'56')]
mytuple = sorted(mytuple)
FULL_HTML = ""

for row in mytuple:
     individual_count =  mytuple.count(row[0])
     print individual_count

     for row1 in xrange(row, row + individual_count):
        HTML_BODY "<tr><td>" + row1[0] + "</td><td>" + row1[1] + "</td><td>" + row1[2] + "</td><td></tr>\n"

     FULL_HTML = "<table>\n" _ FULL_HTML + HTML_BODY +"\n</table>\n"

FULL_HTML = "<html>\n" + FULL_HTML + "\n</html>"

print FULL_HTML
</code>```

答:
The following is simple:

import pandas as pd

df = pd.DataFrame(list(mytuple),columns['name1','name2','name3'])          #name1,name2,name3 are coloumn headings
html = df.to_html("index.html")
# Create index.html to write html on it
 f = open("index.html","r+")
 data = f.read()```

Body:
I have a tuple list of individuals. I would like to generate a HTML table for each person. I'm sure there is a simple way of doing this, but I dont know what that would be. I put together some code that I think is close, but probably not an efficient way of doing it.

Desired Output:

Andrew	10	20

Andrew	54	56

Jim	20	12

Jim	23	15

Sarah	30	43

My Code:

mytuple = [('Andrew','10','20'),('Jim',"20",'12'),("Sarah","30",'43'),("Jim","23",'15'),("Andrew","54",'56')]
mytuple = sorted(mytuple)
FULL_HTML = ""

for row in mytuple:
     individual_count =  mytuple.count(row[0])
     print individual_count

     for row1 in xrange(row, row + individual_count):
        HTML_BODY "
" + row1[0] + "	" + row1[1] + "	" + row1[2] + "
\n"

     FULL_HTML = "
\n" _ FULL_HTML + HTML_BODY +"\n
\n"

FULL_HTML = "\n" + FULL_HTML + "\n"

print FULL_HTML


问:
jQuery UI ui-autocomplete-loading spinner not stopping/disappear when found results
I am using JQuery UI autocomplete-loading spinner in my project by adding .ui-autocomplete-loading class. When I start typing in the editor box, the spinner shows up as expect. If there is no match results, the loading spinner disappear which indicates the search complete. But if there is a match found, the spinner is still showing, even after a selection is made. (see below pic)

My goal is to get this results: (when search complete or results found, spinner should be removed/stopped)
https://jqueryui.com/autocomplete/#multiple-remote

Here is my example code:

View:

```<code>@model AutoCompleteInMVCJson.Models.City

@{
    ViewBag.Title = "www.myexample.com";
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<style>
    .ui-autocomplete-loading {
        background: white url("../images/ui-anim_basic_16x16.gif") right center no-repeat;
    }
</style>
<script type="text/javascript">
    $(document).ready(function () {
        $("#Name").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "/Home/Index",
                    type: "POST",
                    dataType: "json",
                    data: { Prefix: request.term },
                    success: function (data) {
                        response($.map(data, function (item) {
                            return { label: item.Name, value: item.Name };
                        }))

                    }
                })
            },
            messages: {
                noResults: "", results: ""
            }
        });
    })
</script>
</code>```

Model

```<code>public class City
{
    public int Id { get; set; }
    public string Name { get; set; }

}
</code>```

Controller:

```<code>[HttpPost]
        public JsonResult Index(string Prefix)
        {
            //Note : you can bind same list from database
            List<City> ObjList = new List<City>()
            {

                new City {Id=1,Name="Latur" },
                new City {Id=2,Name="Mumbai" },
                new City {Id=3,Name="Pune" },
                new City {Id=4,Name="Delhi" },
                new City {Id=5,Name="Dehradun" },
                new City {Id=6,Name="Noida" },
                new City {Id=7,Name="New Delhi" }

        };
            //Searching records from list using LINQ query
            var CityName = (from N in ObjList
                            where N.Name.StartsWith(Prefix)
                          select new { N.Name });
            return Json(CityName, JsonRequestBehavior.AllowGet);
        }
    }
</code>```

How can I fix this issue? Thanks in advance.

答:
In Ajax success method you can simply remove class from textbox using .removeClass function</p>

```<code>$("#textboxid").removeClass("ui-autocomplete-loading");
</code>```

Body:
I am using JQuery UI autocomplete-loading spinner in my project by adding .ui-autocomplete-loading class. When I start typing in the editor box, the spinner shows up as expect. If there is no match results, the loading spinner disappear which indicates the search complete. But if there is a match found, the spinner is still showing, even after a selection is made. (see below pic)

My goal is to get this results: (when search complete or results found, spinner should be removed/stopped)
https://jqueryui.com/autocomplete/#multiple-remote

Here is my example code:

View:

@model AutoCompleteInMVCJson.Models.City

@{
    ViewBag.Title = "www.myexample.com";
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">

Model

public class City
{
    public int Id { get; set; }
    public string Name { get; set; }

}

Controller:

[HttpPost]
        public JsonResult Index(string Prefix)
        {
            //Note : you can bind same list from database
            List<City> ObjList = new List<City>()
            {

                new City {Id=1,Name="Latur" },
                new City {Id=2,Name="Mumbai" },
                new City {Id=3,Name="Pune" },
                new City {Id=4,Name="Delhi" },
                new City {Id=5,Name="Dehradun" },
                new City {Id=6,Name="Noida" },
                new City {Id=7,Name="New Delhi" }

        };
            //Searching records from list using LINQ query
            var CityName = (from N in ObjList
                            where N.Name.StartsWith(Prefix)
                          select new { N.Name });
            return Json(CityName, JsonRequestBehavior.AllowGet);
        }
    }

How can I fix this issue? Thanks in advance.

Body:
In Ajax success method you can simply remove class from textbox using .removeClass function

$("#textboxid").removeClass("ui-autocomplete-loading");


问:
Copy contents of one List into another List (not reference)
I have two List :

```<code>List<Object> listA = new ArrayList<Object>();
List<Object> newListB = new ArrayList<Object>();
</code>```

How can i copy the contents of listA into newListB such as if i change one of the elements in my copied list, i dont want to change it in my original list.

答:
Am afraid to tell you that clone is broken in java:

https://en.wikipedia.org/wiki/Clone_(Java_method)

http://www.javapractices.com/topic/TopicAction.do?Id=71

so you better off need to implement your deep copy method (which will bring you a O(log n) problem)

```<code>List<Point> listA = new ArrayList<>();
listA.add(new Point(0, 0));
listA.add(new Point(1, 1));
listA.add(new Point(2, 2));

List<Point> newListB = new ArrayList<>();

for (Point point : listA) {
    newListB.add(new Point(point));
}
System.out.println("Before deep copy");
System.out.println(listA);
System.out.println(newListB);
listA.get(0).setX(987);
listA.get(0).setY(987);
System.out.println("after changes ");
System.out.println(listA);
System.out.println(newListB);
</code>```

Body:
I have two List :

List<Object> listA = new ArrayList<Object>();
List<Object> newListB = new ArrayList<Object>();

How can i copy the contents of listA into newListB such as if i change one of the elements in my copied list, i dont want to change it in my original list.

Body:
Am afraid to tell you that clone is broken in java:

https://en.wikipedia.org/wiki/Clone_(Java_method)

http://www.javapractices.com/topic/TopicAction.do?Id=71

so you better off need to implement your deep copy method (which will bring you a O(log n) problem)

List<Point> listA = new ArrayList<>();
listA.add(new Point(0, 0));
listA.add(new Point(1, 1));
listA.add(new Point(2, 2));

List<Point> newListB = new ArrayList<>();

for (Point point : listA) {
    newListB.add(new Point(point));
}
System.out.println("Before deep copy");
System.out.println(listA);
System.out.println(newListB);
listA.get(0).setX(987);
listA.get(0).setY(987);
System.out.println("after changes ");
System.out.println(listA);
System.out.println(newListB);


问:
ReactJS: how to append a component to the App component in React
I am trying to append a "Item" component which consists of some array items, in the main "App" Component. But the component is getting replaced with the new array items instead of getting appended. Following is the code snippet:

```<code>//the App render function
render: function() {
    return (
        <div>
        {
            this.state.productDisplayed.map(function(product, i) {
                return (
                    <Item source = {product.url} prodId = {product.id}  key = {product.id} />
                )
            })
        }

        </div>
    )
}

//The Item render function
render: function(){
    return(
        <div className = "col-sm-4" >
            <img src = {this.props.source} width = "70%" className = "img-responsive"></img>
            <div>{this.props.prodId}
            </div>
        </div>
    )
}
</code>```

"ProductDisplayed" is an array which gets replaced by new items which are then displayed using a "for" loop.

How can i append the items as if I am adding some extra items to the main App component. I am trying to implement infinite scrolling.

答:
You need to append them to the array in your state.  I have used the function argument to setState because your nextState is dependent on your previous state.</p>

```<code>component ProductList extends React.Component {
    constructor() {
        super()
        this.setState({
            productDisplayed: []
        });
    }

    getMoreItems = ( startingId ) => {
        Api.getMoreItems(startingId).then(this.addItems);
    }

    addItems = ( items ) => {
        this.setState(( prevState ) => ({
          updatedItems: [...prevState.productDisplayed, ...items]
        }));
    }

    render() {
        // no changes
        // something triggers this.getMoreItems(id)
    }
}
</code>```

Body:
I am trying to append a "Item" component which consists of some array items, in the main "App" Component. But the component is getting replaced with the new array items instead of getting appended. Following is the code snippet:

//the App render function
render: function() {
    return (

        {
            this.state.productDisplayed.map(function(product, i) {
                return (
                    <Item source = {product.url} prodId = {product.id}  key = {product.id} />
                )
            })
        }

    )
}

//The Item render function
render: function(){
    return(

{this.props.prodId}

    )
}

"ProductDisplayed" is an array which gets replaced by new items which are then displayed using a "for" loop.

How can i append the items as if I am adding some extra items to the main App component. I am trying to implement infinite scrolling.

Body:
You need to append them to the array in your state.  I have used the function argument to setState because your nextState is dependent on your previous state.

component ProductList extends React.Component {
    constructor() {
        super()
        this.setState({
            productDisplayed: []
        });
    }

    getMoreItems = ( startingId ) => {
        Api.getMoreItems(startingId).then(this.addItems);
    }

    addItems = ( items ) => {
        this.setState(( prevState ) => ({
          updatedItems: [...prevState.productDisplayed, ...items]
        }));
    }

    render() {
        // no changes
        // something triggers this.getMoreItems(id)
    }
}


问:
Angular2 404 Not Found for URL: http://localhost/WebApi2/api/hero
I have tried the http Angular 2 and TypeScript example on https://angular.io/docs/ts/latest/tutorial/toh-pt6.html it works.
https://embed.plnkr.co/?show=preview

Updated code to use external Web Api

```<code>private headers = new Headers({'Content-Type': 'application/json'});
// private heroesUrl = 'api/heroes';  // URL to web api
private heroesUrl = 'http://localhost/WebApi2/api/hero';  // URL to web api

constructor(private http: Http) { }

getHeroes(): Promise<Hero[]> {
   return this.http.get(this.heroesUrl)
               .toPromise()
               .then(response => response.json().data as Hero[])
               .catch(this.handleError);
}
</code>```

Now I want to update it to use an external Web Api2 and get the error below.

EXCEPTION: Uncaught (in promise): Response with status: 404 Not Found for URL: http://localhost/WebApi2/api/hero"
  An error occurred Object { _body: Object, status: 404, ok: false, statusText: "Not Found", headers: Object, type: null, url: "http://localhost/WebApi2/api/hero" }

I have looked at this solution but it does not work for me.
Angular2 http get request results into 404

Error on import

```<code>import { Injectable }    from '@angular/core';
import { Headers, Http } from '@angular/http';
import { JSONP_PROVIDERS } from '@angular/http';
</code>```

Http/Http/node_modules/@angular/http/index"' has no exported member 'JSONP_PROVIDERS'.

Could anyone point me in the correct direction, example of calling Web Api2 from Angular2?

答:
I personnaly fought with this for over two weeks before I landed on a post by @mp-loki -- Angular 2 HTTP GET 404 Not Found for URL -- here on stackoverflow: The credit therefore really goes to him (or her, to be safe).

On the Angular setup page (https://angular.io/docs/ts/latest/guide/setup.html), you are greeted with this sentence: "Install the Angular QuickStart seed for faster, more efficient development on your machine."

You probably followed the instructions on that setup page and your project is therefore based on the Angular QuickStart Seed.

There's nothing wrong with that, only that the tutorial given by Angular uses an in-memory web api, and that intercepts all requests to another web api, whether you make a direct call to the in-memory web api from your project code or not.

To make requests to a different web api, you therefore have to disconnect  from the in-memory web api. How? Just follow the steps below:

In your project root directory, expand node_modules and delete the angular-in-memory-web-api directory

Still in your project root directory, open the package.json file and remove the following line from the list of dependencies: "angular-in-memory-web-api": "~0.2.4",

In the src/app directory, if the following files exit, or any files related to in-memory, delete them: in-memory-data.service.ts, in-memory-data.service.js, and in-memory-data.service.js.map

Open src/app/app.module.ts and remove the following from the list of imports: import { InMemoryWebApiModule } from 'angular-in-memory-web-api';, and import { InMemoryDataService }  from './in-memory-data.service';

Still in src/app/app.module.ts, remove this line of code from the @NgModule annotation: InMemoryWebApiModule.forRoot(InMemoryDataService),

At this stage you should be able to make requests to your web api, but most likely the object returned doesn't have a data property, so you remove it from your service file: Replace:

```<code>getHeroes(): Promise<Hero[]> {
   return this.http.get(this.heroesUrl)
               .toPromise()
               .then(response => response.json().data as Hero[])
               .catch(this.handleError);
}
</code>```

with

```<code>getHeroes(): Promise<Hero[]> {
   return this.http.get(this.heroesUrl)
               .toPromise()
               .then(response => response.json() as Hero[])
               .catch(this.handleError);
}
</code>```

I hope this helps.

Body:
I have tried the http Angular 2 and TypeScript example on https://angular.io/docs/ts/latest/tutorial/toh-pt6.html it works.
https://embed.plnkr.co/?show=preview

Updated code to use external Web Api

private headers = new Headers({'Content-Type': 'application/json'});
// private heroesUrl = 'api/heroes';  // URL to web api
private heroesUrl = 'http://localhost/WebApi2/api/hero';  // URL to web api

constructor(private http: Http) { }

getHeroes(): Promise<Hero[]> {
   return this.http.get(this.heroesUrl)
               .toPromise()
               .then(response => response.json().data as Hero[])
               .catch(this.handleError);
}

Now I want to update it to use an external Web Api2 and get the error below.

EXCEPTION: Uncaught (in promise): Response with status: 404 Not Found for URL: http://localhost/WebApi2/api/hero"
  An error occurred Object { _body: Object, status: 404, ok: false, statusText: "Not Found", headers: Object, type: null, url: "http://localhost/WebApi2/api/hero" }

I have looked at this solution but it does not work for me.
Angular2 http get request results into 404

Error on import

import { Injectable }    from '@angular/core';
import { Headers, Http } from '@angular/http';
import { JSONP_PROVIDERS } from '@angular/http';

Http/Http/node_modules/@angular/http/index"' has no exported member 'JSONP_PROVIDERS'.

Could anyone point me in the correct direction, example of calling Web Api2 from Angular2?

Body:
I personnaly fought with this for over two weeks before I landed on a post by @mp-loki -- Angular 2 HTTP GET 404 Not Found for URL -- here on stackoverflow: The credit therefore really goes to him (or her, to be safe).

On the Angular setup page (https://angular.io/docs/ts/latest/guide/setup.html), you are greeted with this sentence: "Install the Angular QuickStart seed for faster, more efficient development on your machine."

You probably followed the instructions on that setup page and your project is therefore based on the Angular QuickStart Seed.

There's nothing wrong with that, only that the tutorial given by Angular uses an in-memory web api, and that intercepts all requests to another web api, whether you make a direct call to the in-memory web api from your project code or not.

To make requests to a different web api, you therefore have to disconnect  from the in-memory web api. How? Just follow the steps below:

In your project root directory, expand node_modules and delete the angular-in-memory-web-api directory

Still in your project root directory, open the package.json file and remove the following line from the list of dependencies: "angular-in-memory-web-api": "~0.2.4",

In the src/app directory, if the following files exit, or any files related to in-memory, delete them: in-memory-data.service.ts, in-memory-data.service.js, and in-memory-data.service.js.map

Open src/app/app.module.ts and remove the following from the list of imports: import { InMemoryWebApiModule } from 'angular-in-memory-web-api';, and import { InMemoryDataService }  from './in-memory-data.service';

Still in src/app/app.module.ts, remove this line of code from the @NgModule annotation: InMemoryWebApiModule.forRoot(InMemoryDataService),

At this stage you should be able to make requests to your web api, but most likely the object returned doesn't have a data property, so you remove it from your service file: Replace:

getHeroes(): Promise<Hero[]> {
   return this.http.get(this.heroesUrl)
               .toPromise()
               .then(response => response.json().data as Hero[])
               .catch(this.handleError);
}

with

getHeroes(): Promise<Hero[]> {
   return this.http.get(this.heroesUrl)
               .toPromise()
               .then(response => response.json() as Hero[])
               .catch(this.handleError);
}

I hope this helps.


问:
three.js: Change attributes value in vertex shader and pass to buffer
Is it possible to change the value of an attribute in the shader and have this reflected in the buffer for the next frame render?

So for example change the position of a vertex in the vertex shader and send this new value back to the javascript buffer object?

Code sample below:

```<code>attribute vec3 newPosition;
attribute vec3 divideVal;

void main() {
    vec3 difference = newPosition - position;

    velocity = difference / divideVal;

    position += velocity;

    vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);

    gl_PointSize = size * (sizeMultipler / -mvPosition.z);

    gl_Position = projectionMatrix * mvPosition;
}
</code>```

Edit:

Right now I do this in the JS itself, but understand it will be faster if I move as much calculation as I can to the shaders? This is my current JS:

```<code>const positions = this.geometry.attributes.position.array;
const newPositions = this.geometry.attributes.newPosition.array;

for (let i = 0, i3 = 0; i < this.numParticles; i++, i3 += 3) {
    const velocity = [newPositions[i3] - positions[i3], newPositions[i3 + 1] - positions[i3 + 1], newPositions[i3 + 2] - positions[i3 + 2]];

    if (velocity[0] || velocity[1] || velocity[2]) {
        const minReset = 1;

        velocity[0] = velocity[0] / 60;
        velocity[1] = velocity[1] / 60;
        velocity[2] = velocity[2] / 60;

        positions[i3] = positions[i3] + velocity[0];
        positions[i3 + 1] = positions[i3 + 1] + velocity[1];
        positions[i3 + 2] = positions[i3 + 2] + velocity[2];
    }
}
</code>```

答:
I found out how to do this.

Using a concept called FBO Simulation, I created a simulation shader, which computes the calculations in its glsl shaders, and then rather than displaying the results on screens, writes them to a texture. I then read from that texture in the "real" shader and wrote the results to the screen. This also allowed me to compare different output textures to work out velocity and size differences of particles between frames.

You can read more about it being discussed here: https://github.com/mrdoob/three.js/issues/1183

Example:
http://barradeau.com/blog/?p=621

Body:
Is it possible to change the value of an attribute in the shader and have this reflected in the buffer for the next frame render?

So for example change the position of a vertex in the vertex shader and send this new value back to the javascript buffer object?

Code sample below:

attribute vec3 newPosition;
attribute vec3 divideVal;

void main() {
    vec3 difference = newPosition - position;

    velocity = difference / divideVal;

    position += velocity;

    vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);

    gl_PointSize = size * (sizeMultipler / -mvPosition.z);

    gl_Position = projectionMatrix * mvPosition;
}

Edit:

Right now I do this in the JS itself, but understand it will be faster if I move as much calculation as I can to the shaders? This is my current JS:

const positions = this.geometry.attributes.position.array;
const newPositions = this.geometry.attributes.newPosition.array;

for (let i = 0, i3 = 0; i < this.numParticles; i++, i3 += 3) {
    const velocity = [newPositions[i3] - positions[i3], newPositions[i3 + 1] - positions[i3 + 1], newPositions[i3 + 2] - positions[i3 + 2]];

    if (velocity[0] || velocity[1] || velocity[2]) {
        const minReset = 1;

        velocity[0] = velocity[0] / 60;
        velocity[1] = velocity[1] / 60;
        velocity[2] = velocity[2] / 60;

        positions[i3] = positions[i3] + velocity[0];
        positions[i3 + 1] = positions[i3 + 1] + velocity[1];
        positions[i3 + 2] = positions[i3 + 2] + velocity[2];
    }
}


问:
Why can't I reference a character in a string that was previously cast to void?
To use pthreads, I used as input a char* that was cast to void* as input. If it's later cast to (char*) it can be printed and used normally ( (char*)var ). However, if one does (char*)var[i], where 'i' will help us reference a character, it doesn't. Why?

e.g. MS says 'expression must be a pointer to a complete object type'.

答: Try (char *) &var[i], but that simply gets reference from var[i]. You can't do (char *) var[i] as that actually tries to convert a char to (char *).


问:
ffmpeg returned non-zero exit status. Check stdout Coldfusion
I have an coldfusion application. I am converting recorded video from mobile through ffmpeg and coldfusion. Here is the ffmpeg command which i am running.

ffmpegPath -i "inputfile" -vcodec libx264 -acodec aac "OutputFile"

Output file type is mp4. I want to convert my all videos to mp4 with h.264 and ACC sound. So that it will work on all platforms.

I am getting the following error:

```<code>java.io.IOException: ffmpeg returned non-zero exit status. Check stdout.
</code>```

Here is the CF code that i am running.

```<code><cfset resultLog        = "path\to\directory\testOuput_result.log">
<cfset errorLog         = "path\to\directory\testOuput_error.log">
<cfset results  = structNew()>
        <cfscript>
            try {
                runtime = createObject("java", "java.lang.Runtime").getRuntime();
                command = 'ffmpegPath -i "inputfile" -vcodec libx264 -acodec aac "OutputFile"';
                process = runtime.exec(#command#);
                results.errorLogSuccess = processStream(process.getErrorStream(), errorLog);
                results.resultLogSuccess = processStream(process.getInputStream(), resultLog);
                results.exitCode = process.waitFor();
            }
            catch(exception e) {
                results.status = e;
            }
        </cfscript>
<cffunction name="processStream" access="public" output="false" returntype="boolean" hint="Returns true if stream was successfully processed">
    <cfargument name="in" type="any" required="true" hint="java.io.InputStream object">
    <cfargument name="logPath" type="string" required="false" default="" hint="Full path to LogFile">
    <cfset var out = "">
    <cfset var writer = "">
    <cfset var reader = "">
    <cfset var buffered = "">
    <cfset var line = "">
    <cfset var sendToFile = false>
    <cfset var errorFound = false>

    <cfscript>
        if ( len(trim(arguments.logPath)) ) {
            out = createObject("java", "java.io.FileOutputStream").init(arguments.logPath);
            writer = createObject("java", "java.io.PrintWriter").init(out);
            sendToFile = true;
        }

        reader = createObject("java", "java.io.InputStreamReader").init(arguments.in);
        buffered = createObject("java", "java.io.BufferedReader").init(reader);
        line = buffered.readLine();
        while ( IsDefined("line") ) {
            if (sendToFile) {
                writer.println(line);
            }
            line = buffered.readLine();
        }
           if (sendToFile) {
           errorFound = writer.checkError();
           writer.flush();
           writer.close();
        }
    </cfscript>
    <!--- return true if no errors found. --->
    <cfreturn (NOT errorFound)>
</cffunction>
</code>```

I have also used different ffmpeg.exe but got same error. I have also used ffmpeg-cli-wrapper java wrapper in coldfusion. Still i got the same error. Can any one help me to sort out this issue.

答: I am able to resolve this issue. The problem is in inputfile path. I have fixed this by passing absolute path of inputfile to ffmpeg</p>

Body:
I have an coldfusion application. I am converting recorded video from mobile through ffmpeg and coldfusion. Here is the ffmpeg command which i am running.

ffmpegPath -i "inputfile" -vcodec libx264 -acodec aac "OutputFile"

Output file type is mp4. I want to convert my all videos to mp4 with h.264 and ACC sound. So that it will work on all platforms.

I am getting the following error:

java.io.IOException: ffmpeg returned non-zero exit status. Check stdout.

Here is the CF code that i am running.

<cfset resultLog        = "path\to\directory\testOuput_result.log">
<cfset errorLog         = "path\to\directory\testOuput_error.log">
<cfset results  = structNew()>
        <cfscript>
            try {
                runtime = createObject("java", "java.lang.Runtime").getRuntime();
                command = 'ffmpegPath -i "inputfile" -vcodec libx264 -acodec aac "OutputFile"';
                process = runtime.exec(#command#);
                results.errorLogSuccess = processStream(process.getErrorStream(), errorLog);
                results.resultLogSuccess = processStream(process.getInputStream(), resultLog);
                results.exitCode = process.waitFor();
            }
            catch(exception e) {
                results.status = e;
            }
        </cfscript>
<cffunction name="processStream" access="public" output="false" returntype="boolean" hint="Returns true if stream was successfully processed">
    <cfargument name="in" type="any" required="true" hint="java.io.InputStream object">
    <cfargument name="logPath" type="string" required="false" default="" hint="Full path to LogFile">
    <cfset var out = "">
    <cfset var writer = "">
    <cfset var reader = "">
    <cfset var buffered = "">
    <cfset var line = "">
    <cfset var sendToFile = false>
    <cfset var errorFound = false>

    <cfscript>
        if ( len(trim(arguments.logPath)) ) {
            out = createObject("java", "java.io.FileOutputStream").init(arguments.logPath);
            writer = createObject("java", "java.io.PrintWriter").init(out);
            sendToFile = true;
        }

        reader = createObject("java", "java.io.InputStreamReader").init(arguments.in);
        buffered = createObject("java", "java.io.BufferedReader").init(reader);
        line = buffered.readLine();
        while ( IsDefined("line") ) {
            if (sendToFile) {
                writer.println(line);
            }
            line = buffered.readLine();
        }
           if (sendToFile) {
           errorFound = writer.checkError();
           writer.flush();
           writer.close();
        }
    </cfscript>

    <cfreturn (NOT errorFound)>
</cffunction>

I have also used different ffmpeg.exe but got same error. I have also used ffmpeg-cli-wrapper java wrapper in coldfusion. Still i got the same error. Can any one help me to sort out this issue.


问:
Convert stdClass object to array in PHP
I fetch post_id from postmeta as:

```<code>$post_id = $wpdb->get_results("SELECT post_id FROM $wpdb->postmeta WHERE (meta_key = 'mfn-post-link1' AND meta_value = '". $from ."')");
</code>```

when i try print_r($post_id);
I have array like this:

```<code>Array
(
    [0] => stdClass Object
        (
            [post_id] => 140
        )

    [1] => stdClass Object
        (
            [post_id] => 141
        )

    [2] => stdClass Object
        (
            [post_id] => 142
        )

)
</code>```

and i dont know how to traverse it, and how could I get array like this

```<code>Array
(
    [0]  => 140

    [1] => 141

    [2] => 142

)
</code>```

Any idea how can I do this?

答:
Lets assume $post_id is array of $item

```<code>$post_id = array_map(function($item){

       return $item->{'post_id'};

       },$post_id);
</code>```

strong text

ContentLicense: CC BY-SA 4.0

Title: Convert stdClass object to array in PHP

Body:
I fetch post_id from postmeta as:

$post_id = $wpdb->get_results("SELECT post_id FROM $wpdb->postmeta WHERE (meta_key = 'mfn-post-link1' AND meta_value = '". $from ."')");

when i try print_r($post_id);
I have array like this:

Array
(
    [0] => stdClass Object
        (
            [post_id] => 140
        )

    [1] => stdClass Object
        (
            [post_id] => 141
        )

    [2] => stdClass Object
        (
            [post_id] => 142
        )

)

and i dont know how to traverse it, and how could I get array like this

Array
(
    [0]  => 140

    [1] => 141

    [2] => 142

)

Any idea how can I do this?

Body:
Lets assume $post_id is array of $item

$post_id = array_map(function($item){

       return $item->{'post_id'};

       },$post_id);

strong text


问:
Injecting Single Instance HttpClient with specific HttpMessageHandler
As part of an ASP.Net Core project that I am working on I have a requirement to communicate with a number of different Rest based API Endpoints from within my WebApi.  To achieve this I am using a number of service classes that each instantiate a static HttpClient.  Essentially I have a service class for each of the Rest based endpoints that the WebApi connects to.

An example of how the static HttpClient is instantiated in each of the service classes can be seen below.

```<code>private static HttpClient _client = new HttpClient()
{
    BaseAddress = new Uri("http://endpointurlexample"),
};
</code>```

Whilst the above is working well, it does not allow for effective unit testing of the service classes that are using HttpClient.  To enable me to carry out unit testing I have a fake HttpMessageHandler that I would like to use for the HttpClient in my unit tests, whilst the HttpClient is instantiated as above however I am unable to apply the fake HttpMessageHandler as part of my unit tests.

What is the best way for the HttpClient in the service classes to remain a single instance throughout the application (one instance per endpoint), but to allow a different HttpMessageHandler to be applied during the unit tests?

One approach I have thought of would be not to use a static field to hold the HttpClient in the service classes, rather to allow it to be injected via constructor injection using a singleton lifecycle, which would allow me to specify a HttpClient with the desired HttpMessageHandler during unit tests, the other option I thought of would be to use a HttpClient Factory Class that instantiated the HttpClients in static fields that could then be retrieved by injecting the HttpClient factory into the service classes, again allowing a different implementation with the relevant HttpMessageHandler to be returned in unit tests.  None of the above feel particularly clean however and it feels like there must be a better way?

Any questions, let me know.

答:
You think to complicated. All you need is a HttpClient factory or accessor with a HttpClient property and use it the same way the ASP.NET Core is allowing HttpContext to be injected

```<code>public interface IHttpClientAccessor
{
    HttpClient Client { get; }
}

public class DefaultHttpClientAccessor : IHttpClientAccessor
{
    public HttpClient Client { get; }

    public DefaultHttpClientAccessor()
    {
        Client = new HttpClient();
    }
}
</code>```

and inject this in your services

```<code>public class MyRestClient : IRestClient
{
    private readonly HttpClient client;

    public MyRestClient(IHttpClientAccessor httpClientAccessor)
    {
        client = httpClientAccessor.Client;
    }
}
</code>```

registration in Startup.cs:

```<code>services.AddSingleton<IHttpClientAccessor, DefaultHttpClientAccessor>();
</code>```

For unit-testing, just mock it

```<code>// Moq-esque

// Arrange
var httpClientAccessor = new Mock<IHttpClientAccessor>();
var httpHandler = new HttpMessageHandler(..) { ... };
var httpContext = new HttpContext(httpHandler);

httpClientAccessor.SetupGet(a => a.Client).Returns(httpContext);

// Act
var restClient = new MyRestClient(httpClientAccessor.Object);
var result = await restClient.GetSomethingAsync(...);

// Assert
...
</code>```

Body:
As part of an ASP.Net Core project that I am working on I have a requirement to communicate with a number of different Rest based API Endpoints from within my WebApi.  To achieve this I am using a number of service classes that each instantiate a static HttpClient.  Essentially I have a service class for each of the Rest based endpoints that the WebApi connects to.

An example of how the static HttpClient is instantiated in each of the service classes can be seen below.

private static HttpClient _client = new HttpClient()
{
    BaseAddress = new Uri("http://endpointurlexample"),
};

Whilst the above is working well, it does not allow for effective unit testing of the service classes that are using HttpClient.  To enable me to carry out unit testing I have a fake HttpMessageHandler that I would like to use for the HttpClient in my unit tests, whilst the HttpClient is instantiated as above however I am unable to apply the fake HttpMessageHandler as part of my unit tests.

What is the best way for the HttpClient in the service classes to remain a single instance throughout the application (one instance per endpoint), but to allow a different HttpMessageHandler to be applied during the unit tests?

One approach I have thought of would be not to use a static field to hold the HttpClient in the service classes, rather to allow it to be injected via constructor injection using a singleton lifecycle, which would allow me to specify a HttpClient with the desired HttpMessageHandler during unit tests, the other option I thought of would be to use a HttpClient Factory Class that instantiated the HttpClients in static fields that could then be retrieved by injecting the HttpClient factory into the service classes, again allowing a different implementation with the relevant HttpMessageHandler to be returned in unit tests.  None of the above feel particularly clean however and it feels like there must be a better way?

Any questions, let me know.

Body:
You think to complicated. All you need is a HttpClient factory or accessor with a HttpClient property and use it the same way the ASP.NET Core is allowing HttpContext to be injected

public interface IHttpClientAccessor
{
    HttpClient Client { get; }
}

public class DefaultHttpClientAccessor : IHttpClientAccessor
{
    public HttpClient Client { get; }

    public DefaultHttpClientAccessor()
    {
        Client = new HttpClient();
    }
}

and inject this in your services

public class MyRestClient : IRestClient
{
    private readonly HttpClient client;

    public MyRestClient(IHttpClientAccessor httpClientAccessor)
    {
        client = httpClientAccessor.Client;
    }
}

registration in Startup.cs:

services.AddSingleton<IHttpClientAccessor, DefaultHttpClientAccessor>();

For unit-testing, just mock it

// Moq-esque

// Arrange
var httpClientAccessor = new Mock<IHttpClientAccessor>();
var httpHandler = new HttpMessageHandler(..) { ... };
var httpContext = new HttpContext(httpHandler);

httpClientAccessor.SetupGet(a => a.Client).Returns(httpContext);

// Act
var restClient = new MyRestClient(httpClientAccessor.Object);
var result = await restClient.GetSomethingAsync(...);

// Assert
...


问:
How to close TCP and UDP ports via windows command line
Does somebody knows how to close a TCP or UDP socket for a single connection via windows command line?

Googling about this, I saw some people asking the same thing. But the answers looked like a manual page of netstat or netsh commands focusing on how to monitor the ports. I don't want answers on how to monitor them (I already do this). I want to close/kill them.

EDIT, for clarification: Let's say that my server listens TCP port 80. A client makes a connection and port 56789 is allocated for it. Then, I discover that this connection is undesired (e.g. this user is doing bad things, we asked them to stop but the connection didn't get dropped somewhere along the way). Normally, I would add a firewall to do the job, but this would take some time, and I was in an emergency situation. Killing the process that owns the connection is really a bad idea here because this would take down the server (all users would lose functionality when we just want to selectively and temporally drop this one connection).

答:
Yes there is possible to close TCP or UDP port there is a command in DOS </p>

```<code>TASKKILL /f /pid 1234
</code>```

<p>I hope this will work for You  </p>

Body:
Yes there is possible to close TCP or UDP port there is a command in DOS

TASKKILL /f /pid 1234

I hope this will work for You