问:
Ninject Runtime Exception occuring frequently - System.InvalidOperationException: Collection was modified; enumeration operation may not execute
I am using Ninject 2.2.1.0 with Ninject.Web 2.2.0.0 in a webforms application.

I am getting daily error reports of the following...

```<code>System.InvalidOperationException: Collection was modified; enumeration
</code>```

operation may not execute.
         at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource
  resource)
         at System.Collections.Generic.List1.Enumerator.MoveNextRare()
         at System.Collections.Generic.List1.Enumerator.MoveNext()
         at System.Linq.Enumerable.WhereSelectListIterator2.MoveNext()
         at Ninject.Infrastructure.Language.ExtensionsForIEnumerableOfT.Map[T](IEnumerable1
  series, Action`1 action) in
  c:\Projects\Ninject\ninject\src\Ninject\Infrastructure\Language\ExtensionsForIEnumerableOfT.cs:line
  22
         at Ninject.OnePerRequestModule.DeactivateInstancesForCurrentHttpRequest()
  in
  c:\Projects\Ninject\ninject\src\Ninject\OnePerRequestModule.cs:line
  63
         at Ninject.OnePerRequestModule.b__0(Object
  o, EventArgs e) in
  c:\Projects\Ninject\ninject\src\Ninject\OnePerRequestModule.cs:line
  36
         at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
         at System.Web.HttpApplication.ExecuteStep(IExecutionStep
  step, Boolean& completedSynchronously)

Seems to be occuring at peak times.  Is there a stable release with this patched yet?

答: Creation of kernel instances is not thread safe at the moment. This will probably be changed with 2.4</p>

Body:
I am using Ninject 2.2.1.0 with Ninject.Web 2.2.0.0 in a webforms application.

I am getting daily error reports of the following...

System.InvalidOperationException: Collection was modified; enumeration

operation may not execute.
         at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource
  resource)
         at System.Collections.Generic.List1.Enumerator.MoveNextRare()
         at System.Collections.Generic.List1.Enumerator.MoveNext()
         at System.Linq.Enumerable.WhereSelectListIterator2.MoveNext()
         at Ninject.Infrastructure.Language.ExtensionsForIEnumerableOfT.Map[T](IEnumerable1
  series, Action`1 action) in
  c:\Projects\Ninject\ninject\src\Ninject\Infrastructure\Language\ExtensionsForIEnumerableOfT.cs:line
  22
         at Ninject.OnePerRequestModule.DeactivateInstancesForCurrentHttpRequest()
  in
  c:\Projects\Ninject\ninject\src\Ninject\OnePerRequestModule.cs:line
  63
         at Ninject.OnePerRequestModule.b__0(Object
  o, EventArgs e) in
  c:\Projects\Ninject\ninject\src\Ninject\OnePerRequestModule.cs:line
  36
         at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
         at System.Web.HttpApplication.ExecuteStep(IExecutionStep
  step, Boolean& completedSynchronously)

Seems to be occuring at peak times.  Is there a stable release with this patched yet?


来源: stackexchange

问:
Python SQLAlchemy mocking
this is a method that I made chained DB query calls.

import math
def get_all_keys():
    db_session = DBSession()
    keys = db_session.query(SomeClass).all()
```

<p>I should mock <code>DBSession().query(SomeClass).all()</code>. I tried some but nothing worked. Here are my trials.</p>

<pre class="lang-py prettyprint-override"><code>@patch('app.modules.somemodule.DBSession')
def test_asd(self, DBSession):
    DBSession.execute.query.execute.all.return_value = [1, 2, 3]
    self.assertListEqual(DBSession.query('qwe').all(), [1, 2, 3])
</code>```

In this attempt if I try to print DBSession() I get a MagicMock object which seems fine. But when I run pytest I got following error.

```<code>    self = <test_some_module.SomeModuleTests testMethod=test_asd>, DBSession = <MagicMock name='DBSession' id='140028663111976'>

    @patch('app.modules.somemodule.DBSession')
    def test_asd(self, DBSession):
        DBSession.execute.query.execute.all.return_value = [1, 2, 3]
        print(DBSession().query('qwe').all())
>       self.assertListEqual(DBSession.query('qwe').all(), [1, 2, 3])
E       AssertionError: First sequence is not a list: <MagicMock name='DBSession.query().all()' id='140028662649184'>

tests/test_some_module.py:21: AssertionError
</code>```

Seems like I did something wrong while mocking. What is my mistake? I checked the documentation.

答:
You may use the alchemy mock for mocking session and data for SQLAlchemy

```<code>from alchemy_mock.mocking import UnifiedAlchemyMagicMock
db_session = UnifiedAlchemyMagicMock()
db_session.query.return_value.all.return_value = [1,2,3]

mock_res = test_asd(db_session)
self.assertEqual(mock_res, [1,2,3])
</code>```

optionally you may also mock data by

```<code>db_session.add(SomeClass(column1=1, column2=2, column3=3))
</code>```

ContentLicense: CC BY-SA 4.0

Title: Python SQLAlchemy mocking

Body:
this is a method that I made chained DB query calls.

import math
def get_all_keys():
    db_session = DBSession()
    keys = db_session.query(SomeClass).all()

I should mock DBSession().query(SomeClass).all(). I tried some but nothing worked. Here are my trials.

@patch('app.modules.somemodule.DBSession')
def test_asd(self, DBSession):
    DBSession.execute.query.execute.all.return_value = [1, 2, 3]
    self.assertListEqual(DBSession.query('qwe').all(), [1, 2, 3])

In this attempt if I try to print DBSession() I get a MagicMock object which seems fine. But when I run pytest I got following error.

    self = <test_some_module.SomeModuleTests testMethod=test_asd>, DBSession = <MagicMock name='DBSession' id='140028663111976'>

    @patch('app.modules.somemodule.DBSession')
    def test_asd(self, DBSession):
        DBSession.execute.query.execute.all.return_value = [1, 2, 3]
        print(DBSession().query('qwe').all())
>       self.assertListEqual(DBSession.query('qwe').all(), [1, 2, 3])
E       AssertionError: First sequence is not a list: <MagicMock name='DBSession.query().all()' id='140028662649184'>

tests/test_some_module.py:21: AssertionError

Seems like I did something wrong while mocking. What is my mistake? I checked the documentation.

Body:
You may use the alchemy mock for mocking session and data for SQLAlchemy

from alchemy_mock.mocking import UnifiedAlchemyMagicMock
db_session = UnifiedAlchemyMagicMock()
db_session.query.return_value.all.return_value = [1,2,3]

mock_res = test_asd(db_session)
self.assertEqual(mock_res, [1,2,3])

optionally you may also mock data by

db_session.add(SomeClass(column1=1, column2=2, column3=3))


问:
Add a time/delay into a foreach for reading a string / Visual Studio 2019 C# Win Forms
I want to easily read a string letter by letter, but slowly, and drop it into a textbox.

```<code>private void btn1_Click(object sender, EventArgs e)
{
    string str = "hello world", bar = string.Empty;

    foreach (char c in str)
    {
        bar += c;
        richTextBox1.Text = bar;

        /// delay??
    }
}
</code>```

答:
Turn the method async and add an await with the desired delay.

```<code>private async void button1_Click(object sender, EventArgs e)
{
    richTextBox1.Text = string.Empty;

    foreach (char c in "hello world")
    {
        richTextBox1.Text += c;
        await Task.Delay(100);
    }
}
</code>```

Body:
I want to easily read a string letter by letter, but slowly, and drop it into a textbox.

private void btn1_Click(object sender, EventArgs e)
{
    string str = "hello world", bar = string.Empty;

    foreach (char c in str)
    {
        bar += c;
        richTextBox1.Text = bar;

        /// delay??
    }
}

Body:
Turn the method async and add an await with the desired delay.

private async void button1_Click(object sender, EventArgs e)
{
    richTextBox1.Text = string.Empty;

    foreach (char c in "hello world")
    {
        richTextBox1.Text += c;
        await Task.Delay(100);
    }
}


问:
What should I return instead of null?
I've heard that it is bad practice to return null.

What are the alternatives to returning null in this case?

```<code>    public RollingStock getHeadPoint() {
        if (!train.isEmpty()) {
            return train.get(0);
        } else {
            return null;
        }
    }
</code>```

答: You could define a TrainIsEmptyException and throw that when the train is empty. Make it a checked Exception. Or you can just return null. </p>

Title: What should I return instead of null?

Body:
I've heard that it is bad practice to return null.

What are the alternatives to returning null in this case?

    public RollingStock getHeadPoint() {
        if (!train.isEmpty()) {
            return train.get(0);
        } else {
            return null;
        }
    }


问:
Lint found fatal errors while assembling a release target
383/5000
I have an app that gives me compilation errors when I change it to release mode to upload it to the play store

I've tried analyzing-inspecting code
and I do not have any error.

I have also tried the compilation sugestion in the build build gradle and it does not give an error, but when I try to install the apk it gives me an error: "the APK failed to install. Error: Could not stop error string"

```<code>org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:lintVitalRelease'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:100)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:70)
    at org.gradle.api.internal.tasks.execution.OutputDirectoryCreatingTaskExecuter.execute(OutputDirectoryCreatingTaskExecuter.java:51)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:62)
    at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:60)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:97)
    at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:87)
    at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.run(DefaultTaskGraphExecuter.java:248)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:241)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:230)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:123)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:79)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:104)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:98)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTaskExecutionPlan.java:626)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:581)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:98)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.gradle.api.GradleException: Lint found fatal errors while assembling a release target.

To proceed, either fix the issues identified by lint, or modify your build script as follows:
...
android {
    lintOptions {
        checkReleaseBuilds false
        // Or, if you prefer, you can continue to check for errors in release builds,
        // but continue the build even when errors are found:
        abortOnError false
    }
}
...
    at com.android.tools.lint.gradle.LintGradleExecution.abort(LintGradleExecution.java:199)
    at com.android.tools.lint.gradle.LintGradleExecution.runLint(LintGradleExecution.java:263)
    at com.android.tools.lint.gradle.LintGradleExecution.lintSingleVariant(LintGradleExecution.java:359)
    at com.android.tools.lint.gradle.LintGradleExecution.analyze(LintGradleExecution.java:93)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.android.tools.lint.gradle.api.ReflectiveLintRunner.runLint(ReflectiveLintRunner.kt:38)
    at com.android.build.gradle.tasks.LintBaseTask.runLint(LintBaseTask.java:87)
    at com.android.build.gradle.tasks.LintPerVariantTask.lint(LintPerVariantTask.java:41)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.doExecute(StandardTaskAction.java:46)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:39)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:26)
    at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:780)
    at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:747)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:121)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:110)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:92)
    ... 32 more
</code>```

答:
Here I have written an article on all possible solutions to resolve Lint found fatal errors issue.

Generally, you can resolve it in the following way:

Android studio shows all build errors in html & xml file present at the following link. Just open that file in your browser, check the error and fix it.

```<code>/YOUR_APPLICATION/app/build/reports/lint-results-release-fatal.html
</code>```

Sample Error

Body:
383/5000
I have an app that gives me compilation errors when I change it to release mode to upload it to the play store

I've tried analyzing-inspecting code
and I do not have any error.

I have also tried the compilation sugestion in the build build gradle and it does not give an error, but when I try to install the apk it gives me an error: "the APK failed to install. Error: Could not stop error string"

org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:lintVitalRelease'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:100)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:70)
    at org.gradle.api.internal.tasks.execution.OutputDirectoryCreatingTaskExecuter.execute(OutputDirectoryCreatingTaskExecuter.java:51)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:62)
    at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:60)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:97)
    at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:87)
    at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.run(DefaultTaskGraphExecuter.java:248)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:241)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:230)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:123)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:79)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:104)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:98)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTaskExecutionPlan.java:626)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:581)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:98)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.gradle.api.GradleException: Lint found fatal errors while assembling a release target.

To proceed, either fix the issues identified by lint, or modify your build script as follows:
...
android {
    lintOptions {
        checkReleaseBuilds false
        // Or, if you prefer, you can continue to check for errors in release builds,
        // but continue the build even when errors are found:
        abortOnError false
    }
}
...
    at com.android.tools.lint.gradle.LintGradleExecution.abort(LintGradleExecution.java:199)
    at com.android.tools.lint.gradle.LintGradleExecution.runLint(LintGradleExecution.java:263)
    at com.android.tools.lint.gradle.LintGradleExecution.lintSingleVariant(LintGradleExecution.java:359)
    at com.android.tools.lint.gradle.LintGradleExecution.analyze(LintGradleExecution.java:93)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.android.tools.lint.gradle.api.ReflectiveLintRunner.runLint(ReflectiveLintRunner.kt:38)
    at com.android.build.gradle.tasks.LintBaseTask.runLint(LintBaseTask.java:87)
    at com.android.build.gradle.tasks.LintPerVariantTask.lint(LintPerVariantTask.java:41)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.doExecute(StandardTaskAction.java:46)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:39)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:26)
    at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:780)
    at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:747)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:121)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:110)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:92)
    ... 32 more

Body:
Here I have written an article on all possible solutions to resolve Lint found fatal errors issue.

Generally, you can resolve it in the following way:

Android studio shows all build errors in html & xml file present at the following link. Just open that file in your browser, check the error and fix it.

/YOUR_APPLICATION/app/build/reports/lint-results-release-fatal.html

Sample Error


问:
Creating PyTest fixture parameters dynamically from another fixture
I have an AWS S3 directory containing several JSON files, which are used as test inputs.

I've created a PyTest module that downloads all JSON files once using a module wide fixture, and then runs several test functions - each being parameterized over the set of JSONs:

import pytest
import os
from tempfile import mkdtemp, TemporaryDirectory
from glob import glob

JSONS_AWS_PATH = 's3://some/path/'

def download_jsons():
    temp_dir = mkdtemp()
    aws_sync_dir(JSONS_AWS_PATH, temp_dir)
    json_filenames = glob(os.path.join(local_path, "*.json"))
    return json_filenames

@pytest.fixture(scope='module', params=download_jsons()) #<-- Invoking download_jsons() directly
def json_file(request):
    return request.param

def test_something(json_file):
   # Open the json file and test something

def test_something_else(json_file):
   # Open the json file and test something else

def test_another_thing(json_file):
   # you got the point...
```

<p>This test module in itself works - the only pain point is how to cleanup the <code>temp_dir</code> at the end of the module\session.<br>
Since <code>download_jsons()</code> is being invoked directly, before <code>json_file</code> fixture is even started - it has no context of its own. So I can't make it clean <code>temp_dir</code> after all the tests are done. </p>

<p>I would like to make <code>download_jsons()</code> a module\session scope <code>fixture</code> in itself. Something like:</p>

<pre class="lang-py prettyprint-override"><code>fixture(scope='module')
def download_jsons():
   temp_dir = mkdtemp()
   # Download and as glob, as above
   yield json_filenames
   shutil.rmtree(temp_dir)
</code>```

or

fixture(scope='module')
def download_jsons(tmpdir_factory):
    #...
```

as @Gabriela Melo has suggested.

The question is how to make the json_file fixture parameterized over the list returned by download_jsons(), without invoking it directly?

I've tried implementing this solution with either mark.parametrize, setup_module(), or pytest_generate_tests(metafunc) - but wasn't able to implement the exact functionality I was looking for.

答:
This seems to be what you're looking for: https://docs.pytest.org/en/latest/tmpdir.html#the-tmpdir-factory-fixture

(Using Pytest's tmpdir_factory fixture and setting the scope of your json_file function to session instead of module)

Body:
I have an AWS S3 directory containing several JSON files, which are used as test inputs.

I've created a PyTest module that downloads all JSON files once using a module wide fixture, and then runs several test functions - each being parameterized over the set of JSONs:

import pytest
import os
from tempfile import mkdtemp, TemporaryDirectory
from glob import glob

JSONS_AWS_PATH = 's3://some/path/'

def download_jsons():
    temp_dir = mkdtemp()
    aws_sync_dir(JSONS_AWS_PATH, temp_dir)
    json_filenames = glob(os.path.join(local_path, "*.json"))
    return json_filenames

@pytest.fixture(scope='module', params=download_jsons()) #<-- Invoking download_jsons() directly
def json_file(request):
    return request.param

def test_something(json_file):
   # Open the json file and test something

def test_something_else(json_file):
   # Open the json file and test something else

def test_another_thing(json_file):
   # you got the point...

This test module in itself works - the only pain point is how to cleanup the temp_dir at the end of the module\session.

Since download_jsons() is being invoked directly, before json_file fixture is even started - it has no context of its own. So I can't make it clean temp_dir after all the tests are done.

I would like to make download_jsons() a module\session scope fixture in itself. Something like:

fixture(scope='module')
def download_jsons():
   temp_dir = mkdtemp()
   # Download and as glob, as above
   yield json_filenames
   shutil.rmtree(temp_dir)

or

fixture(scope='module')
def download_jsons(tmpdir_factory):
    #...

as @Gabriela Melo has suggested.

The question is how to make the json_file fixture parameterized over the list returned by download_jsons(), without invoking it directly?

I've tried implementing this solution with either mark.parametrize, setup_module(), or pytest_generate_tests(metafunc) - but wasn't able to implement the exact functionality I was looking for.


问:
State not updating on view layer after it is updated in store mutation -- Vuex
I'm using a Vuex mutation to change the value of an array called practices.  I call this mutation in a component called PracticeTree, which includes a getter for practices.

```<code> handleNodeClick(data, other) {
     this.expanded=data.namespace
     this.SET_PRACTICES(data.practices)
     console.log('practices as set in view layer: ')
     console.log(this.practices)
 },
</code>```

The mutation that is called looks like:

```<code>SET_PRACTICES(state, data){
    Vue.set(state.practices, data)
    console.log('practices as set in the store:' )
    console.log(state.practices)
},
</code>```

I am using Vue.set instead of simply changing the state because I thought it might help when I saw that the state wasn't changing on the view layer - but it didn't.

Here is the output of the above functions:

```<code>practices as set in the store:
store.js?0571:100 (3) [{…}, {…}, {…}, "": (...), __ob__: Observer]
PracticeTree.vue?f108:95 practices as set in view layer:
PracticeTree.vue?f108:96 []
</code>```

As you can see, although the store updates the value of practices, it doesn't change within the component.

Does anyone have any ideas as to what may be going wrong?

答:
You are using the method incorrectly.

enter link description here

```<code>SET_PRACTICES(state, data){
    Vue.set(state, 'practices', data)
    console.log('practices as set in the store:' )
    console.log(state.practices)
}
</code>```

Body:
I'm using a Vuex mutation to change the value of an array called practices.  I call this mutation in a component called PracticeTree, which includes a getter for practices.

 handleNodeClick(data, other) {
     this.expanded=data.namespace
     this.SET_PRACTICES(data.practices)
     console.log('practices as set in view layer: ')
     console.log(this.practices)
 },

The mutation that is called looks like:

SET_PRACTICES(state, data){
    Vue.set(state.practices, data)
    console.log('practices as set in the store:' )
    console.log(state.practices)
},

I am using Vue.set instead of simply changing the state because I thought it might help when I saw that the state wasn't changing on the view layer - but it didn't.

Here is the output of the above functions:

practices as set in the store:
store.js?0571:100 (3) [{…}, {…}, {…}, "": (...), __ob__: Observer]
PracticeTree.vue?f108:95 practices as set in view layer:
PracticeTree.vue?f108:96 []

As you can see, although the store updates the value of practices, it doesn't change within the component.

Does anyone have any ideas as to what may be going wrong?

Body:
You are using the method incorrectly.

enter link description here

SET_PRACTICES(state, data){
    Vue.set(state, 'practices', data)
    console.log('practices as set in the store:' )
    console.log(state.practices)
}


ContentLicense: CC BY-SA 3.0

Title: Sort an array that has highest point?

Body:
How do I sort array that has highest point from 15.00 key?

I have an array look like this:

Array
(

    [9] => Array
        (
            [15.00] => 3.0
            [20.00] => 8.0
            [25.00] => 10.5
        )

    [2] => Array
        (
            [15.00] => 2.0
            [20.00] => 5.0
            [25.00] => 2.5
        )

    [4] => Array
        (
            [15.00] => 6.0
            [25.00] => 4.0
            [30.00] => 6.0
        )
)

In order it should be: 4, 9 and 2

Body:
<?
for ($i=1;$i<=count($arr);$i++)
for ($j=$i+1;$j<=count($arr) - 1;$j++)
 if ($arr[$i]['15.00'] > $arr[$j]['15.00']) {
   $tmp = $arr[$i];
   $arr[$i] = $arr[$j];
   $arr[$j] = $tmp
 }
?>


问:
Leaflet: Map container not found
I have the below react class which fetches the geolocation through the browser.

I am mapping a leaflet map. I want to geolocation to be an input to the setView, for such that the map "zooms" into the region of the client browser location.

Here's the react class:

```<code>    import React from 'react';
    import L from 'leaflet';
    import countries from './countries.js';

    var Worldmap = React.createClass({

        render: function() {

            let geolocation = [];

            navigator.geolocation.getCurrentPosition(function(position) {
                let lat = position.coords.latitude;
                let lon = position.coords.longitude;
                geolocation.push(lat, lon);
                locationCode()
            });

            function locationCode() {
                if(geolocation.length <= 0)
                    geolocation.push(0, 0);
            }

            let map = L.map('leafletmap').setView(geolocation, 3);

            L.geoJSON(countries, {
                style: function(feature) {
                    return {
                        fillColor: "#FFBB78",
                        fillOpacity: 0.6,
                        stroke: true,
                        color: "black",
                        weight: 2
                    };
                }
            }).bindPopup(function(layer) {
                return layer.feature.properties.name;
            }).addTo(map);

            return (
                <div id="leafletmap" style={{width: "100%", height: "800px" }}/>
            )
        }
    });

    export default Worldmap
</code>```

It's called in a main file where the HTML is rendered as <WorldMap />.

I get the error Uncaught Error: Map container not found. when loading the page. Looking around, usually it would be because the map is trying to be displayed in a div before being provided values((gelocation, 3) in this case). However, it shouldn't display it before being returned from the render function below.

What could the issue be?

Printing out the geolocation in the console correctly fetches the coordinates, so that doesn't seem to be the issue.

答:
I hope this helps if you are using Angular:</p>

```<code>const container = document.getElementById('map')
if(container) {
    // code to render map here...
}
</code>```

Title: Leaflet: Map container not found

Body:
I have the below react class which fetches the geolocation through the browser.

I am mapping a leaflet map. I want to geolocation to be an input to the setView, for such that the map "zooms" into the region of the client browser location.

Here's the react class:

    import React from 'react';
    import L from 'leaflet';
    import countries from './countries.js';

    var Worldmap = React.createClass({

        render: function() {

            let geolocation = [];

            navigator.geolocation.getCurrentPosition(function(position) {
                let lat = position.coords.latitude;
                let lon = position.coords.longitude;
                geolocation.push(lat, lon);
                locationCode()
            });

            function locationCode() {
                if(geolocation.length <= 0)
                    geolocation.push(0, 0);
            }

            let map = L.map('leafletmap').setView(geolocation, 3);

            L.geoJSON(countries, {
                style: function(feature) {
                    return {
                        fillColor: "#FFBB78",
                        fillOpacity: 0.6,
                        stroke: true,
                        color: "black",
                        weight: 2
                    };
                }
            }).bindPopup(function(layer) {
                return layer.feature.properties.name;
            }).addTo(map);

            return (

            )
        }
    });

    export default Worldmap

It's called in a main file where the HTML is rendered as <WorldMap />.

I get the error Uncaught Error: Map container not found. when loading the page. Looking around, usually it would be because the map is trying to be displayed in a div before being provided values((gelocation, 3) in this case). However, it shouldn't display it before being returned from the render function below.

What could the issue be?

Printing out the geolocation in the console correctly fetches the coordinates, so that doesn't seem to be the issue.

Body:
I hope this helps if you are using Angular:

const container = document.getElementById('map')
if(container) {
    // code to render map here...
}


问:
Nginx caching with Azure Storage Blob
Local caching works fine, however trying to cache files server by the Azure Blob Storage is not working.

Each request the Signature changes and it returns no caching headers.
I think its because of this signature at the end? Anyone got an idea how to surpass that?

```<code>https://accountname.blob.core.windows.net/static/assets/js/jquery331.min.js?se=2020-02-10T15%3A06%3A35Z&sp=r&sv=2019-09-28&sr=b&sig=<Signature>
</code>```

Below is my nginx config. It mostly based on this one = https://serversforhackers.com/c/nginx-caching

```<code>upstream app {
    server web:8000;
}

proxy_cache_path ./cache keys_zone=one:10m loader_threshold=300 loader_files=200;
proxy_cache_key "$scheme$request_method$host$request_uri";

# Expires map
map $sent_http_content_type $expires {
    default                    off;
    text/css                   max;
    application/javascript     max;
    ~image/                    max;
}

server {

    include mime.types;

    listen 80;
    listen [::]:80;
    root /usr/src/application/;
    index /usr/src/application/main/;

    gzip on;
    gzip_comp_level 2;
    gzip_http_version 1.0;
    gzip_proxied any;
    gzip_min_length 1100;
    gzip_buffers 16 8k;
    gzip_types text/plain text/html text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript script text/script;
    gzip_disable "MSIE [1-6].(?!.*SV1)";
    gzip_vary on;

    location / {
        proxy_pass http://app;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_redirect off;

    }

    location /staticfiles/ {
        proxy_cache one;
        proxy_buffering on;
        add_header X-Proxy-Cache $upstream_cache_status;
        proxy_http_version      1.1;
        proxy_set_header        Connection "";
        proxy_set_header        Authorization '';
        proxy_set_header        Host https://accountname.blob.core.windows.net/static;
        proxy_pass              https://accountname.blob.core.windows.net;
    }

    location /media/ {
        proxy_http_version      1.1;
        proxy_set_header        Connection "";
        proxy_set_header        Authorization '';
        proxy_set_header        Host https://accountname.blob.core.windows.net/media;
        proxy_pass              https://accountname.blob.core.windows.net;
    }

    # cache.appcache, your document html and data
    location ~* \.(?:manifest|appcache|html?|xml|json)$ {

      expires -1;
    }

    # Feed
    location ~* \.(?:rss|atom)$ {

      expires 1h;
      add_header Cache-Control "public";
    }

    # Media: images, icons, video, audio, HTC
    location ~* \.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc)$ {

      expires 1M;
      access_log off;
      add_header Cache-Control "public";
    }

    # CSS and Javascript
    location ~* \.(?:css|js)$ {

      expires 1y;
      access_log off;
      add_header Cache-Control "public";
    }

  location /media/ {

    alias /usr/src/application/main/media;
  }

    proxy_connect_timeout 300s;
    proxy_read_timeout 300s;
    proxy_next_upstream error timeout http_502;
    location /index/ {
        alias /usr/src/application/main/;
    }
}
</code>```

答:
So I've found what caused the query strings. We are using django storages, in that the option for a variable AZURE_URL_EXPIRATION_SECS is possible which appends a query string.
As of now caching works without CDN. However, I am surprised that with the CDN active and rules set to ignore query strings no caching was happening.</p>

Title: Nginx caching with Azure Storage Blob

Body:
Local caching works fine, however trying to cache files server by the Azure Blob Storage is not working.

Each request the Signature changes and it returns no caching headers.
I think its because of this signature at the end? Anyone got an idea how to surpass that?

https://accountname.blob.core.windows.net/static/assets/js/jquery331.min.js?se=2020-02-10T15%3A06%3A35Z&sp=r&sv=2019-09-28&sr=b&sig=<Signature>

Below is my nginx config. It mostly based on this one = https://serversforhackers.com/c/nginx-caching

upstream app {
    server web:8000;
}

proxy_cache_path ./cache keys_zone=one:10m loader_threshold=300 loader_files=200;
proxy_cache_key "$scheme$request_method$host$request_uri";

# Expires map
map $sent_http_content_type $expires {
    default                    off;
    text/css                   max;
    application/javascript     max;
    ~image/                    max;
}

server {

    include mime.types;

    listen 80;
    listen [::]:80;
    root /usr/src/application/;
    index /usr/src/application/main/;

    gzip on;
    gzip_comp_level 2;
    gzip_http_version 1.0;
    gzip_proxied any;
    gzip_min_length 1100;
    gzip_buffers 16 8k;
    gzip_types text/plain text/html text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript script text/script;
    gzip_disable "MSIE [1-6].(?!.*SV1)";
    gzip_vary on;

    location / {
        proxy_pass http://app;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_redirect off;

    }

    location /staticfiles/ {
        proxy_cache one;
        proxy_buffering on;
        add_header X-Proxy-Cache $upstream_cache_status;
        proxy_http_version      1.1;
        proxy_set_header        Connection "";
        proxy_set_header        Authorization '';
        proxy_set_header        Host https://accountname.blob.core.windows.net/static;
        proxy_pass              https://accountname.blob.core.windows.net;
    }

    location /media/ {
        proxy_http_version      1.1;
        proxy_set_header        Connection "";
        proxy_set_header        Authorization '';
        proxy_set_header        Host https://accountname.blob.core.windows.net/media;
        proxy_pass              https://accountname.blob.core.windows.net;
    }

    # cache.appcache, your document html and data
    location ~* \.(?:manifest|appcache|html?|xml|json)$ {

      expires -1;
    }

    # Feed
    location ~* \.(?:rss|atom)$ {

      expires 1h;
      add_header Cache-Control "public";
    }

    # Media: images, icons, video, audio, HTC
    location ~* \.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc)$ {

      expires 1M;
      access_log off;
      add_header Cache-Control "public";
    }

    # CSS and Javascript
    location ~* \.(?:css|js)$ {

      expires 1y;
      access_log off;
      add_header Cache-Control "public";
    }

  location /media/ {

    alias /usr/src/application/main/media;
  }

    proxy_connect_timeout 300s;
    proxy_read_timeout 300s;
    proxy_next_upstream error timeout http_502;
    location /index/ {
        alias /usr/src/application/main/;
    }
}


问:
Flutter I can't release or debug when I add Connectivity
SOLUTION for this problem
I deleted the JDK 13. I installed JDK 8.
I gave the environment variable for the Flutter SDK. in user variables
flutter
C: \ flutter \ bin

I gave the environment variable for JAVA_HOME. in system variables
JAVA_HOME
C: \ Program Files \ Java \ jdk1.8.0_241

Then I accepted Android licenses with cmd.
(flutter doctor --android-licenses)

Now I can use flutter connectivity.
The problem is solved. Thank you.

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

I cannot debug or release to my app when I add Connectivity to my app's pubspec.yaml

Flutter Doctor

```<code>[flutter] flutter doctor -v
[√] Flutter (Channel stable, v1.12.13+hotfix.8, on Microsoft Windows [Version 10.0.18363.657], locale tr-TR)
    • Flutter version 1.12.13+hotfix.8 at C:\flutter
    • Framework revision 0b8abb4724 (9 days ago), 2020-02-11 11:44:36 -0800
    • Engine revision e1e6ced81d
    • Dart version 2.7.0

[!] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
    • Android SDK at C:\Users\Faruk Aydin\AppData\Local\Android\sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-29, build-tools 29.0.2
    • Java binary at: C:\Program Files\Java\jdk-13.0.2\bin\java
    • Java version Java(TM) SE Runtime Environment (build 13.0.2+8)
    X Android license status unknown.
      Try re-installing or updating your Android SDK Manager.
      See https://developer.android.com/studio/#downloads or visit https://flutter.dev/setup/#android-setup for detailed instructions.

[!] Android Studio (version 3.5)
    • Android Studio at C:\Program Files\Android\Android Studio
    • Flutter plugin version 42.1.1
    • Dart plugin version 191.8593
    X Unable to find bundled Java version.
    • Try updating or re-installing Android Studio.

[√] VS Code (version 1.42.1)
    • VS Code at C:\Users\Faruk Aydin\AppData\Local\Programs\Microsoft VS Code
    • Flutter extension version 3.8.1

[√] Connected device (1 available)
    • Redmi 8A • f12007c00606 • android-arm • Android 9 (API 28)

! Doctor found issues in 2 categories.
exit code 0
</code>```

答:
You need to create a global file under your username in Mac. Just create a .bashprofile file as described bellow:

Open to see location and locate your flutter sdk inside.

Body:
SOLUTION for this problem
I deleted the JDK 13. I installed JDK 8.
I gave the environment variable for the Flutter SDK. in user variables
flutter
C: \ flutter \ bin

I gave the environment variable for JAVA_HOME. in system variables
JAVA_HOME
C: \ Program Files \ Java \ jdk1.8.0_241

Then I accepted Android licenses with cmd.
(flutter doctor --android-licenses)

Now I can use flutter connectivity.
The problem is solved. Thank you.

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

I cannot debug or release to my app when I add Connectivity to my app's pubspec.yaml

Flutter Doctor

[flutter] flutter doctor -v
[√] Flutter (Channel stable, v1.12.13+hotfix.8, on Microsoft Windows [Version 10.0.18363.657], locale tr-TR)
    • Flutter version 1.12.13+hotfix.8 at C:\flutter
    • Framework revision 0b8abb4724 (9 days ago), 2020-02-11 11:44:36 -0800
    • Engine revision e1e6ced81d
    • Dart version 2.7.0

[!] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
    • Android SDK at C:\Users\Faruk Aydin\AppData\Local\Android\sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-29, build-tools 29.0.2
    • Java binary at: C:\Program Files\Java\jdk-13.0.2\bin\java
    • Java version Java(TM) SE Runtime Environment (build 13.0.2+8)
    X Android license status unknown.
      Try re-installing or updating your Android SDK Manager.
      See https://developer.android.com/studio/#downloads or visit https://flutter.dev/setup/#android-setup for detailed instructions.

[!] Android Studio (version 3.5)
    • Android Studio at C:\Program Files\Android\Android Studio
    • Flutter plugin version 42.1.1
    • Dart plugin version 191.8593
    X Unable to find bundled Java version.
    • Try updating or re-installing Android Studio.

[√] VS Code (version 1.42.1)
    • VS Code at C:\Users\Faruk Aydin\AppData\Local\Programs\Microsoft VS Code
    • Flutter extension version 3.8.1

[√] Connected device (1 available)
    • Redmi 8A • f12007c00606 • android-arm • Android 9 (API 28)

! Doctor found issues in 2 categories.
exit code 0


问:
addClass to every div with data-attribute tag
How can I add CSS classes like widget-00, widget-01 etc. to each of these divs via jQuery?

```<code><div class="mdl-form  mdl-color--white mdl-shadow--2dp mdl-cell mdl-grid mdl-cell--12-col" data-widget-id="00">
<div class="mdl-form  mdl-color--white mdl-shadow--2dp mdl-cell mdl-grid mdl-cell--12-col" data-widget-id="01">
<div class="mdl-form  mdl-color--white mdl-shadow--2dp mdl-cell mdl-grid mdl-cell--12-col" data-widget-id="02">
<div class="mdl-form  mdl-color--white mdl-shadow--2dp mdl-cell mdl-grid mdl-cell--12-col" data-widget-id="03">
</code>```

答:
This is how I would do it. Similar to Prateik's answer but I would select it by the attribute and not by one class of the div.

That way you also make sure that the data-widget-id attribute is present without having to check for it.

$(document).ready(function(){
  $('[data-widget-id]').each(function(){
    $(this).addClass("widget-" + $(this).data('widget-id'));
  })
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="mdl-form  mdl-color--white mdl-shadow--2dp mdl-cell mdl-grid mdl-cell--12-col" data-widget-id="00"></div>
<div class="mdl-form  mdl-color--white mdl-shadow--2dp mdl-cell mdl-grid mdl-cell--12-col" data-widget-id="01"></div>
<div class="mdl-form  mdl-color--white mdl-shadow--2dp mdl-cell mdl-grid mdl-cell--12-col" data-widget-id="02"></div>
<div class="mdl-form  mdl-color--white mdl-shadow--2dp mdl-cell mdl-grid mdl-cell--12-col" data-widget-id="03"></div></code>```

Body:
This is how I would do it. Similar to Prateik's answer but I would select it by the attribute and not by one class of the div.

That way you also make sure that the data-widget-id attribute is present without having to check for it.

$(document).ready(function(){
  $('[data-widget-id]').each(function(){
    $(this).addClass("widget-" + $(this).data('widget-id'));
  })
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="mdl-form  mdl-color--white mdl-shadow--2dp mdl-cell mdl-grid mdl-cell--12-col" data-widget-id="00"></div>
<div class="mdl-form  mdl-color--white mdl-shadow--2dp mdl-cell mdl-grid mdl-cell--12-col" data-widget-id="01"></div>
<div class="mdl-form  mdl-color--white mdl-shadow--2dp mdl-cell mdl-grid mdl-cell--12-col" data-widget-id="02"></div>
<div class="mdl-form  mdl-color--white mdl-shadow--2dp mdl-cell mdl-grid mdl-cell--12-col" data-widget-id="03"></div>


问:
checking if a nested column exists in spark
lets we have following following

```<code>case class SubRecord(x: Int)
case class ArrayElement(foo: String, bar: Int, vals: Array[Double])
case class Record(
  an_array: Array[Int], a_map: Map[String, String],
  a_struct: SubRecord, an_array_of_structs: Array[ArrayElement])

val df = sc.parallelize(Seq(
  Record(Array(1, 2, 3), Map("foo" -> "bar"), SubRecord(1),
         Array(
           ArrayElement("foo", 1, Array(1.0, 2.0, 2.0)),
           ArrayElement("bar", 2, Array(3.0, 4.0, 5.0)))),
  Record(Array(4, 5, 6), Map("foz" -> "baz"), SubRecord(2),
         Array(ArrayElement("foz", 3, Array(5.0, 6.0)),
               ArrayElement("baz", 4, Array(7.0, 8.0))))
)).toDF

</code>```

Here we get value if a column(path) exists, other wise we get an exception,
But i want to get value like 'NOT_FOUND' in this case, is it possible???

Expected output

答:
I found a better solution, we can just safeCol() in place of col() method

```<code> def DataFrameSafeCol(df:DataFrame)(path: String): Column = {
      Try(df(path)) match {
        case Success(x) => x
        case Failure(_) => lit("NOT_FOUND")
      }
  }

</code>```

Then we can use as below

```<code>val safeCol=DataFrameSafeCol(df)(_) // function currying
df.select(safeCol("column_name")).show
</code>```

Body:
lets we have following following

case class SubRecord(x: Int)
case class ArrayElement(foo: String, bar: Int, vals: Array[Double])
case class Record(
  an_array: Array[Int], a_map: Map[String, String],
  a_struct: SubRecord, an_array_of_structs: Array[ArrayElement])

val df = sc.parallelize(Seq(
  Record(Array(1, 2, 3), Map("foo" -> "bar"), SubRecord(1),
         Array(
           ArrayElement("foo", 1, Array(1.0, 2.0, 2.0)),
           ArrayElement("bar", 2, Array(3.0, 4.0, 5.0)))),
  Record(Array(4, 5, 6), Map("foz" -> "baz"), SubRecord(2),
         Array(ArrayElement("foz", 3, Array(5.0, 6.0)),
               ArrayElement("baz", 4, Array(7.0, 8.0))))
)).toDF

Here we get value if a column(path) exists, other wise we get an exception,
But i want to get value like 'NOT_FOUND' in this case, is it possible???

Expected output

Body:
I found a better solution, we can just safeCol() in place of col() method

 def DataFrameSafeCol(df:DataFrame)(path: String): Column = {
      Try(df(path)) match {
        case Success(x) => x
        case Failure(_) => lit("NOT_FOUND")
      }
  }

Then we can use as below

val safeCol=DataFrameSafeCol(df)(_) // function currying
df.select(safeCol("column_name")).show


问:
How do I know if the 'usedforsecurity' flag is supported by hashlib.md5?
When I run the following on my Macbook, I get the error:

```<code>>>> import hashlib
>>> hashlib.md5(usedforsecurity=False)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: openssl_md5() takes no keyword arguments
</code>```

But when I run it on my Linux box, it works!

```<code>>>> import hashlib
>>> hashlib.md5(usedforsecurity=False)
<md5 HASH object @ 0x7f763c1375d0>
</code>```

My problem is, I need to run some safe, non-security related code on my FIPS enabled system (such as managing a cache of user requests which hashes the user query as an MD5 string). Using the usedforsecurity flag prevents a FIPs exception.

This works fine, except when I want to test my code on my Macbook. My Macbook's "libcrypto" library apparently doesn't support this usedforsecurity flag. Is there a good way to detect if the underlying C bindings behind hashlib.md5 support this  flag or not?

答:
I ran into the same problem with FIPS and hashlib.md5(), but I was able to do this to check:

```<code>>>> import hashlib, inspect
>>> inspect.getargspec(hashlib.new)
ArgSpec(args=['name', 'string', 'usedforsecurity'], varargs=None, keywords=None, defaults=('', True))
</code>```

On Python 3+, getargspec is deprecated, so getfullargspec should be used instead. The data structure is similar, but usedforsecurity is in the kwonlyargs field now.

```<code>>>> inspect.getfullargspec(hashlib.new)
FullArgSpec(args=['name', 'data'], varargs=None, varkw='kwargs', defaults=(b'',), kwonlyargs=['usedforsecurity'], kwonlydefaults={'usedforsecurity': True}, annotations={})
</code>```

Body:
When I run the following on my Macbook, I get the error:

>>> import hashlib
>>> hashlib.md5(usedforsecurity=False)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: openssl_md5() takes no keyword arguments

But when I run it on my Linux box, it works!

>>> import hashlib
>>> hashlib.md5(usedforsecurity=False)
<md5 HASH object @ 0x7f763c1375d0>

My problem is, I need to run some safe, non-security related code on my FIPS enabled system (such as managing a cache of user requests which hashes the user query as an MD5 string). Using the usedforsecurity flag prevents a FIPs exception.

This works fine, except when I want to test my code on my Macbook. My Macbook's "libcrypto" library apparently doesn't support this usedforsecurity flag. Is there a good way to detect if the underlying C bindings behind hashlib.md5 support this  flag or not?

Body:
I ran into the same problem with FIPS and hashlib.md5(), but I was able to do this to check:

>>> import hashlib, inspect
>>> inspect.getargspec(hashlib.new)
ArgSpec(args=['name', 'string', 'usedforsecurity'], varargs=None, keywords=None, defaults=('', True))

On Python 3+, getargspec is deprecated, so getfullargspec should be used instead. The data structure is similar, but usedforsecurity is in the kwonlyargs field now.

>>> inspect.getfullargspec(hashlib.new)
FullArgSpec(args=['name', 'data'], varargs=None, varkw='kwargs', defaults=(b'',), kwonlyargs=['usedforsecurity'], kwonlydefaults={'usedforsecurity': True}, annotations={})


问:
Django - linking multiple ChoiceField's
I need to have user inputing his address by first select country, then city, then district, and then sub-district.  How do I best implement this functionality in django Form?  The models are similar to this:</p>

```<code>Class Country(models.Model):
    name = models.CharField(max_length=30)

Class City(models.Model):
    name = models.CharField(max_length=30)
    country = models.ForeignKey(Country)

Class District(models.Model):
    name = models.CharField(max_length=30)
    city = models.ForeignKey(City)

Class Subdistrict(models.Model):
    name = models.CharField(max_length=30)
    district = models.ForeignKey(District)
</code>```

答: You can use Filtering results based on the value of other fields in the form from django-autocomplete-light</p>

Title: Django - linking multiple ChoiceField's

Body:
I need to have user inputing his address by first select country, then city, then district, and then sub-district.  How do I best implement this functionality in django Form?  The models are similar to this:

Class Country(models.Model):
    name = models.CharField(max_length=30)

Class City(models.Model):
    name = models.CharField(max_length=30)
    country = models.ForeignKey(Country)

Class District(models.Model):
    name = models.CharField(max_length=30)
    city = models.ForeignKey(City)

Class Subdistrict(models.Model):
    name = models.CharField(max_length=30)
    district = models.ForeignKey(District)


问:
Python Flask can't host Backend on my machine
So I wanted to host my backed on my machine for my website.
The Problem is I can't the frontend works perfectly but the Flask backend doesn't.
The backend works when I use localhost or my local ip to access it.
But doesn't work when I try to use it with the link :

https://desktop-1234567.1234567890qwert.myfritz.net:3182
(this one is fake)
It displays this error message :

So basically it says that it can't find the backend the Flask backend also dosen't react.
Even though I port forwarded the port 3182 with my-Fritz :

I also turned off Windows Firewall and it dosen't help

My Fritz is basically a free service from avm for Firtz-Box users (that's my Router)
It generates a sub domain where all your traffic is routed through this is useful since this url is static.

I tried it with a simpler backend :

```<code>from flask import Flask

app = Flask(__name__)

@app.route("/test")
def test():
    return "<h1>Test</h1>"

if __name__ == "__main__":
    app.run(
        debug=False,
        host='0.0.0.0',
        port=3182,
        threaded=True
    )
</code>```

and it also doesn't work it gives the same error message as above.
I also tried using waitress to host this simple app but it also won't work.

It has to be Flask since I can access my Frontend with the link on port 80 and 443.

I'm on Windows 10 and I hope somebody knows why this isn't working.

So yeah pleas help me I searched and it appears that no one had this exact problem before (But you never know on Stack Overflow)

答:
Well I found out what the issue is.
The Issue is that I used "0.0.0.0" as the host parameter to run the app.
This tells flask to use IPV4, however I looked in to it and found out that "My Fritz" uses IPV6 so I just had to change the host parameter to use IPV6 by replacing "0.0.0.0" with ::.

That's it hope it helps, if anyone runs into the same issue as me.

Body:
So I wanted to host my backed on my machine for my website.
The Problem is I can't the frontend works perfectly but the Flask backend doesn't.
The backend works when I use localhost or my local ip to access it.
But doesn't work when I try to use it with the link :

https://desktop-1234567.1234567890qwert.myfritz.net:3182
(this one is fake)
It displays this error message :

So basically it says that it can't find the backend the Flask backend also dosen't react.
Even though I port forwarded the port 3182 with my-Fritz :

I also turned off Windows Firewall and it dosen't help

My Fritz is basically a free service from avm for Firtz-Box users (that's my Router)
It generates a sub domain where all your traffic is routed through this is useful since this url is static.

I tried it with a simpler backend :

from flask import Flask

app = Flask(__name__)

@app.route("/test")
def test():
    return "
Test
"

if __name__ == "__main__":
    app.run(
        debug=False,
        host='0.0.0.0',
        port=3182,
        threaded=True
    )

and it also doesn't work it gives the same error message as above.
I also tried using waitress to host this simple app but it also won't work.

It has to be Flask since I can access my Frontend with the link on port 80 and 443.

I'm on Windows 10 and I hope somebody knows why this isn't working.

So yeah pleas help me I searched and it appears that no one had this exact problem before (But you never know on Stack Overflow)


问:
Replace value in a node retaining the XML Structure using XSLT
I have a requirement where I need to replace the value of a node based on the attributes with a different value, retaining the original XML structure. Basically, I need to copy the whole XML only by replacing certain values when specific attributes are encountered in the original XML.

Below is a sample XML before transformation and after transformation.

Original XML:

```<code><root>
    <body>
        <node_level1>
            <node_level2>
                <node_level3>
                    <value animal="cat">Munchkin</value>
                </node_level3>
                <node_level3>
                    <value animal="cat">Turkish Angora</value>
                </node_level3>
                <node_level3>
                    <value animal="cat">La Perm</value>
                </node_level3>
            </node_level2>
            <node_level2>
                <node_level3>
                    <node_level4>
                        <value animal="dog">Siberian Husky</value>
                    </node_level4>
                    <node_level4>
                        <value animal="dog">Pug</value>
                    </node_level4>
                    <node_level4>
                        <value animal="dog">Beagle</value>
                    </node_level4>
                </node_level3>
            </node_level2>
        </node_level1>
    </body>
</root>
</code>```

After transforming the data using XSLT, I need the XML as below:

```<code><root>
    <body>
        <node_level1>
            <node_level2>
                <node_level3>
                    <value animal="cat">Cat Family</value>
                </node_level3>
                <node_level3>
                    <value animal="cat">Cat Family</value>
                </node_level3>
                <node_level3>
                    <value animal="cat">Cat Family</value>
                </node_level3>
            </node_level2>
            <node_level2>
                <node_level3>
                    <node_level4>
                        <value animal="dog">Dog Family</value>
                    </node_level4>
                    <node_level4>
                        <value animal="dog">Dog Family</value>
                    </node_level4>
                    <node_level4>
                        <value animal="dog">Dog Family</value>
                    </node_level4>
                </node_level3>
            </node_level2>
        </node_level1>
    </body>
</root>
</code>```

Here is the code that works for specified attributes, I need to generalize it.

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" exclude-result-prefixes="xsl" version="2.0">
    <xsl:template match="/">
        <root>
            <xsl:for-each select="//*[value[@animal = 'cat']]">
                <xsl:copy>
                    <xsl:value-of select="@*"/>
                    <xsl:value-of select="'Cat Family'"/>
                </xsl:copy>
            </xsl:for-each>
        </root>
    </xsl:template>
</xsl:stylesheet>
</code>```

答:
In XSLT 3 you can declare the identity transformation with an xsl:mode on-no-match="shallow-copy" as the default processing and then match on value[@animal]:

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="#all"
    version="3.0">

  <xsl:mode on-no-match="shallow-copy"/>

  <xsl:template match="value[@animal]">
      <xsl:copy>
          <xsl:apply-templates select="@*"/>
          <xsl:value-of select="@animal || ' family'"/>
      </xsl:copy>
  </xsl:template>

</xsl:stylesheet>
</code>```

https://xsltfiddle.liberty-development.net/94Acsmj

Body:
I have a requirement where I need to replace the value of a node based on the attributes with a different value, retaining the original XML structure. Basically, I need to copy the whole XML only by replacing certain values when specific attributes are encountered in the original XML.

Below is a sample XML before transformation and after transformation.

Original XML:

<root>

        <node_level1>
            <node_level2>
                <node_level3>
                    <value animal="cat">Munchkin</value>
                </node_level3>
                <node_level3>
                    <value animal="cat">Turkish Angora</value>
                </node_level3>
                <node_level3>
                    <value animal="cat">La Perm</value>
                </node_level3>
            </node_level2>
            <node_level2>
                <node_level3>
                    <node_level4>
                        <value animal="dog">Siberian Husky</value>
                    </node_level4>
                    <node_level4>
                        <value animal="dog">Pug</value>
                    </node_level4>
                    <node_level4>
                        <value animal="dog">Beagle</value>
                    </node_level4>
                </node_level3>
            </node_level2>
        </node_level1>

</root>

After transforming the data using XSLT, I need the XML as below:

<root>

        <node_level1>
            <node_level2>
                <node_level3>
                    <value animal="cat">Cat Family</value>
                </node_level3>
                <node_level3>
                    <value animal="cat">Cat Family</value>
                </node_level3>
                <node_level3>
                    <value animal="cat">Cat Family</value>
                </node_level3>
            </node_level2>
            <node_level2>
                <node_level3>
                    <node_level4>
                        <value animal="dog">Dog Family</value>
                    </node_level4>
                    <node_level4>
                        <value animal="dog">Dog Family</value>
                    </node_level4>
                    <node_level4>
                        <value animal="dog">Dog Family</value>
                    </node_level4>
                </node_level3>
            </node_level2>
        </node_level1>

</root>

Here is the code that works for specified attributes, I need to generalize it.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" exclude-result-prefixes="xsl" version="2.0">
    <xsl:template match="/">
        <root>
            <xsl:for-each select="//*[value[@animal = 'cat']]">
                <xsl:copy>
                    <xsl:value-of select="@*"/>
                    <xsl:value-of select="'Cat Family'"/>
                </xsl:copy>
            </xsl:for-each>
        </root>
    </xsl:template>
</xsl:stylesheet>

Body:
In XSLT 3 you can declare the identity transformation with an xsl:mode on-no-match="shallow-copy" as the default processing and then match on value[@animal]:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="#all"
    version="3.0">

  <xsl:mode on-no-match="shallow-copy"/>

  <xsl:template match="value[@animal]">
      <xsl:copy>
          <xsl:apply-templates select="@*"/>
          <xsl:value-of select="@animal || ' family'"/>
      </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

https://xsltfiddle.liberty-development.net/94Acsmj


问:
Exception in Application start method. OpenJFX 13 with Maven
i tried to start a new project using OpenJFX modular with Maven. I followed this: https://openjfx.io/openjfx-docs/ (Go to JavaFX with Maven -> Modular with Maven) but gets an Exceptetion in Application start method.

Error:

```<code>Exception in Application start method
java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
    at java.base/java.lang.Thread.run(Thread.java:830)
Caused by: java.lang.IllegalStateException: Location is not set.
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2459)
    at javafx.fxml/javafx.fxml.FXMLLoader.load(FXMLLoader.java:2435)
    at org.openjfx/org.openjfx.App.loadFXML(App.java:31)
    at org.openjfx/org.openjfx.App.start(App.java:20)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
    at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
    ... 1 more
Exception running application org.openjfx.App
</code>```

pom.xml:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.openjfx</groupId>
    <artifactId>Oblig1</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-controls</artifactId>
            <version>13</version>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-fxml</artifactId>
            <version>13</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.0</version>
            <configuration>
                <release>11</release>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-maven-plugin</artifactId>
            <version>0.0.1</version>
            <configuration>
                <mainClass>org.openjfx.App</mainClass>
            </configuration>
        </plugin>
        </plugins>
    </build>
</project>
</code>```

app.java

```<code>package org.openjfx;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

import java.io.IOException;

/**
 * JavaFX App
 */
public class App extends Application {

    private static Scene scene;

    @Override
    public void start(Stage stage) throws IOException {
        scene = new Scene(loadFXML("/org.openjfx/primary"));
        stage.setScene(scene);
        stage.show();
    }

    static void setRoot(String fxml) throws IOException {
        scene.setRoot(loadFXML(fxml));
    }

    private static Parent loadFXML(String fxml) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(fxml + ".fxml"));
        return fxmlLoader.load();
    }

    public static void main(String[] args) {
        launch();
    }

}
</code>```

primary.fxml:

```<code><?import javafx.scene.layout.VBox?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.Button?>
<?import javafx.geometry.Insets?>

<VBox alignment="CENTER" spacing="20.0" xmlns="http://javafx.com/javafx/8.0.171"
xmlns:fx="http://javafx.com/fxml/1" fx:controller="kristoffer.PrimaryController">
   <children>
      <Label text="Primary View" />
      <Button fx:id="primaryButton" text="Switch to Secondary View" onAction="#switchToSecondary"/>
   </children>
   <padding>
      <Insets bottom="20.0" left="20.0" right="20.0" top="20.0" />
   </padding>
</VBox>
</code>```

PrimaryController.java:

```<code>package org.openjfx;

import java.io.IOException;
import javafx.fxml.FXML;

public class PrimaryController {

}
</code>```

secondary.fxml:

```<code><?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.layout.VBox?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.Button?>
<?import javafx.geometry.Insets?>

<VBox alignment="CENTER" spacing="20.0"
xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1"
fx:controller="org.openjfx.SecondaryController">
    <children>
        <Label text="Secondary View" />
        <Button fx:id="secondaryButton" text="Switch to Primary View"
onAction="#switchToPrimary" />
    </children>
    <padding>
        <Insets bottom="20.0" left="20.0" right="20.0" top="20.0" />
    </padding>
</VBox>
</code>```

SecondaryController.java:

```<code>package org.openjfx;

import java.io.IOException;
import javafx.fxml.FXML;

public class SecondaryController {

    @FXML
    private void switchToPrimary() throws IOException {
        App.setRoot("PrimaryController");
    }
}
</code>```

Directorary:

```<code>    src
        main
            java
                org.openjfx
                    App.java
                    PrimaryController.java
                    SecondaryController.java
            resources
                org.openjfx
                    primary.fxml
                    secondary.fxml
</code>```

jar -tf Oblig1.jar:

I think it might be something with the link in the FXML Loader, i have seen other people having similar issues(like this one), but my directorary has the resources folder unlike theirs. Any help is appreciated, thanks.

答:
The error message

java.lang.IllegalStateException: Location is not set.
```

<p>means that the URL you provided to the <code>FXMLLoader</code> constructor was <code>null</code>. The <code>Class.getResource(...)</code> method silently returns <code>null</code> if the resource specified cannot be found.</p>

<p>This is happening because the resource name you're providing to your <code>loadFXML</code> method, and ultimately to <code>App.class.getResource(...)</code> is incorrect. The value you provide to <code>Class.getResource(...)</code> is a <em>resource name</em>, the details of which are documented here.</p>

<p>The resource name is formed from "the fully qualified name of the package of the class, but convert
all periods (.) to slashes (/)" (see below). It's impossible to know exactly what's going wrong without at least seeing the structure of the buid folder and/or jar file, but it should probably be</p>

```scene = new Scene(loadFXML("/org/openjfx/primary"));
```

<p>Since your FXML files and the class from which you are executing this code are in the same package, you can probably also get away with just</p>

```scene = new Scene(loadFXML("primary"));
```

<p>Some pertinent parts of that documentation:</p>

<blockquote>
  <p><strong>Resources, names, and contexts</strong></p>

  <p>A resource is identified by a string consisting of a sequence of
  substrings, delimited by slashes (/), followed by a resource name.
  Each substring must be a valid Java identifier. The resource name is
  of the form shortName or shortName.extension. Both shortName and
  extension must be Java identifiers.</p>

  <p>The name of a resource is independent of the Java implementation; in
  particular, the path separator is always a slash (/). However, the
  Java implementation controls the details of how the contents of the
  resource are mapped into a file, database, or other object containing
  the actual resource.</p>

  <p>The interpretation of a resource name is relative to a class loader
  instance. Methods implemented by the ClassLoader class do this
  interpretation.</p>

  <p>...</p>

  <p><strong>Resource Names</strong></p>

  <p>A common convention for the name of a resource used by a class is to
  use the fully qualified name of the package of the class, but convert
  all periods (.) to slashes (/), and add a resource name of the form
  name.extension. To support this, and to simplify handling the details
  of system classes (for which getClassLoader returns null), the class
  Class provides two convenience methods that call the appropriate
  methods in ClassLoader.</p>

  <p>The resource name given to a Class method may have an initial starting
  "/" that identifies it as an "absolute" name. Resource names that do
  not start with a "/" are "relative".</p>
</blockquote>

<p>So <code>"/org.openjfx/primary"</code> is not a valid resource name, because <code>"org.openjfx"</code> is not a valid Java identifier.</p>

<p>In your structure, note that <code>org.openjfx</code> is not a <em>folder</em>, but a <em>package</em>. The IDE and build tool will convert this to a folder hierarchy on the file system and ultimately inside the jar file, with the package-subpackage structure being replaced by folders and subfolders. So in your source code structure, you will have a "java" folder with "org" subfolder, "openjfx" sub-subfolder, and in there the Java source files for classes in the <code>org.openjfx</code> package. In the "resources" folder, you will also have an "org" subfolder, an "openjfx" sub-subfolder, and in there the resource files you created (including the FMXL file).</p>

<p>The build tool (either Maven or just your IDE) recognizes specific source folders; these are configured in your case to include "java" and "resources". When the app is built, the union of the structures under the source folders is recreated in the build target; here this just results in a single <code>org</code> folder and <code>openjfx</code> subfolder. Any Java source files are compiled to class files; any other files are merely copied. Finally the whole thing is bundled into a jar file (which is essentially just a zip archive).</p>

<p>If you find the jar file on the file system (by default Maven will place it in a folder called "target", which is alongside your "src" folder), you can examine its contents with</p>

<pre class="lang-none prettyprint-override"><code>jar -tf Oblig1-1.0-SNAPSHOT.jar
</code>```

(I think that Oblig1-1.0-SNAPSHOT.jar is the name of the generated jar file, but obviously adjust that if necessary). You should see the folder structure I outlined, and the output should include

/org/openjfx/App.class
/org/openjfx/PrimaryController.class
/org/openjfx/SecondaryController.class
/org/openjfx/primary.fxml
/org/openjfx/secondary.fxml
```

(The same structure should exist under the target/classes folder, though again the folder naming and location depends on your Maven setup.)

As an aside, you really should not use org.openjfx for your own package names and Maven group ids; use something specific to yourself or your organization.

Body:
i tried to start a new project using OpenJFX modular with Maven. I followed this: https://openjfx.io/openjfx-docs/ (Go to JavaFX with Maven -> Modular with Maven) but gets an Exceptetion in Application start method.

Error:

Exception in Application start method
java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
    at java.base/java.lang.Thread.run(Thread.java:830)
Caused by: java.lang.IllegalStateException: Location is not set.
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2459)
    at javafx.fxml/javafx.fxml.FXMLLoader.load(FXMLLoader.java:2435)
    at org.openjfx/org.openjfx.App.loadFXML(App.java:31)
    at org.openjfx/org.openjfx.App.start(App.java:20)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
    at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
    ... 1 more
Exception running application org.openjfx.App

pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.openjfx</groupId>
    <artifactId>Oblig1</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-controls</artifactId>
            <version>13</version>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-fxml</artifactId>
            <version>13</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.0</version>
            <configuration>
                <release>11</release>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-maven-plugin</artifactId>
            <version>0.0.1</version>
            <configuration>
                <mainClass>org.openjfx.App</mainClass>
            </configuration>
        </plugin>
        </plugins>
    </build>
</project>

app.java

package org.openjfx;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

import java.io.IOException;

/**
 * JavaFX App
 */
public class App extends Application {

    private static Scene scene;

    @Override
    public void start(Stage stage) throws IOException {
        scene = new Scene(loadFXML("/org.openjfx/primary"));
        stage.setScene(scene);
        stage.show();
    }

    static void setRoot(String fxml) throws IOException {
        scene.setRoot(loadFXML(fxml));
    }

    private static Parent loadFXML(String fxml) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(fxml + ".fxml"));
        return fxmlLoader.load();
    }

    public static void main(String[] args) {
        launch();
    }

}

primary.fxml:

<?import javafx.scene.layout.VBox?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.Button?>
<?import javafx.geometry.Insets?>

<VBox alignment="CENTER" spacing="20.0" xmlns="http://javafx.com/javafx/8.0.171"
xmlns:fx="http://javafx.com/fxml/1" fx:controller="kristoffer.PrimaryController">
   <children>

      <Button fx:id="primaryButton" text="Switch to Secondary View" onAction="#switchToSecondary"/>
   </children>
   <padding>
      <Insets bottom="20.0" left="20.0" right="20.0" top="20.0" />
   </padding>
</VBox>

PrimaryController.java:

package org.openjfx;

import java.io.IOException;
import javafx.fxml.FXML;

public class PrimaryController {

}

secondary.fxml:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.layout.VBox?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.Button?>
<?import javafx.geometry.Insets?>

<VBox alignment="CENTER" spacing="20.0"
xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1"
fx:controller="org.openjfx.SecondaryController">
    <children>

        <Button fx:id="secondaryButton" text="Switch to Primary View"
onAction="#switchToPrimary" />
    </children>
    <padding>
        <Insets bottom="20.0" left="20.0" right="20.0" top="20.0" />
    </padding>
</VBox>

SecondaryController.java:

package org.openjfx;

import java.io.IOException;
import javafx.fxml.FXML;

public class SecondaryController {

    @FXML
    private void switchToPrimary() throws IOException {
        App.setRoot("PrimaryController");
    }
}

Directorary:

    src
        main
            java
                org.openjfx
                    App.java
                    PrimaryController.java
                    SecondaryController.java
            resources
                org.openjfx
                    primary.fxml
                    secondary.fxml

jar -tf Oblig1.jar:

I think it might be something with the link in the FXML Loader, i have seen other people having similar issues(like this one), but my directorary has the resources folder unlike theirs. Any help is appreciated, thanks.

Body:
The error message

java.lang.IllegalStateException: Location is not set.

means that the URL you provided to the FXMLLoader constructor was null. The Class.getResource(...) method silently returns null if the resource specified cannot be found.

This is happening because the resource name you're providing to your loadFXML method, and ultimately to App.class.getResource(...) is incorrect. The value you provide to Class.getResource(...) is a resource name, the details of which are documented here.

The resource name is formed from "the fully qualified name of the package of the class, but convert
all periods (.) to slashes (/)" (see below). It's impossible to know exactly what's going wrong without at least seeing the structure of the buid folder and/or jar file, but it should probably be

scene = new Scene(loadFXML("/org/openjfx/primary"));

Since your FXML files and the class from which you are executing this code are in the same package, you can probably also get away with just

scene = new Scene(loadFXML("primary"));

Some pertinent parts of that documentation:

Resources, names, and contexts

A resource is identified by a string consisting of a sequence of
  substrings, delimited by slashes (/), followed by a resource name.
  Each substring must be a valid Java identifier. The resource name is
  of the form shortName or shortName.extension. Both shortName and
  extension must be Java identifiers.

The name of a resource is independent of the Java implementation; in
  particular, the path separator is always a slash (/). However, the
  Java implementation controls the details of how the contents of the
  resource are mapped into a file, database, or other object containing
  the actual resource.

The interpretation of a resource name is relative to a class loader
  instance. Methods implemented by the ClassLoader class do this
  interpretation.

...

Resource Names

A common convention for the name of a resource used by a class is to
  use the fully qualified name of the package of the class, but convert
  all periods (.) to slashes (/), and add a resource name of the form
  name.extension. To support this, and to simplify handling the details
  of system classes (for which getClassLoader returns null), the class
  Class provides two convenience methods that call the appropriate
  methods in ClassLoader.

The resource name given to a Class method may have an initial starting
  "/" that identifies it as an "absolute" name. Resource names that do
  not start with a "/" are "relative".

So "/org.openjfx/primary" is not a valid resource name, because "org.openjfx" is not a valid Java identifier.

In your structure, note that org.openjfx is not a folder, but a package. The IDE and build tool will convert this to a folder hierarchy on the file system and ultimately inside the jar file, with the package-subpackage structure being replaced by folders and subfolders. So in your source code structure, you will have a "java" folder with "org" subfolder, "openjfx" sub-subfolder, and in there the Java source files for classes in the org.openjfx package. In the "resources" folder, you will also have an "org" subfolder, an "openjfx" sub-subfolder, and in there the resource files you created (including the FMXL file).

The build tool (either Maven or just your IDE) recognizes specific source folders; these are configured in your case to include "java" and "resources". When the app is built, the union of the structures under the source folders is recreated in the build target; here this just results in a single org folder and openjfx subfolder. Any Java source files are compiled to class files; any other files are merely copied. Finally the whole thing is bundled into a jar file (which is essentially just a zip archive).

If you find the jar file on the file system (by default Maven will place it in a folder called "target", which is alongside your "src" folder), you can examine its contents with

jar -tf Oblig1-1.0-SNAPSHOT.jar

(I think that Oblig1-1.0-SNAPSHOT.jar is the name of the generated jar file, but obviously adjust that if necessary). You should see the folder structure I outlined, and the output should include

/org/openjfx/App.class
/org/openjfx/PrimaryController.class
/org/openjfx/SecondaryController.class
/org/openjfx/primary.fxml
/org/openjfx/secondary.fxml

(The same structure should exist under the target/classes folder, though again the folder naming and location depends on your Maven setup.)

As an aside, you really should not use org.openjfx for your own package names and Maven group ids; use something specific to yourself or your organization.