问:
Gradle Sync Fails With "UnhandledIsstesReporter"
Here's an issue I had after Android Studio Upgrade From 3.4 to 3.5. A previously working project now fails with the following error:

Gradle sync failed: com/android/tools/idea/gradle/project/sync/issues/UnhandledIssuesReporter (wrong name: com/android/tools/idea/gradle/project/sync/issues/UnhandledIsstesReporter)

Error Log Exception:

```<code>[SearchTask]   WARN - ConfigurableExtensionPointUtil - ignore deprecated groupId: language for id: preferences.language.Kotlin.scripting
[SearchTask]   WARN - ConfigurableExtensionPointUtil - use other group instead of unexpected one: project.propCompiler
[SearchTask]   WARN - ConfigurableExtensionPointUtil - use other group instead of unexpected one: project.propCompiler
[entQueue-0]   WARN - un.AndroidRunConfigurationBase - Can't get application ID: Android module missing
[entQueue-0]   WARN - un.AndroidRunConfigurationBase - Can't get application ID: Android module missing
[entQueue-0]   WARN - un.AndroidRunConfigurationBase - Can't get application ID: Android module missing
[entQueue-0]   WARN - un.AndroidRunConfigurationBase - Can't get application ID: Android module missing
[ thread 22]   INFO - e.project.sync.GradleSyncState - Started setup of project 'My Application 3'.
[entQueue-0]   INFO - idea.project.IndexingSuspender - Consuming IndexingSuspender activation event: SETUP_STARTED
[ thread 22]   INFO - ule.android.SdkModuleSetupStep - Set Android SDK 'Android API 28 Platform' (C:\Users\Jonathan\AppData\Local\Android\sdk) to module 'app'
[entQueue-0]   INFO - pl.ProjectRootManagerComponent - project roots have changed
[ thread 22]   INFO - e.project.sync.GradleSyncState - Gradle sync failed: com/android/tools/idea/gradle/project/sync/issues/UnhandledIssuesReporter (wrong name: com/android/tools/idea/gradle/project/sync/issues/UnhandledIsstesReporter) (29 s 205 ms)
[ating Pool]   WARN - .idea.model.MergedManifestInfo - getMergedManifest failed Manifest merger failed : Attribute intent-filter#action:name:android.accounts.AccountAuthenticator@priority at AndroidManifest.xml requires a placeholder substitution but no value for <priority> is provided.
[entQueue-0]   WARN - .idea.model.MergedManifestInfo - getMergedManifest failed Manifest merger failed : Attribute intent-filter#action:name:android.accounts.AccountAuthenticator@priority at AndroidManifest.xml requires a placeholder substitution but no value for <priority> is provided.
[entQueue-0]   WARN - un.AndroidRunConfigurationBase - Can't get application ID: Android module missing
[entQueue-0]   WARN - un.AndroidRunConfigurationBase - Can't get application ID: Android module missing
[entQueue-0]   WARN - un.AndroidRunConfigurationBase - Can't get application ID: Android module missing
[entQueue-0]   WARN - un.AndroidRunConfigurationBase - Can't get application ID: Android module missing
[ thread 25]   INFO - .diagnostic.PerformanceWatcher - Pushing properties took 9ms; general responsiveness: ok; EDT responsiveness: ok
[ thread 22]   WARN - ject.sync.ng.SyncResultHandler - Gradle sync failed
    java.lang.NoClassDefFoundError: com/android/tools/idea/gradle/project/sync/issues/UnhandledIssuesReporter (wrong name: com/android/tools/idea/gradle/project/sync/issues/UnhandledIsstesReporter)
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:642)
        at com.intellij.util.lang.UrlClassLoader._defineClass(UrlClassLoader.java:306)
        at com.intellij.util.lang.UrlClassLoader.defineClass(UrlClassLoader.java:302)
        at com.intellij.util.lang.UrlClassLoader._findClass(UrlClassLoader.java:271)
        at com.intellij.ide.plugins.cl.PluginClassLoader.loadClassInsideSelf(PluginClassLoader.java:183)
        at com.intellij.ide.plugins.cl.PluginClassLoader.tryLoadingClass(PluginClassLoader.java:136)
        at com.intellij.ide.plugins.cl.PluginClassLoader.loadClass(PluginClassLoader.java:49)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        at com.android.tools.idea.gradle.project.sync.ng.SyncResultHandler.setUpProject(SyncResultHandler.java:156)
        at com.android.tools.idea.gradle.project.sync.ng.SyncResultHandler.onSyncFinished(SyncResultHandler.java:86)
        at com.android.tools.idea.gradle.project.sync.ng.SyncResultHandler.lambda$onCompoundSyncModels$5(SyncResultHandler.java:267)
        at com.intellij.openapi.application.impl.ApplicationImpl$1.run(ApplicationImpl.java:312)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
</code>```

I updated the gradle plugin version from 3.4.2 to 3.5.0 in my project's gradle file:

```<code>buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
</code>```

I then got another error:

Gradle sync failed: Minimum supported Gradle version is 5.4.1. Current version is 5.1.1. If using the gradle wrapper, try editing the distributionUrl in ...\StudioProjects\BlueView\gradle\wrapper\gradle-wrapper.properties to gradle-5.4.1-all.zip

So I did what it suggested and modified my gradle-wrapper.properties files to:

```<code>distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip
</code>```

I synced project with the gradle files and after the new version of gradle had been downloaded, It failed again with the very same error:

Gradle sync failed: com/android/tools/idea/gradle/project/sync/issues/UnhandledIssuesReporter (wrong name: com/android/tools/idea/gradle/project/sync/issues/UnhandledIsstesReporter)

I invalidated cache and restarted Android Studio. Still No Luck.

Finally, I tried creating a brand new project. Build also failed on the brand new project template.

I searched my hard drive for this mysterious UnhandledIsstesReporter file and didn't find it.

答:
First, PLEASE MAKE SURE THAT YOU DON'T MIND OVERWRITING YOUR WORK or have saved it somewhere.

Then run:

git reset --hard origin master

(or whatever it's called), in my case it was:

git reset --hard origin develop

Also, this is how I solved my problem. Your problem may have a different solution.

Here are a few other potential solutions to your problem. You may try it in any order you want though:

Build -> Clean Project

Remove emulator as Owais mentioned.

Restart Android Studio

File -> Sync Project with Gradle Files

File -> Sync with System files

File -> invalidate Caches/Restart... -> Invalidate and Restart. It usually takes 10 to 30 minutes but solves a lot of similar problems (not this one in my case though).

Uninstall Android Studio and install it again as Jon mentioned.

Body:
Here's an issue I had after Android Studio Upgrade From 3.4 to 3.5. A previously working project now fails with the following error:

Gradle sync failed: com/android/tools/idea/gradle/project/sync/issues/UnhandledIssuesReporter (wrong name: com/android/tools/idea/gradle/project/sync/issues/UnhandledIsstesReporter)

Error Log Exception:

[SearchTask]   WARN - ConfigurableExtensionPointUtil - ignore deprecated groupId: language for id: preferences.language.Kotlin.scripting
[SearchTask]   WARN - ConfigurableExtensionPointUtil - use other group instead of unexpected one: project.propCompiler
[SearchTask]   WARN - ConfigurableExtensionPointUtil - use other group instead of unexpected one: project.propCompiler
[entQueue-0]   WARN - un.AndroidRunConfigurationBase - Can't get application ID: Android module missing
[entQueue-0]   WARN - un.AndroidRunConfigurationBase - Can't get application ID: Android module missing
[entQueue-0]   WARN - un.AndroidRunConfigurationBase - Can't get application ID: Android module missing
[entQueue-0]   WARN - un.AndroidRunConfigurationBase - Can't get application ID: Android module missing
[ thread 22]   INFO - e.project.sync.GradleSyncState - Started setup of project 'My Application 3'.
[entQueue-0]   INFO - idea.project.IndexingSuspender - Consuming IndexingSuspender activation event: SETUP_STARTED
[ thread 22]   INFO - ule.android.SdkModuleSetupStep - Set Android SDK 'Android API 28 Platform' (C:\Users\Jonathan\AppData\Local\Android\sdk) to module 'app'
[entQueue-0]   INFO - pl.ProjectRootManagerComponent - project roots have changed
[ thread 22]   INFO - e.project.sync.GradleSyncState - Gradle sync failed: com/android/tools/idea/gradle/project/sync/issues/UnhandledIssuesReporter (wrong name: com/android/tools/idea/gradle/project/sync/issues/UnhandledIsstesReporter) (29 s 205 ms)
[ating Pool]   WARN - .idea.model.MergedManifestInfo - getMergedManifest failed Manifest merger failed : Attribute intent-filter#action:name:android.accounts.AccountAuthenticator@priority at AndroidManifest.xml requires a placeholder substitution but no value for <priority> is provided.
[entQueue-0]   WARN - .idea.model.MergedManifestInfo - getMergedManifest failed Manifest merger failed : Attribute intent-filter#action:name:android.accounts.AccountAuthenticator@priority at AndroidManifest.xml requires a placeholder substitution but no value for <priority> is provided.
[entQueue-0]   WARN - un.AndroidRunConfigurationBase - Can't get application ID: Android module missing
[entQueue-0]   WARN - un.AndroidRunConfigurationBase - Can't get application ID: Android module missing
[entQueue-0]   WARN - un.AndroidRunConfigurationBase - Can't get application ID: Android module missing
[entQueue-0]   WARN - un.AndroidRunConfigurationBase - Can't get application ID: Android module missing
[ thread 25]   INFO - .diagnostic.PerformanceWatcher - Pushing properties took 9ms; general responsiveness: ok; EDT responsiveness: ok
[ thread 22]   WARN - ject.sync.ng.SyncResultHandler - Gradle sync failed
    java.lang.NoClassDefFoundError: com/android/tools/idea/gradle/project/sync/issues/UnhandledIssuesReporter (wrong name: com/android/tools/idea/gradle/project/sync/issues/UnhandledIsstesReporter)
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:642)
        at com.intellij.util.lang.UrlClassLoader._defineClass(UrlClassLoader.java:306)
        at com.intellij.util.lang.UrlClassLoader.defineClass(UrlClassLoader.java:302)
        at com.intellij.util.lang.UrlClassLoader._findClass(UrlClassLoader.java:271)
        at com.intellij.ide.plugins.cl.PluginClassLoader.loadClassInsideSelf(PluginClassLoader.java:183)
        at com.intellij.ide.plugins.cl.PluginClassLoader.tryLoadingClass(PluginClassLoader.java:136)
        at com.intellij.ide.plugins.cl.PluginClassLoader.loadClass(PluginClassLoader.java:49)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        at com.android.tools.idea.gradle.project.sync.ng.SyncResultHandler.setUpProject(SyncResultHandler.java:156)
        at com.android.tools.idea.gradle.project.sync.ng.SyncResultHandler.onSyncFinished(SyncResultHandler.java:86)
        at com.android.tools.idea.gradle.project.sync.ng.SyncResultHandler.lambda$onCompoundSyncModels$5(SyncResultHandler.java:267)
        at com.intellij.openapi.application.impl.ApplicationImpl$1.run(ApplicationImpl.java:312)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)

I updated the gradle plugin version from 3.4.2 to 3.5.0 in my project's gradle file:

buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

I then got another error:

Gradle sync failed: Minimum supported Gradle version is 5.4.1. Current version is 5.1.1. If using the gradle wrapper, try editing the distributionUrl in ...\StudioProjects\BlueView\gradle\wrapper\gradle-wrapper.properties to gradle-5.4.1-all.zip

So I did what it suggested and modified my gradle-wrapper.properties files to:

distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip

I synced project with the gradle files and after the new version of gradle had been downloaded, It failed again with the very same error:

Gradle sync failed: com/android/tools/idea/gradle/project/sync/issues/UnhandledIssuesReporter (wrong name: com/android/tools/idea/gradle/project/sync/issues/UnhandledIsstesReporter)

I invalidated cache and restarted Android Studio. Still No Luck.

Finally, I tried creating a brand new project. Build also failed on the brand new project template.

I searched my hard drive for this mysterious UnhandledIsstesReporter file and didn't find it.


来源: stackexchange

问:
Don't start every fragment at once in ViewPager
I have implemented a View Pager in my app. It slides between to fragments, the problem is, even if only the first fragment is being display, the other fragment gets created.
That causes problems because, in the second fragment I'm displaying a Loading Bar and this way it shows in the first fragment instead of the second one.

This is my ViewPager code:

```<code>
class FragmentViewPagerAdapter(fm: FragmentManager) : FragmentStatePagerAdapter(fm) {

    override fun getItem(position: Int): Fragment {
        if (position == 0){
            return VentFragment()
        }
        return ConversationsFragment()
    }

    override fun getCount(): Int {
        return 2
    }

}
</code>```

In the second fragment I call the Loading Bar this way in onCreateView:

```<code> loading = ProgressDialog(context)

        loading.setTitle(getString(R.string.loading))
        loading.setMessage(getString(R.string.fetching_your_data))
        loading.setCanceledOnTouchOutside(false)
        loading.show()
</code>```

Is it because of the context? I can't seem to find the bug...

答:
So it is possible to do "lazy loading" of UI data with ViewPager (I do), so that data and the loading bar is only displayed when the page is selected.

Update:

I would recommend you move to ViewPager2 as ViewPager2 correctly supports the Fragment lifecycle unlike ViewPager.

This means you can easily update your placeholder (or start your loading bar) in the Fragment's onResume Method

I've just done a full example using ViewPager2 using the ViewPager method, see for https://stackoverflow.com/a/60253406/2373819  (Update2 has full example and is similar to how you can do it if you still want to use ViewPager)

Note both methods will cause a screen update to display the correct (latest) data, this can be during the transition or with ViewPager2 and onResume as soon as the transition has finished, but then you can have the incorrect old data or have a second screen update to have the correct up to date data.

ContentLicense: CC BY-SA 4.0

Body:
I have implemented a View Pager in my app. It slides between to fragments, the problem is, even if only the first fragment is being display, the other fragment gets created.
That causes problems because, in the second fragment I'm displaying a Loading Bar and this way it shows in the first fragment instead of the second one.

This is my ViewPager code:

class FragmentViewPagerAdapter(fm: FragmentManager) : FragmentStatePagerAdapter(fm) {

    override fun getItem(position: Int): Fragment {
        if (position == 0){
            return VentFragment()
        }
        return ConversationsFragment()
    }

    override fun getCount(): Int {
        return 2
    }

}

In the second fragment I call the Loading Bar this way in onCreateView:

 loading = ProgressDialog(context)

        loading.setTitle(getString(R.string.loading))
        loading.setMessage(getString(R.string.fetching_your_data))
        loading.setCanceledOnTouchOutside(false)
        loading.show()

Is it because of the context? I can't seem to find the bug...


问:
Cannot mkdir /data/db (or sudo mkdir /data/db) for mongodb. Haven't been able to find an answer here that works
I get this when I run mongod -

```<code>Johns-MacBook-Pro:~ johnnyringo506$ mongod
2020-02-18T17:12:06.439-0500 I  CONTROL  [main] Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'
2020-02-18T17:12:06.446-0500 I  CONTROL  [initandlisten] MongoDB starting : pid=24840 port=27017 dbpath=/data/db 64-bit host=Johns-MacBook-Pro.local
2020-02-18T17:12:06.446-0500 I  CONTROL  [initandlisten] db version v4.2.3
2020-02-18T17:12:06.446-0500 I  CONTROL  [initandlisten] git version: 6874650b362138df74be53d366bbefc321ea32d4
2020-02-18T17:12:06.446-0500 I  CONTROL  [initandlisten] allocator: system
2020-02-18T17:12:06.446-0500 I  CONTROL  [initandlisten] modules: none
2020-02-18T17:12:06.446-0500 I  CONTROL  [initandlisten] build environment:
2020-02-18T17:12:06.446-0500 I  CONTROL  [initandlisten]     distarch: x86_64
2020-02-18T17:12:06.446-0500 I  CONTROL  [initandlisten]     target_arch: x86_64
2020-02-18T17:12:06.446-0500 I  CONTROL  [initandlisten] options: {}
2020-02-18T17:12:06.447-0500 I  STORAGE  [initandlisten] exception in initAndListen: NonExistentPath: Data directory /data/db not found., terminating
2020-02-18T17:12:06.447-0500 I  NETWORK  [initandlisten] shutdown: going to close listening sockets...
2020-02-18T17:12:06.447-0500 I  -        [initandlisten] Stopping further Flow Control ticket acquisitions.
2020-02-18T17:12:06.447-0500 I  CONTROL  [initandlisten] now exiting
2020-02-18T17:12:06.447-0500 I  CONTROL  [initandlisten] shutting down with code:100
</code>```

And then I receive a "mkdir: /data: No such file or directory" when I try to create it

答:
Try to run with sudo, the issue might be with permissions
or create directory with this command sudo mkdir -p /data/db then restart MongoDB service</p>

Body:
I get this when I run mongod -

Johns-MacBook-Pro:~ johnnyringo506$ mongod
2020-02-18T17:12:06.439-0500 I  CONTROL  [main] Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'
2020-02-18T17:12:06.446-0500 I  CONTROL  [initandlisten] MongoDB starting : pid=24840 port=27017 dbpath=/data/db 64-bit host=Johns-MacBook-Pro.local
2020-02-18T17:12:06.446-0500 I  CONTROL  [initandlisten] db version v4.2.3
2020-02-18T17:12:06.446-0500 I  CONTROL  [initandlisten] git version: 6874650b362138df74be53d366bbefc321ea32d4
2020-02-18T17:12:06.446-0500 I  CONTROL  [initandlisten] allocator: system
2020-02-18T17:12:06.446-0500 I  CONTROL  [initandlisten] modules: none
2020-02-18T17:12:06.446-0500 I  CONTROL  [initandlisten] build environment:
2020-02-18T17:12:06.446-0500 I  CONTROL  [initandlisten]     distarch: x86_64
2020-02-18T17:12:06.446-0500 I  CONTROL  [initandlisten]     target_arch: x86_64
2020-02-18T17:12:06.446-0500 I  CONTROL  [initandlisten] options: {}
2020-02-18T17:12:06.447-0500 I  STORAGE  [initandlisten] exception in initAndListen: NonExistentPath: Data directory /data/db not found., terminating
2020-02-18T17:12:06.447-0500 I  NETWORK  [initandlisten] shutdown: going to close listening sockets...
2020-02-18T17:12:06.447-0500 I  -        [initandlisten] Stopping further Flow Control ticket acquisitions.
2020-02-18T17:12:06.447-0500 I  CONTROL  [initandlisten] now exiting
2020-02-18T17:12:06.447-0500 I  CONTROL  [initandlisten] shutting down with code:100

And then I receive a "mkdir: /data: No such file or directory" when I try to create it


问:
ffmpeg: no matches found: -map[v]
I am trying to merge 4 videos in split-screen with their audio together.

```<code>./ffmpeg -i ./clip11.mp4 -i ./clip21.mp4 -i ./clip31.mp4 -i ./clip41.mp4  -filter_complex "[0:v][1:v]hstack=inputs=2[top];[2:v][3:v]hstack=inputs=2[bottom];[top][bottom]vstack=inputs=2[v];amerge=inputs=4[a]" -map[v] -map[a] ./split21.mp4
</code>```

I try tried and run the code, but it shows this as an error.

```<code>zsh: no matches found: -map[v]
</code>```

I don't know whether my machine cannot configure the "map" because it happens the same thing when I tried to do "concat". I do not know what else to change about. I typed it out on the latest Mac, but surprisingly my friend that have an older version of Mac got the code working. Help.

答:
You are missing some spaces to separate the option from the value.

Use -map "[v]" -map "[a]".

The quotes are not necessary in this case but will allow you to use spaces in your label names if desired.

Title: ffmpeg: no matches found: -map[v]

Body:
I am trying to merge 4 videos in split-screen with their audio together.

./ffmpeg -i ./clip11.mp4 -i ./clip21.mp4 -i ./clip31.mp4 -i ./clip41.mp4  -filter_complex "[0:v][1:v]hstack=inputs=2[top];[2:v][3:v]hstack=inputs=2[bottom];[top][bottom]vstack=inputs=2[v];amerge=inputs=4[a]" -map[v] -map[a] ./split21.mp4

I try tried and run the code, but it shows this as an error.

zsh: no matches found: -map[v]

I don't know whether my machine cannot configure the "map" because it happens the same thing when I tried to do "concat". I do not know what else to change about. I typed it out on the latest Mac, but surprisingly my friend that have an older version of Mac got the code working. Help.


问:
Python run multiple background loops independently
In one of my projects, I need to run three different database updater functions at different intervals.
For instance, function one needs to run every 30 seconds, function two needs to run every 60 seconds and function 3 every 5 minutes (notably due to API call restrictions).

I've been trying to achieve this in python, looking up every possible solution but I cannot seem to find anything that works for my use case. I am rather fresh in python.

Here is (somewhat) what I have, using asyncio.

```<code>import asyncio

def updater1(url1, url2, time):
    print(f"Doing my thing here every {time} seconds")

def updater2(url1, url2, time):
    print(f"Doing my thing here every {time} seconds")

def updater3(url, time):
    print(f"Doing my thing here every {time} seconds")

async def func1():
    updater1(rankUrl, statsUrl, 30)
    await asyncio.sleep(30)

async def func2():
    updater2(rankUrl, statsUrl, 60)
    await asyncio.sleep(60)

async def func3():
    updater3(url, 300)
    await asyncio.sleep(300)

# Initiate async loops
while True:
    asyncio.run(func1())
    asyncio.run(func2())
    asyncio.run(func3())
</code>```

The issue is that these tasks run one after each other, while what I am trying to achieve is that they run independently from each other, with a start time when the script is initiated, and respective to their own individual loop times

Any idea on how this could be done is much appreciated - I am open to new concepts and ideas if you have any for me to explore :)

答:
Don't use asyncio.run() on individual coroutines, as async.run() is itself not asynchronous. The call to asyncio.run() won't return until the funcN() coroutine is done.

Create a single top-level coroutine that then runs others as tasks:

```<code>async def main():
    task1 = asyncio.create_task(func1())
    task2 = asyncio.create_task(func2())
    task3 = asyncio.create_task(func3())

    await asyncio.wait([task1, task2, task3])
</code>```

The above kicks off three independent tasks, then waits for all 3 to complete.

Body:
In one of my projects, I need to run three different database updater functions at different intervals.
For instance, function one needs to run every 30 seconds, function two needs to run every 60 seconds and function 3 every 5 minutes (notably due to API call restrictions).

I've been trying to achieve this in python, looking up every possible solution but I cannot seem to find anything that works for my use case. I am rather fresh in python.

Here is (somewhat) what I have, using asyncio.

import asyncio

def updater1(url1, url2, time):
    print(f"Doing my thing here every {time} seconds")

def updater2(url1, url2, time):
    print(f"Doing my thing here every {time} seconds")

def updater3(url, time):
    print(f"Doing my thing here every {time} seconds")

async def func1():
    updater1(rankUrl, statsUrl, 30)
    await asyncio.sleep(30)

async def func2():
    updater2(rankUrl, statsUrl, 60)
    await asyncio.sleep(60)

async def func3():
    updater3(url, 300)
    await asyncio.sleep(300)

# Initiate async loops
while True:
    asyncio.run(func1())
    asyncio.run(func2())
    asyncio.run(func3())

The issue is that these tasks run one after each other, while what I am trying to achieve is that they run independently from each other, with a start time when the script is initiated, and respective to their own individual loop times

Any idea on how this could be done is much appreciated - I am open to new concepts and ideas if you have any for me to explore :)

Body:
Don't use asyncio.run() on individual coroutines, as async.run() is itself not asynchronous. The call to asyncio.run() won't return until the funcN() coroutine is done.

Create a single top-level coroutine that then runs others as tasks:

async def main():
    task1 = asyncio.create_task(func1())
    task2 = asyncio.create_task(func2())
    task3 = asyncio.create_task(func3())

    await asyncio.wait([task1, task2, task3])

The above kicks off three independent tasks, then waits for all 3 to complete.


问:
How to provide a global .htpassword file to multiple Docker Swarm Stacks?
I am running around 20 service stacks on a docker swarm host that all expose their individual https frontends which are protected by basic auth using Traefik (same username and password for all services).

I would love to centrally manage the .htpassword file or username/passwordHash, so that if there is a requirement for a password change, I can do it once and it will affect all services immediately or after redeployment. I am using Swarmpit to orchestrate Docker Swarm.

I looked into Docker Secrets and Docker Configs but both seem to be immutable if actively used by a running service. I also thought about environment variables, but I cannot really find my way through.

How should I go about this?

答:
If you don't want to use docker secrets/configs for this then you can do the following (for Traefik 2.1):

First add a dynamic configuration directory to your traefik config

```<code>--providers.file.directory=/my/path/to/dynamic/conf
--providers.file.watch=true
</code>```

The mount a volume in this location and create your middleware file (middlewares.yml for example)

```<code>http:
  middlewares:
    defaultAuth:
      basicAuth:
        users:
          - "admin:$apr1$13r2hvw0$Oljx0V7CwdQJG7WxLWRVt0" # correcthorsebatterystaple
</code>```

Now you can edit your users array and traefik will pick the changes automatically.

To use the middleware just reference it on your docker labels:

```<code>- traefik.http.routers.<my_router_name>.middlewares=defaultAuth@file
</code>```

For traefik 1.x you could add the following label

```<code>- traefik.frontend.auth.basic.usersFile=/path/.htpasswd
</code>```

Then update the file when needed and restart the affected services. I don't use 1.x anymore so that one isn't tested.

Body:
If you don't want to use docker secrets/configs for this then you can do the following (for Traefik 2.1):

First add a dynamic configuration directory to your traefik config

--providers.file.directory=/my/path/to/dynamic/conf
--providers.file.watch=true

The mount a volume in this location and create your middleware file (middlewares.yml for example)

http:
  middlewares:
    defaultAuth:
      basicAuth:
        users:
          - "admin:$apr1$13r2hvw0$Oljx0V7CwdQJG7WxLWRVt0" # correcthorsebatterystaple

Now you can edit your users array and traefik will pick the changes automatically.

To use the middleware just reference it on your docker labels:

- traefik.http.routers.<my_router_name>.middlewares=defaultAuth@file

For traefik 1.x you could add the following label

- traefik.frontend.auth.basic.usersFile=/path/.htpasswd

Then update the file when needed and restart the affected services. I don't use 1.x anymore so that one isn't tested.


问:
Creating iPhone compatible video with ffmpeg from an image and MP3 file
I have the following command that I have used to create an MP4 video file from an image and an MP3 file, it plays fine in a Chrome browser on desktop and on an Android phone - but it doesn't work on an iPhone 10. Do I need some extra codec or setting to make this compatible for iPhone? Should I be converting this into a MPEG file instead for wider compatibility?

```<code>ffmpeg -loop 1 -i 6f4aa5dfefc4dd32186f41315ad9d1e2-0.png -i "music.mp3" -c:v libx264 -tune stillimage -c:a aac -b:a 192k -pix_fmt yuv420p -shortest aa-image0.mp4
</code>```

Here are the ffprobe details for the input MP3 file used to create the MP4 video and also the ffprobe for that output file:

```<code>Input #0, wav, from 'download0.mp3':
  Duration: 00:00:35.94, bitrate: 384 kb/s
    Stream #0:0: Audio: pcm_s16le ([1][0][0][0] / 0x0001), 24000 Hz, 1 channels, s16, 384 kb/s
</code>```

```<code>Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'aa-image0.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf58.22.100
  Duration: 00:00:38.76, start: 0.000000, bitrate: 505 kb/s
    Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 2664x1498 [SAR 1:1 DAR 1332:749], 367 kb/s, 25 fps, 25 tbr, 12800 tbn, 50 tbc (default)
    Metadata:
      handler_name    : VideoHandler
    Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 48000 Hz, mono, fltp, 138 kb/s (default)
    Metadata:
      handler_name    : SoundHandler
</code>```

The video seems to play on the iPhone, but the audio seems to start/stop constantly. Like it is a streaming issue (even though it is not). Maybe an MP3 encoding issue when I created the video?

Here are the test files I have used and created (any iPhone users will likely find the MP4 will not play the audio in the video properly):

https://ffmpeg-iphone-issue.netlify.com/tesla.jpg

https://ffmpeg-iphone-issue.netlify.com/tesla.mp3

https://ffmpeg-iphone-issue.netlify.com/tesla.mp4 (OUTPUT - Created from the 2 files above)

In summary, two FFmpeg commands are required:

1) Used to create iPhone/iOS compatible videos in FFmpeg from an image and MP3 (A slight modification to the command at the top of the page)

and

2) An FFmpeg command that could be used to fix or re-encode the video above so that it works on iPhone (A new command incorporating the parts so it works with iPhone and then to rebuild and fix the "broken" video. In a similar fashion to this video where he fixes a broken video https://www.youtube.com/watch?v=2FhmbKKh6mc [command in Youtube description])

答:
Maybe try to use the ipod mp4 muxer using -f ipod:

ffmpeg -loop 1 -i 6f4aa5dfefc4dd32186f41315ad9d1e2-0.png -i "music.mp3" -c:v libx264 -tune stillimage -c:a aac -b:a 192k -pix_fmt yuv420p -shortest -f ipod aa-image0.mp4

```

Body:
I have the following command that I have used to create an MP4 video file from an image and an MP3 file, it plays fine in a Chrome browser on desktop and on an Android phone - but it doesn't work on an iPhone 10. Do I need some extra codec or setting to make this compatible for iPhone? Should I be converting this into a MPEG file instead for wider compatibility?

ffmpeg -loop 1 -i 6f4aa5dfefc4dd32186f41315ad9d1e2-0.png -i "music.mp3" -c:v libx264 -tune stillimage -c:a aac -b:a 192k -pix_fmt yuv420p -shortest aa-image0.mp4

Here are the ffprobe details for the input MP3 file used to create the MP4 video and also the ffprobe for that output file:

Input #0, wav, from 'download0.mp3':
  Duration: 00:00:35.94, bitrate: 384 kb/s
    Stream #0:0: Audio: pcm_s16le ([1][0][0][0] / 0x0001), 24000 Hz, 1 channels, s16, 384 kb/s

Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'aa-image0.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf58.22.100
  Duration: 00:00:38.76, start: 0.000000, bitrate: 505 kb/s
    Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 2664x1498 [SAR 1:1 DAR 1332:749], 367 kb/s, 25 fps, 25 tbr, 12800 tbn, 50 tbc (default)
    Metadata:
      handler_name    : VideoHandler
    Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 48000 Hz, mono, fltp, 138 kb/s (default)
    Metadata:
      handler_name    : SoundHandler

The video seems to play on the iPhone, but the audio seems to start/stop constantly. Like it is a streaming issue (even though it is not). Maybe an MP3 encoding issue when I created the video?

Here are the test files I have used and created (any iPhone users will likely find the MP4 will not play the audio in the video properly):

https://ffmpeg-iphone-issue.netlify.com/tesla.jpg

https://ffmpeg-iphone-issue.netlify.com/tesla.mp3

https://ffmpeg-iphone-issue.netlify.com/tesla.mp4 (OUTPUT - Created from the 2 files above)

In summary, two FFmpeg commands are required:

1) Used to create iPhone/iOS compatible videos in FFmpeg from an image and MP3 (A slight modification to the command at the top of the page)

and

2) An FFmpeg command that could be used to fix or re-encode the video above so that it works on iPhone (A new command incorporating the parts so it works with iPhone and then to rebuild and fix the "broken" video. In a similar fashion to this video where he fixes a broken video https://www.youtube.com/watch?v=2FhmbKKh6mc [command in Youtube description])


问:
UITableView support for right to left languages
how to change a table view layout to be from right to left (including its transition to a detail view: the transition must also be from right to left) ?
thanx in advance.</p>

答: For view transition you can check the following apple sample code:View Transition</p>

ContentLicense: CC BY-SA 3.0


问:
Why doesn't KStreamBinder have a lifecycle for DefaultBinding?
I'm using KStream parameter in @StreamBuilder.

This will create a DefaultBinding through KStreamBinder.

My requirement is to use Binding visualization and control.

However

return new DefaultBinding <> (name, null, outboundBindTarget, null);
```

You can't control the state via springboot /actuator/bindings because the lifecycle is null.

(POST /actuator/bindings/{bindings-name} {"state":"PAUSED"})

How can I control the state of a Binding?

The version I am using is below.

org.springframework.cloud:spring-cloud-stream:3.0.1.RELEASE

org.springframework.cloud:spring-cloud-stream-binder-kafka-core:3.0.1.RELEASE

org.springframework.cloud:spring-cloud-stream-binder-kafka-streams:3.0.1.RELEASE

org.apache.kafka:kafka-streams:2.3.1

please answer about my question.
Thank you.

答: Binding visualization controls are not fully available in Kafka Streams binder in Spring Cloud Stream. If you can describe your use case as a new GitHub issue, we can discuss this further there. Thank you.  </p>

Body:
I'm using KStream parameter in @StreamBuilder.

This will create a DefaultBinding through KStreamBinder.

My requirement is to use Binding visualization and control.

However

return new DefaultBinding <> (name, null, outboundBindTarget, null);

You can't control the state via springboot /actuator/bindings because the lifecycle is null.

(POST /actuator/bindings/{bindings-name} {"state":"PAUSED"})

How can I control the state of a Binding?

The version I am using is below.

org.springframework.cloud:spring-cloud-stream:3.0.1.RELEASE

org.springframework.cloud:spring-cloud-stream-binder-kafka-core:3.0.1.RELEASE

org.springframework.cloud:spring-cloud-stream-binder-kafka-streams:3.0.1.RELEASE

org.apache.kafka:kafka-streams:2.3.1

please answer about my question.
Thank you.


问:
How to group options in Filter Panel on Qlik Sense
I'm wondering how to group some values in a filter panel in Qlik Sense

For Example:
In a filter pane we have:

```<code>Item1
Item2
Item3
Item4
</code>```

But Item3 and Item4 I want to group it just into a 1 ItemX2

So finally it will be:

```<code>Item1
Item2
ItemX2
</code>```

How can I do this in Qlik Sense?

I was trying with match() or aggr() but I wasn't so lucky

答:
This is a data issue. Try not to solve such problems in the frontend/UI. Especially in apps with a lot of data. Such solutions are going to reduce the performance (more aggregations on the fly)

In the script you can use ApplyMap function to create such grouping

(For example) In the script below the have Mapping table contains all Items that are requiring re-mapping (grouping in your case)

This table is used to create new field (ItemsGrouped) which will contain the new values (if the Items field is not a key to another table you can overwrite it with the ApplyMap instead of creating new field). This field can be shown in the UI and will contain these values:

```<code>Item1
Item2
ItemX2
</code>```

```<code>ItemsMapping:
Mapping
Load * Inline [
Old  , New
Item3, ItemX2
Item4, ItemX2
];

Data:
Load
  ....
  Items,
  ApplyMap('ItemsMapping', Items) as ItemsGrouped
From
  MyData.qvd
;

</code>```

Body:
I'm wondering how to group some values in a filter panel in Qlik Sense

For Example:
In a filter pane we have:

Item1
Item2
Item3
Item4

But Item3 and Item4 I want to group it just into a 1 ItemX2

So finally it will be:

Item1
Item2
ItemX2

How can I do this in Qlik Sense?

I was trying with match() or aggr() but I wasn't so lucky

Body:
This is a data issue. Try not to solve such problems in the frontend/UI. Especially in apps with a lot of data. Such solutions are going to reduce the performance (more aggregations on the fly)

In the script you can use ApplyMap function to create such grouping

(For example) In the script below the have Mapping table contains all Items that are requiring re-mapping (grouping in your case)

This table is used to create new field (ItemsGrouped) which will contain the new values (if the Items field is not a key to another table you can overwrite it with the ApplyMap instead of creating new field). This field can be shown in the UI and will contain these values:

Item1
Item2
ItemX2

ItemsMapping:
Mapping
Load * Inline [
Old  , New
Item3, ItemX2
Item4, ItemX2
];

Data:
Load
  ....
  Items,
  ApplyMap('ItemsMapping', Items) as ItemsGrouped
From
  MyData.qvd
;


问:
How can I use randomisation to specify different object parameters to a single iteration in a loop?
I currently have a simple for-loop with 5 iterations that creates 'brick' game objects, adds them into the 'bricks' array and laying them out across the x axis of my javaFX scene. currently, as you can see on the Gameobj parameters; they are all blue. However, I want to have one of these bricks set as yellow on a random iteration of the loop. Here is my code:

```<code>    public void initialiseGame()
    {
        bricks = new ArrayList<>();
        for(int i=0; i<5; i++) {
            GameObj brick = new GameObj(i*100, 100, BRICK_WIDTH, BRICK_HEIGHT, Color.BLUE);
            brick.moveX(75);
            brick.visible = true;
            bricks.add(brick);
            System.out.println("Model:: Create Brick =" + brick);
        }
    }
</code>```

Here is the game object method setup:

```<code>    public GameObj( int x, int y, int w, int h, Color c )
    {
        topX   = x;
        topY = y;
        width  = w;
        height = h;
        colour = c;
    }
</code>```

How exactly can I use some sort of randomiser to change the colour of the brick on a single iteration?

答:
Pick a random number in the range [0, 5) before the loop, and then set the color to yellow if the loop index matches that number:

```<code>Random random = new Random();
int yellowBrick = random.nextInt(5);
for (int i = 0; i < 5; i++) {
    Color color = i == yellowBrick ? Color.YELLOW : Color.BLUE;
    GameObj brick = new GameObj(i*100, 100, BRICK_WIDTH, BRICK_HEIGHT, color);
    brick.moveX(75);
    brick.visible = true;
    bricks.add(brick);
    System.out.println("Model:: Create Brick =" + brick);
}
</code>```

Body:
I currently have a simple for-loop with 5 iterations that creates 'brick' game objects, adds them into the 'bricks' array and laying them out across the x axis of my javaFX scene. currently, as you can see on the Gameobj parameters; they are all blue. However, I want to have one of these bricks set as yellow on a random iteration of the loop. Here is my code:

    public void initialiseGame()
    {
        bricks = new ArrayList<>();
        for(int i=0; i<5; i++) {
            GameObj brick = new GameObj(i*100, 100, BRICK_WIDTH, BRICK_HEIGHT, Color.BLUE);
            brick.moveX(75);
            brick.visible = true;
            bricks.add(brick);
            System.out.println("Model:: Create Brick =" + brick);
        }
    }

Here is the game object method setup:

    public GameObj( int x, int y, int w, int h, Color c )
    {
        topX   = x;
        topY = y;
        width  = w;
        height = h;
        colour = c;
    }

How exactly can I use some sort of randomiser to change the colour of the brick on a single iteration?

Body:
Pick a random number in the range [0, 5) before the loop, and then set the color to yellow if the loop index matches that number:

Random random = new Random();
int yellowBrick = random.nextInt(5);
for (int i = 0; i < 5; i++) {
    Color color = i == yellowBrick ? Color.YELLOW : Color.BLUE;
    GameObj brick = new GameObj(i*100, 100, BRICK_WIDTH, BRICK_HEIGHT, color);
    brick.moveX(75);
    brick.visible = true;
    bricks.add(brick);
    System.out.println("Model:: Create Brick =" + brick);
}


问:
Function pointers with classes
I've been looking for a few days and at this point I assume that I'm not looking with the right criteria.Here's what I need to do

```<code>class AB
{
    public:
        std::function<void()>addr;
};

class BC
{
    public:
        void myTestFunc(std::string value)
        {
            std::cout << "AB::myTestFunc called: " << value << std::endl;
        }
};

int main(void)
{
    AB ob;
    BC obj2;

    ob.addr = std::bind(&obj2::myTestFunc, "");
    // so that i can call
    (ob.addr)("testing");

    return 0;
}
</code>```

The problem is that I need to have a class that can allow instances of other classes its used to call a function on the "parent" or main class.  The actual arguments and functions are obviously different but I cannot  get it to work with a class public function.  I cannot make it static as each instance of the "child" class will be calling a separate function.  Please tell me what I should be searching for and / or what I'm doing wrong.

答:
I believe this is where you're going.</p>

```<code>class AB
{
    public:
        std::function<void(std::string)>addr;
};

class BC
{
    public:
        void myTestFunc(std::string value)
        {
            std::cout << "AB::myTestFunc called: " << value << std::endl;
        }
};

int main(void)
{
    AB ob;
    BC ob2;
    std::string i = "testing";
    ob.addr = std::bind(&BC::myTestFunc, &ob2, i);
    ob.addr(i);

    return 0;
}
</code>```

Title: Function pointers with classes

Body:
I've been looking for a few days and at this point I assume that I'm not looking with the right criteria.Here's what I need to do

class AB
{
    public:
        std::function<void()>addr;
};

class BC
{
    public:
        void myTestFunc(std::string value)
        {
            std::cout << "AB::myTestFunc called: " << value << std::endl;
        }
};

int main(void)
{
    AB ob;
    BC obj2;

    ob.addr = std::bind(&obj2::myTestFunc, "");
    // so that i can call
    (ob.addr)("testing");

    return 0;
}

The problem is that I need to have a class that can allow instances of other classes its used to call a function on the "parent" or main class.  The actual arguments and functions are obviously different but I cannot  get it to work with a class public function.  I cannot make it static as each instance of the "child" class will be calling a separate function.  Please tell me what I should be searching for and / or what I'm doing wrong.

Body:
I believe this is where you're going.

class AB
{
    public:
        std::function<void(std::string)>addr;
};

class BC
{
    public:
        void myTestFunc(std::string value)
        {
            std::cout << "AB::myTestFunc called: " << value << std::endl;
        }
};

int main(void)
{
    AB ob;
    BC ob2;
    std::string i = "testing";
    ob.addr = std::bind(&BC::myTestFunc, &ob2, i);
    ob.addr(i);

    return 0;
}


问:
Git error when trying to push -- pre-receive hook declined
When I try and push a change I've commited, I get the following error ...

```<code>git.exe push -v --progress  "origin" iteration1:iteration1

remote: *********************************************************************
To ssh://git@mycogit/cit_pplus.git
! [remote rejected] iteration1 -> iteration1 (pre-receive hook declined)
error: failed to push some refs to 'ssh://git@mycogit/cit_pplus.git'
</code>```

What's going on?

答: Remove the protected branch option or allow additional roles like developers or admins to allow these users experiencing this error to do merges and push. </p>

Body:
When I try and push a change I've commited, I get the following error ...

git.exe push -v --progress  "origin" iteration1:iteration1

remote: *********************************************************************
To ssh://git@mycogit/cit_pplus.git
! [remote rejected] iteration1 -> iteration1 (pre-receive hook declined)
error: failed to push some refs to 'ssh://git@mycogit/cit_pplus.git'

What's going on?


问:
J2EE Spring security One Time Password
I must implement a One Time Password. For single petitions and although there are loads of resources of information in internet I still having doubts.

It is possible to make it survive system reboot with no use of databases?

答: The only way I know to store persistent data without databases is to write into an external file (actually databases are only files in disguise). In your case you have to carefully think about security issues of this solution. You have to make sure that your file is stored in a secure repository.</p>

Title: J2EE Spring security One Time Password


问:
CSS Backround Autosizing Issues
I am very new to web development and am in need of some help. I have built a login page using JavaScript, html, and CSS. I want my background to autosize to fit the screen of whatever device is accessing the page. I've researched how to do this and have implemented it through this CSS styling:

```<code>    body, html {
      background: url("/images/Test.jpg"), #2d2d2d;
      height: 100%;
      width: 100%;
      background-repeat: no-repeat;
    }
</code>```

Any ideas on how I can fix this? Thanks.

答:
```<code>background-size: 100%; //to fill screen
background-position:center; //to center on screen
</code>```

background cover will shrink image.

Title: CSS Backround Autosizing Issues

Body:
I am very new to web development and am in need of some help. I have built a login page using JavaScript, html, and CSS. I want my background to autosize to fit the screen of whatever device is accessing the page. I've researched how to do this and have implemented it through this CSS styling:

    body, html {
      background: url("/images/Test.jpg"), #2d2d2d;
      height: 100%;
      width: 100%;
      background-repeat: no-repeat;
    }

Any ideas on how I can fix this? Thanks.

Body:
background-size: 100%; //to fill screen
background-position:center; //to center on screen

background cover will shrink image.


问:
Why is FormArrayName always undefined in my html, even when using safe-navigation operator?
I'm following the angular material example at https://angular.io/api/forms/FormArrayName

I'm console logging the packageForm formGroup after it is initialized in ngOnInit() and the translations FormArray is there. But in the html, I'm getting an undefined error. I also tried putting a safe-navigation operator on the formArray, which gets rid of the error but nothing is displayed.

Here is my code in the component.ts :

```<code>ngOnInit() {
    this.packageModel = this.activatedRoute.snapshot.data['package'];
    if (this.packageModel) {
      this.editting = true;
    } else {
      this.packageModel = new PackageModel(null, true, 1, 0, 0, []);
    }
    this._setupForm();
  }

  ngAfterViewInit() {
    console.log(this.packageForm)
  }

  private _setupForm() {
    this.packageForm = this.formBuilder.group({
      isActive: [this.packageModel.isActive, [Validators.required]],
      quantity: [this.packageModel.quantity, [Validators.required]],
      minPrice: [this.packageModel.minPrice, [Validators.required]],
      maxPrice: [this.packageModel.maxPrice, [Validators.required]],
      translations: this.formBuilder.array([
          this._createTranslationFormGroup(0),
          this._createTranslationFormGroup(1)
      ])
    });

    console.log(this.packageForm)

    this.packageForm.get('isActive').valueChanges.subscribe(value => {
      this.packageModel.isActive = value;
    });
  }

  private _createTranslationFormGroup(index: number) {
    return this.formBuilder.group({
      name: [this.packageModel.translations[index].name, [Validators.required]],
      description: [this.packageModel.translations[index].description, [Validators.required]]
    });
  }

</code>```

HTML code:

```<code><div *ngIf="packageForm" class="package-form" [formGroup]="packageForm">
    <div formArrayName="translations">
        <div class="row" *ngFor="let translation of translations.controls; index as i" [formGroupName]="i">
            <div class="col-6">
                <mat-form-field>
                    <input type="text" matInput [formControlName]="name" />
                </mat-form-field>
            </div>
        </div>
    </div>
</div>
</code>```

I'm getting the following error:
ERROR TypeError: Cannot read property 'controls' of undefined

Thanks in advance for taking the time to help me!

答:
it should be *ngFor="let translation of packageForm.get('translations').controls. it is usual to make som getter on a component as a shortcut to this

```<code>get translations() {
 return this.packageForm.get('translations') as FormArray
}
^^ with this your template referencing will work fine.
</code>```

also <input formControlName="name"><- here braces are not needed

Body:
I'm following the angular material example at https://angular.io/api/forms/FormArrayName

I'm console logging the packageForm formGroup after it is initialized in ngOnInit() and the translations FormArray is there. But in the html, I'm getting an undefined error. I also tried putting a safe-navigation operator on the formArray, which gets rid of the error but nothing is displayed.

Here is my code in the component.ts :

ngOnInit() {
    this.packageModel = this.activatedRoute.snapshot.data['package'];
    if (this.packageModel) {
      this.editting = true;
    } else {
      this.packageModel = new PackageModel(null, true, 1, 0, 0, []);
    }
    this._setupForm();
  }

  ngAfterViewInit() {
    console.log(this.packageForm)
  }

  private _setupForm() {
    this.packageForm = this.formBuilder.group({
      isActive: [this.packageModel.isActive, [Validators.required]],
      quantity: [this.packageModel.quantity, [Validators.required]],
      minPrice: [this.packageModel.minPrice, [Validators.required]],
      maxPrice: [this.packageModel.maxPrice, [Validators.required]],
      translations: this.formBuilder.array([
          this._createTranslationFormGroup(0),
          this._createTranslationFormGroup(1)
      ])
    });

    console.log(this.packageForm)

    this.packageForm.get('isActive').valueChanges.subscribe(value => {
      this.packageModel.isActive = value;
    });
  }

  private _createTranslationFormGroup(index: number) {
    return this.formBuilder.group({
      name: [this.packageModel.translations[index].name, [Validators.required]],
      description: [this.packageModel.translations[index].description, [Validators.required]]
    });
  }

HTML code:

                <mat-form-field>
                    <input type="text" matInput [formControlName]="name" />
                </mat-form-field>

I'm getting the following error:
ERROR TypeError: Cannot read property 'controls' of undefined

Thanks in advance for taking the time to help me!

Body:
it should be *ngFor="let translation of packageForm.get('translations').controls. it is usual to make som getter on a component as a shortcut to this

get translations() {
 return this.packageForm.get('translations') as FormArray
}
^^ with this your template referencing will work fine.

also <input formControlName="name"><- here braces are not needed


问:
How to place two div side-by-side in a HTML page
I have created a simple HTML page, where I have a parent div with over-flow enabled in both axes. Now within that div, there are 2 divs which I want to place side by side.

#Result {
  margin: 0 auto;
  padding: 0;
  background-color: rgba(0, 0, 0, .02);
  padding-top: 25px;
  font-size: 16px;
  overflow: scroll;
  width: 99%;
  height: calc(100% - 90px - 70px);
  position: absolute;
}

#Left,
#Right {
  height: calc(99vh - 90px - 70px);
  width: 28vw;
  margin: 0 auto;
  padding: 0;
  display: inline-block;
  float: left;
  text-align: center;
  background-color: rgba(0, 0, 0, .04);
  border-right: 1px solid #a6a6a6;
  border-bottom: 1px solid #a6a6a6;
}

#Right {
  background-color: rgba(0, 0, 0, .5);
  border-right: 0px solid #737373;
  padding-left: 15px;
  margin-right: 15px;
  width: 2000px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='Result'>
  <div id='Left'>

  </div>
  <div id='Right'>

  </div>
</div></code>```

Codepen - https://codepen.io/Volabos/pen/qBdNyPa?editors=1100

However unfortunately, the 3rd div is moved down if its width is taken a large number. How can I place the 2nd and 3rd div side by side?

答:
.flex-container {
  display: flex;
  align-items: stretch;
  background-color: #f1f1f1;
}

.flex-container>div {
  background-color: DodgerBlue;
  color: white;
  width: 100px;
  margin: 10px;
  text-align: center;
  line-height: 75px;
  font-size: 30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flex-container">
  <div style="flex-grow: 1">1</div>
  <div style="flex-grow: 1">2</div>
  <div style="flex-grow: 8">3</div>
</div></code>```

Body:
I have created a simple HTML page, where I have a parent div with over-flow enabled in both axes. Now within that div, there are 2 divs which I want to place side by side.

#Result {
  margin: 0 auto;
  padding: 0;
  background-color: rgba(0, 0, 0, .02);
  padding-top: 25px;
  font-size: 16px;
  overflow: scroll;
  width: 99%;
  height: calc(100% - 90px - 70px);
  position: absolute;
}

#Left,
#Right {
  height: calc(99vh - 90px - 70px);
  width: 28vw;
  margin: 0 auto;
  padding: 0;
  display: inline-block;
  float: left;
  text-align: center;
  background-color: rgba(0, 0, 0, .04);
  border-right: 1px solid #a6a6a6;
  border-bottom: 1px solid #a6a6a6;
}

#Right {
  background-color: rgba(0, 0, 0, .5);
  border-right: 0px solid #737373;
  padding-left: 15px;
  margin-right: 15px;
  width: 2000px;
}

Codepen - https://codepen.io/Volabos/pen/qBdNyPa?editors=1100

However unfortunately, the 3rd div is moved down if its width is taken a large number. How can I place the 2nd and 3rd div side by side?

Body:
.flex-container {
  display: flex;
  align-items: stretch;
  background-color: #f1f1f1;
}

.flex-container>div {
  background-color: DodgerBlue;
  color: white;
  width: 100px;
  margin: 10px;
  text-align: center;
  line-height: 75px;
  font-size: 30px;
}

<div class="flex-container">
  <div style="flex-grow: 1">1</div>
  <div style="flex-grow: 1">2</div>
  <div style="flex-grow: 8">3</div>
</div>


问:
TypeError: _this.props.onSave is not a function
I am trying to build a simple blog app using Nextjs(React+Typescript) and I am getting this error

TypeError: _this.props.onSave is not a function

How can I resolve this error?
I have already asked a query on stackoverflow about this but so far no luck. This is the link:
this.props.onSave is not a function- Uncaught typescript error

I have tried everything from binding to literally debugging lines. How can I resolve this error?

答:
That error is basically saying, you did not pass prop onSave onto that component, or you did pass it, but somehow incorrectly.

I advise, use console.log(this.props) or console.log(this.props.onSave)  to find out what you did really pass.

Also, pay attention to this, just make sure, you are passing a function, not it's return value

```<code>class Parent extends Component {

    myCustomMethod() {
        console.log("call me ");
    }

    render() {

        //incorrect
        //return <MyCustomComponent callback={this.myCustomMethod()} />;

        //this one is correct, without parentheses
        return <MyCustomComponent callback={this.myCustomMethod} />;
    }
}
</code>```

Body:
That error is basically saying, you did not pass prop onSave onto that component, or you did pass it, but somehow incorrectly.

I advise, use console.log(this.props) or console.log(this.props.onSave)  to find out what you did really pass.

Also, pay attention to this, just make sure, you are passing a function, not it's return value

class Parent extends Component {

    myCustomMethod() {
        console.log("call me ");
    }

    render() {

        //incorrect
        //return <MyCustomComponent callback={this.myCustomMethod()} />;

        //this one is correct, without parentheses
        return <MyCustomComponent callback={this.myCustomMethod} />;
    }
}


答:
Floats can be a way, but I'd rather go with flexbox:

```<code>#result {
  display: flex;
  justify-content: space-between  // or flex-start, center, flex-end ... whatever
}
</code>```

Your #Left and #Right will be placed side by side and will have the same height by default.

EDIT: Container with two children aligned next to each other, including a horizontal scrollbar:

```<code>  <style>

  .container{
    display: flex;
    justify-content: space-between;
    overflow: scroll;
    border: 1px solid blue;
  }

  .child {
    width: 60%;
    flex-shrink: 0;
    height: 100px;
    border: 1px solid red;
  }

</style>

<div class="container">
  <div class="child"></div>
  <div class="child"></div>
</div>
</code>```

Title: How to place two div side-by-side in a HTML page

Body:
Floats can be a way, but I'd rather go with flexbox:

#result {
  display: flex;
  justify-content: space-between  // or flex-start, center, flex-end ... whatever
}

Your #Left and #Right will be placed side by side and will have the same height by default.

EDIT: Container with two children aligned next to each other, including a horizontal scrollbar:

  <style>

  .container{
    display: flex;
    justify-content: space-between;
    overflow: scroll;
    border: 1px solid blue;
  }

  .child {
    width: 60%;
    flex-shrink: 0;
    height: 100px;
    border: 1px solid red;
  }

</style>

<div class="container">
  <div class="child"></div>
  <div class="child"></div>
</div>


问:
How best to reduce CPU time used by a datastore put
I have a cron job which I run every three minutes, which pulls some data from a remote API, and then stores it in my local datastore. However, this is taking a huge amount of CPU time  in the datastore put operation. I suspect I'm probably doing something really stupid which can be optimised a lot:

```<code>result = urllib2.urlopen(url).read()
foos = json.loads(result)['foo']
bars = json.loads(result)['bar']

models = []
for foo in foos:
    d = FooContainer()
    d.Property = foo.Value #in real code, this is setting a load of values based off foo
    models.append(d)

for bar in bars:
    d = BarContainer()
    d.Property = bar.Value #in real code, this is setting a load of properties based off bar
    models.append(d)

db.put(models)
</code>```

As you can see, I'm storing every piece of data returned as a new "row" in my local datastore tables. Is there some technique I can use to reduce the huge datastore CPU time used by this cron job?

答:
Have you tried using nice to be nice to others process?

http://en.wikipedia.org/wiki/Nice_%28Unix%29

Also, be sure you are doing bulk insert but it seems so.

Body:
I have a cron job which I run every three minutes, which pulls some data from a remote API, and then stores it in my local datastore. However, this is taking a huge amount of CPU time  in the datastore put operation. I suspect I'm probably doing something really stupid which can be optimised a lot:

result = urllib2.urlopen(url).read()
foos = json.loads(result)['foo']
bars = json.loads(result)['bar']

models = []
for foo in foos:
    d = FooContainer()
    d.Property = foo.Value #in real code, this is setting a load of values based off foo
    models.append(d)

for bar in bars:
    d = BarContainer()
    d.Property = bar.Value #in real code, this is setting a load of properties based off bar
    models.append(d)

db.put(models)

As you can see, I'm storing every piece of data returned as a new "row" in my local datastore tables. Is there some technique I can use to reduce the huge datastore CPU time used by this cron job?


问:
if/then replace values looping over rows conditional on column value(s) in R
I am trying to do an if/then replacement (recoding) of values row by row (looping over rows), based on one the values of or more columns in those rows. I've looked at a lot of prior examples here and elsewhere (R help) but haven't been able to get very far.

Here is an example data set:

```<code>> set.seed(1234)
> let<-c("AB","AA","BB")
> df <- data.frame(rbind(x1=c(12,"DF1",sample(let,6,TRUE)),x2=c(12,"HA.1",sample(let,6,TRUE)),x3=c(21,"DF1",sample(let,6,TRUE)),x4=c(12,"AS.2",sample(let,6,TRUE))
+ ))
> df
   X1   X2 X3 X4 X5 X6 X7 X8
x1 12  DF1 AB AA AA AA BB AA
x2 12 HA.1 AB AB AA AA BB AA
x3 21  DF1 AB BB AB BB AB AB
x4 12 AS.2 AB AB AB AB AB AB
</code>```

I would like to conditionally change the coding (replace) values in columns 3:8 (from X3 through X8) based on values in X1 and X2 using if/then. 'AB' becomes 1 if X1=12 AND X2=DF1, 'AA' becomes 2 if X1=12 AND X2=DF1, 'BB' becomes 3 if X1=12 and X2=DF1 etc. There will be many other (nested?) if statements to add to complete this specific case, but I am not sure how to approach even the most basic aspect of this script: how to condition the replacement of values in columns 3:8 based on the column 1 value (and also column 2 or more columns) at a given row.

So, looping over each row, I would test if the value in X2 = DF1 and X1=12 (for example), and if so in both cases, change values of AB to 1, AA to 2, and BB to 3...

```<code>for(i in 1:nrow(df)){
      if((df$X2[i]=="DF1") & (df$X1[i]=12)) {
          ifelse(df[i,3:8] == "AB", 1, ifelse(df[i,3:8]=="AA", 2,ifelse(df[i,3:8]=="BB",3,"NA")))}
             else{}
      }
</code>```

Now...this appears to do nothing - no changes to dfand no warnings. But the ifelse statements  work when I specify the row (4):

```<code>> ifelse(df[4,3:8] == "AB", 1, ifelse(df[4,3:8]=="AA", 2,ifelse(df[4,3:8]=="BB",3,"NA")))
   X3  X4  X5  X6  X7  X8
x4 "1" "3" "1" "1" "1" "2"
> df[4,3:8]
   X3 X4 X5 X6 X7 X8
x4 AB BB AB AB AB AA
</code>```

So it must be something in the initial if &  ? Do I need to have something in my else clause?

And of course, my 'real' world use case is more complicated as each different value in X1 or X2 will require different if/then statements to recode the values in colum 3:8

Anyway - am I even approaching this correctly? Would a look up table work better? I would be setting up additional nested if/& statements for each combination of values for X1 and X2. It will be ugly, but if I can get the nested if statements to work, then at least I can get there.

Thanks for any suggestions!

答:
if((df$X2[i]=="DF1") & (df$X1[i]=12))
```

<p>In the second comparison you are using <code>=</code> instead of <code>==</code>. Also, you are not assigning anything within your loop, that is why nothing is happening. </p>

<p>But iterating over rows of a data frame in R is generally not a good idea as it is not very performant. Furthermore, <code>ifelse()</code> already provides a vectorized solution. But unfortunately, you are not using it right, as you need to apply it to each of the columns you are working on.</p>

<p>I think the best solution for what you are trying to do would be the following:</p>

<pre class="lang-r prettyprint-override"><code>df <- structure(list(X1 = c(12, 12, 21, 12),
                     X2 = c("DF1", "HA.1", "DF1", "AS.2"),
                     X3 = c("AB", "AB", "AB", "AB"),
                     X4 = c("AA", "AB", "BB", "AB"),
                     X5 = c("AA", "AA", "AB", "AB"),
                     X6 = c("AA", "AA", "BB", "AB"),
                     X7 = c("BB", "BB", "AB", "AB"),
                     X8 = c("AA", "AA", "AB", "AB")),
                class = "data.frame", row.names = c(NA, -4L)
                )
df
#>   X1   X2 X3 X4 X5 X6 X7 X8
#> 1 12  DF1 AB AA AA AA BB AA
#> 2 12 HA.1 AB AB AA AA BB AA
#> 3 21  DF1 AB BB AB BB AB AB
#> 4 12 AS.2 AB AB AB AB AB AB

rows <- df$X2 == "DF1" & df$X1 == 12
df[rows, 3:8] <- lapply(df[rows, 3:8], function(x) {as.integer(factor(x, c("AB", "AA", "BB")))})
df
#>   X1   X2 X3 X4 X5 X6 X7 X8
#> 1 12  DF1  1  2  2  2  3  2
#> 2 12 HA.1 AB AB AA AA BB AA
#> 3 21  DF1 AB BB AB BB AB AB
#> 4 12 AS.2 AB AB AB AB AB AB
</code>```

Created on 2020-02-19 by the reprex package (v0.3.0)

You need to make sure here, that your variables are characters, not factors or it won't work.

You could also do it with nested ifelse() calls, as you did before, but it is already pretty verbose for just three.

Edit in response to comment:

# Unite the group vars in one vector
group <- paste(df$X1, df$X2, sep = "-")

# In this list you can say what case should use what recoding
lst <- list("12-DF1" = c("AB" = 1, "AA" = 2, "BB" = 3),
            "12-HA.1" = c("AB" = 5, "AA" = 3, "BB" = 4),
            "21-DF1" = c("AB" = 8, "AA" = 22, "BB" = 11),
            "12-AS.2" = c("AB" = 9, "AA" = 7, "BB" = 6))

# Function to recode single column
rcde_cols <- function(column) mapply(function(col, g) {unlist(lst[[g]][col])},
                                     col = as.list(column),
                                     g = as.list(group))

# Apply to all
df[3:8] <- lapply(df[3:8], rcde_cols)
```

Body:
I am trying to do an if/then replacement (recoding) of values row by row (looping over rows), based on one the values of or more columns in those rows. I've looked at a lot of prior examples here and elsewhere (R help) but haven't been able to get very far.

Here is an example data set:

> set.seed(1234)
> let<-c("AB","AA","BB")
> df <- data.frame(rbind(x1=c(12,"DF1",sample(let,6,TRUE)),x2=c(12,"HA.1",sample(let,6,TRUE)),x3=c(21,"DF1",sample(let,6,TRUE)),x4=c(12,"AS.2",sample(let,6,TRUE))
+ ))
> df
   X1   X2 X3 X4 X5 X6 X7 X8
x1 12  DF1 AB AA AA AA BB AA
x2 12 HA.1 AB AB AA AA BB AA
x3 21  DF1 AB BB AB BB AB AB
x4 12 AS.2 AB AB AB AB AB AB

I would like to conditionally change the coding (replace) values in columns 3:8 (from X3 through X8) based on values in X1 and X2 using if/then. 'AB' becomes 1 if X1=12 AND X2=DF1, 'AA' becomes 2 if X1=12 AND X2=DF1, 'BB' becomes 3 if X1=12 and X2=DF1 etc. There will be many other (nested?) if statements to add to complete this specific case, but I am not sure how to approach even the most basic aspect of this script: how to condition the replacement of values in columns 3:8 based on the column 1 value (and also column 2 or more columns) at a given row.

So, looping over each row, I would test if the value in X2 = DF1 and X1=12 (for example), and if so in both cases, change values of AB to 1, AA to 2, and BB to 3...

for(i in 1:nrow(df)){
      if((df$X2[i]=="DF1") & (df$X1[i]=12)) {
          ifelse(df[i,3:8] == "AB", 1, ifelse(df[i,3:8]=="AA", 2,ifelse(df[i,3:8]=="BB",3,"NA")))}
             else{}
      }

Now...this appears to do nothing - no changes to dfand no warnings. But the ifelse statements  work when I specify the row (4):

> ifelse(df[4,3:8] == "AB", 1, ifelse(df[4,3:8]=="AA", 2,ifelse(df[4,3:8]=="BB",3,"NA")))
   X3  X4  X5  X6  X7  X8
x4 "1" "3" "1" "1" "1" "2"
> df[4,3:8]
   X3 X4 X5 X6 X7 X8
x4 AB BB AB AB AB AA

So it must be something in the initial if &  ? Do I need to have something in my else clause?

And of course, my 'real' world use case is more complicated as each different value in X1 or X2 will require different if/then statements to recode the values in colum 3:8

Anyway - am I even approaching this correctly? Would a look up table work better? I would be setting up additional nested if/& statements for each combination of values for X1 and X2. It will be ugly, but if I can get the nested if statements to work, then at least I can get there.

Thanks for any suggestions!

Body:
if((df$X2[i]=="DF1") & (df$X1[i]=12))

In the second comparison you are using = instead of ==. Also, you are not assigning anything within your loop, that is why nothing is happening.

But iterating over rows of a data frame in R is generally not a good idea as it is not very performant. Furthermore, ifelse() already provides a vectorized solution. But unfortunately, you are not using it right, as you need to apply it to each of the columns you are working on.

I think the best solution for what you are trying to do would be the following:

df <- structure(list(X1 = c(12, 12, 21, 12),
                     X2 = c("DF1", "HA.1", "DF1", "AS.2"),
                     X3 = c("AB", "AB", "AB", "AB"),
                     X4 = c("AA", "AB", "BB", "AB"),
                     X5 = c("AA", "AA", "AB", "AB"),
                     X6 = c("AA", "AA", "BB", "AB"),
                     X7 = c("BB", "BB", "AB", "AB"),
                     X8 = c("AA", "AA", "AB", "AB")),
                class = "data.frame", row.names = c(NA, -4L)
                )
df
#>   X1   X2 X3 X4 X5 X6 X7 X8
#> 1 12  DF1 AB AA AA AA BB AA
#> 2 12 HA.1 AB AB AA AA BB AA
#> 3 21  DF1 AB BB AB BB AB AB
#> 4 12 AS.2 AB AB AB AB AB AB

rows <- df$X2 == "DF1" & df$X1 == 12
df[rows, 3:8] <- lapply(df[rows, 3:8], function(x) {as.integer(factor(x, c("AB", "AA", "BB")))})
df
#>   X1   X2 X3 X4 X5 X6 X7 X8
#> 1 12  DF1  1  2  2  2  3  2
#> 2 12 HA.1 AB AB AA AA BB AA
#> 3 21  DF1 AB BB AB BB AB AB
#> 4 12 AS.2 AB AB AB AB AB AB

Created on 2020-02-19 by the reprex package (v0.3.0)

You need to make sure here, that your variables are characters, not factors or it won't work.

You could also do it with nested ifelse() calls, as you did before, but it is already pretty verbose for just three.

Edit in response to comment:

# Unite the group vars in one vector
group <- paste(df$X1, df$X2, sep = "-")

# In this list you can say what case should use what recoding
lst <- list("12-DF1" = c("AB" = 1, "AA" = 2, "BB" = 3),
            "12-HA.1" = c("AB" = 5, "AA" = 3, "BB" = 4),
            "21-DF1" = c("AB" = 8, "AA" = 22, "BB" = 11),
            "12-AS.2" = c("AB" = 9, "AA" = 7, "BB" = 6))

# Function to recode single column
rcde_cols <- function(column) mapply(function(col, g) {unlist(lst[[g]][col])},
                                     col = as.list(column),
                                     g = as.list(group))

# Apply to all
df[3:8] <- lapply(df[3:8], rcde_cols)


问:
c# efficient way to convert a list of paths to xml
I have a list of folder paths coming from a database that I need to export to xml.  The raw data looks as follows:

What I need to do is create a tree like structure, similar to this within the xml:

 - networkAdd
    - users
        - test1
           - delete unicode character test
                 - character test 1
                        - linked to folder
                 - character test 2
                 - character test 3
 - sp2013
    - newTestsite
        - newTestLib
           - sampleFolder
           - Renamed at source again
           - SecurityTest2013Folder
        - Shared Documents
           - sample.folder
```

<p>I have current got an efficient xml write method available to me BUT it requires a treeview.  I took the list above (coming from the database) and converted it to a treeview that could be used with this method (which works fine) but it requires me to convert to a treeview first which is inefficient.  I use this code:</p>

```public static TreeView PopulateTreeView(IEnumerable<FolderInfo> paths)
{
    var treeView = new TreeView();
    treeView.PathSeparator = "\\";

    TreeNode lastNode = null;
    string subPathAgg;
    string lastRootFolder = null;

    foreach (var item in paths)
    {
        var path = item.FolderName; // folder path.

        if (lastRootFolder != item.FolderRoot)
        {
            lastRootFolder = item.FolderRoot;
            lastNode = null;
        }

        subPathAgg = string.Empty;
        foreach (string subPath in path.Split('\\'))
        {
            if (subPath.Length > 0)
            {
                subPathAgg += subPath + "\\";
                TreeNode[] nodes = treeView.Nodes.Find(subPathAgg, true);

                var newNode = new TreeNode
                {
                    Name = subPathAgg,
                    Text = subPath,
                    ImageIndex = 2,
                    ToolTipText = item.FullFolderPath
                };

                if (nodes.Length == 0)
                {
                    if (lastNode == null)
                        treeView.Nodes.Add(newNode);
                    else
                        lastNode.Nodes.Add(newNode);

                    lastNode = newNode;
                }
                else
                    lastNode = nodes[0];
            }
        }
    }

    return treeView;
}
```

This line of code becomes very slow to execute when I have over 10 million records to process:
TreeNode[] nodes = treeView.Nodes.Find(subPathAgg, true);

It would be much more efficient for me to convert straight from DB to XML (without the treeview middle man).

Has anyone any advice on an alternative way of parsing folder paths into xml, taking nesting into consideration?  Thanks for any pointers in advance!

答:
Turns out, if you can ensure that your strings are properly sorted (which should be easy if they're coming from a DB), this is pretty easy if you work directly with an XmlWriter. Something like:

```<code>var strings = new[]
{
    @"\\networkAdd",
    @"\\networkAdd\users",
    @"\\networkAdd\users\test1\",
    @"\\networkAdd\users\test1\delete unicode character test",
    @"\\networkAdd\users\test1\delete unicode character test\character test 1",
    @"\\networkAdd\users\test1\delete unicode character test\character test 1\linked to folder",
    @"\\networkAdd\users\test1\delete unicode character test\character test 2",
    @"\\networkAdd\users\test1\delete unicode character test\character test 3",
    @"http:\\sp2013",
    @"http:\\sp2013\newTestsite",
    @"http:\\sp2013\newTestlib",
    @"http:\\sp2013\newTestlib\sampleFolder",
};
</code>```

```<code>// Obviously, stream it out to a file rather than an in-memory string
using (var stringWriter = new StringWriter())
using (var writer = new XmlTextWriter(stringWriter))
{
    writer.WriteStartDocument();
    writer.WriteStartElement("Items");

    var previous = Array.Empty<string>();
    foreach (var str in strings)
    {
        var current = str.Split('\\', StringSplitOptions.RemoveEmptyEntries);
        int i;
        // Find where the first difference from the previous element is
        for (i = 0; i < Math.Min(current.Length, previous.Length); i++)
        {
            if (current[i] != previous[i])
            {
                break;
            }
        }
        // i now contains the index of the first difference
        // First, close off anything in previous which isn't in the current
        for (int j = i; j < previous.Length; j++)
        {
            writer.WriteEndElement();
        }
        // Then, any new elements
        for (int j = i; j < current.Length; j++)
        {
            writer.WriteStartElement("Item");
            writer.WriteAttributeString("value", current[j]);
        }

        previous = current;
    }

    writer.WriteEndDocument();
}
</code>```

Gives:

```<code><?xml version="1.0" encoding="utf-16"?>
<Items>
    <Item value="networkAdd">
        <Item value="users">
            <Item value="test1">
                <Item value="delete unicode character test">
                    <Item value="character test 1">
                        <Item value="linked to folder" />
                    </Item>
                    <Item value="character test 2" />
                    <Item value="character test 3" />
                </Item>
            </Item>
        </Item>
    </Item>
    <Item value="http:">
        <Item value="sp2013">
            <Item value="newTestsite" />
            <Item value="newTestlib">
                <Item value="sampleFolder" />
            </Item>
        </Item>
    </Item>
</Items>
</code>```

It needs a bit of work around handling :// etc, but the basic principle should be sound.

Body:
I have a list of folder paths coming from a database that I need to export to xml.  The raw data looks as follows:

What I need to do is create a tree like structure, similar to this within the xml:

 - networkAdd
    - users
        - test1
           - delete unicode character test
                 - character test 1
                        - linked to folder
                 - character test 2
                 - character test 3
 - sp2013
    - newTestsite
        - newTestLib
           - sampleFolder
           - Renamed at source again
           - SecurityTest2013Folder
        - Shared Documents
           - sample.folder

I have current got an efficient xml write method available to me BUT it requires a treeview.  I took the list above (coming from the database) and converted it to a treeview that could be used with this method (which works fine) but it requires me to convert to a treeview first which is inefficient.  I use this code:

public static TreeView PopulateTreeView(IEnumerable<FolderInfo> paths)
{
    var treeView = new TreeView();
    treeView.PathSeparator = "\\";

    TreeNode lastNode = null;
    string subPathAgg;
    string lastRootFolder = null;

    foreach (var item in paths)
    {
        var path = item.FolderName; // folder path.

        if (lastRootFolder != item.FolderRoot)
        {
            lastRootFolder = item.FolderRoot;
            lastNode = null;
        }

        subPathAgg = string.Empty;
        foreach (string subPath in path.Split('\\'))
        {
            if (subPath.Length > 0)
            {
                subPathAgg += subPath + "\\";
                TreeNode[] nodes = treeView.Nodes.Find(subPathAgg, true);

                var newNode = new TreeNode
                {
                    Name = subPathAgg,
                    Text = subPath,
                    ImageIndex = 2,
                    ToolTipText = item.FullFolderPath
                };

                if (nodes.Length == 0)
                {
                    if (lastNode == null)
                        treeView.Nodes.Add(newNode);
                    else
                        lastNode.Nodes.Add(newNode);

                    lastNode = newNode;
                }
                else
                    lastNode = nodes[0];
            }
        }
    }

    return treeView;
}

This line of code becomes very slow to execute when I have over 10 million records to process:
TreeNode[] nodes = treeView.Nodes.Find(subPathAgg, true);

It would be much more efficient for me to convert straight from DB to XML (without the treeview middle man).

Has anyone any advice on an alternative way of parsing folder paths into xml, taking nesting into consideration?  Thanks for any pointers in advance!

Body:
Turns out, if you can ensure that your strings are properly sorted (which should be easy if they're coming from a DB), this is pretty easy if you work directly with an XmlWriter. Something like:

var strings = new[]
{
    @"\\networkAdd",
    @"\\networkAdd\users",
    @"\\networkAdd\users\test1\",
    @"\\networkAdd\users\test1\delete unicode character test",
    @"\\networkAdd\users\test1\delete unicode character test\character test 1",
    @"\\networkAdd\users\test1\delete unicode character test\character test 1\linked to folder",
    @"\\networkAdd\users\test1\delete unicode character test\character test 2",
    @"\\networkAdd\users\test1\delete unicode character test\character test 3",
    @"http:\\sp2013",
    @"http:\\sp2013\newTestsite",
    @"http:\\sp2013\newTestlib",
    @"http:\\sp2013\newTestlib\sampleFolder",
};

// Obviously, stream it out to a file rather than an in-memory string
using (var stringWriter = new StringWriter())
using (var writer = new XmlTextWriter(stringWriter))
{
    writer.WriteStartDocument();
    writer.WriteStartElement("Items");

    var previous = Array.Empty<string>();
    foreach (var str in strings)
    {
        var current = str.Split('\\', StringSplitOptions.RemoveEmptyEntries);
        int i;
        // Find where the first difference from the previous element is
        for (i = 0; i < Math.Min(current.Length, previous.Length); i++)
        {
            if (current[i] != previous[i])
            {
                break;
            }
        }
        // i now contains the index of the first difference
        // First, close off anything in previous which isn't in the current
        for (int j = i; j < previous.Length; j++)
        {
            writer.WriteEndElement();
        }
        // Then, any new elements
        for (int j = i; j < current.Length; j++)
        {
            writer.WriteStartElement("Item");
            writer.WriteAttributeString("value", current[j]);
        }

        previous = current;
    }

    writer.WriteEndDocument();
}

Gives:

<?xml version="1.0" encoding="utf-16"?>
<Items>
    <Item value="networkAdd">
        <Item value="users">
            <Item value="test1">
                <Item value="delete unicode character test">
                    <Item value="character test 1">
                        <Item value="linked to folder" />
                    </Item>
                    <Item value="character test 2" />
                    <Item value="character test 3" />
                </Item>
            </Item>
        </Item>
    </Item>
    <Item value="http:">
        <Item value="sp2013">
            <Item value="newTestsite" />
            <Item value="newTestlib">
                <Item value="sampleFolder" />
            </Item>
        </Item>
    </Item>
</Items>

It needs a bit of work around handling :// etc, but the basic principle should be sound.


问:
MongoDB If condition as the second field in gt
I want to select the $user_a_seen_at field if $user_a_id == socket.user_id otherwise select the $user_b_seen_at field. But my query isn't working.

$gt: ["$$this.created_at", IF CONDITION TO SELECT A FIELD ]

```<code>$project: {
    unread_messages: {
        $size: {
            $filter: {
                input: "$messages",
                cond: {
                    $and: [
                        { $eq: ["$$this.to_id", socket.user_id] },
                        {
                            $gt: [
                                "$$this.created_at", {
                                    if: { $eq: ["$user_a_id", socket.user_id] },
                                    then: "$user_a_seen_at",
                                    else: "$user_b_seen_at"
                                }
                            ]
                        }
                    ]
                }
            }
        }
    }
}
</code>```

Sample data

```<code>{
   "_id" : ObjectId("5e4c57649fad2e2cac9f8cd5"),
   "user_a_id" : 1,
   "user_b_id" : 2,
   "user_a_seen_at" : ISODate("2020-02-18T21:30:12.418Z"),
   "user_b_seen_at" : ISODate("2020-02-18T15:30:12.418Z"),
   "messages" : [
                {
                        "text" : "Hello",
                        "_id" : ObjectId("5e4c57649fad2e2cac9f8cd4"),
                        "from_id" : 1,
                        "to_id" : 2,
                        "created_at" : ISODate("2020-02-18T21:30:12.409Z")
                }
        ],
    "created_at" : ISODate("2020-02-18T21:30:12.418Z"),
    "last_activity" : ISODate("2020-02-18T21:30:12.418Z"),
    "__v" : 0
}
</code>```

答:
You need to use $cond operator to evaluate a boolean expression to return one of the two specified return expressions

```<code>{ $cond: { if: <boolean-expression>, then: <true-case>, else: <false-case> } }
//or simplified
{ $cond: [ <boolean-expression>, <true-case>, <false-case> ] }
</code>```

```<code>db.collection.aggregate([
  {
    $project: {
      unread_messages: {
        $size: {
          $filter: {
            input: "$messages",
            cond: {
              $and: [
                {
                  $eq: [
                    "$$this.to_id",
                    socket.user_id
                  ]
                },
                {
                  $gt: [
                    "$$this.created_at",
                    {
                      $cond: [
                        {
                          $eq: [
                            "$user_a_id",
                            socket.user_id
                          ]
                        },
                        "$user_a_seen_at",
                        "$user_b_seen_at"
                      ]
                    }
                  ]
                }
              ]
            }
          }
        }
      }
    }
  }
])
</code>```

MongoPlayground

Body:
I want to select the $user_a_seen_at field if $user_a_id == socket.user_id otherwise select the $user_b_seen_at field. But my query isn't working.

$gt: ["$$this.created_at", IF CONDITION TO SELECT A FIELD ]

$project: {
    unread_messages: {
        $size: {
            $filter: {
                input: "$messages",
                cond: {
                    $and: [
                        { $eq: ["$$this.to_id", socket.user_id] },
                        {
                            $gt: [
                                "$$this.created_at", {
                                    if: { $eq: ["$user_a_id", socket.user_id] },
                                    then: "$user_a_seen_at",
                                    else: "$user_b_seen_at"
                                }
                            ]
                        }
                    ]
                }
            }
        }
    }
}

Sample data

{
   "_id" : ObjectId("5e4c57649fad2e2cac9f8cd5"),
   "user_a_id" : 1,
   "user_b_id" : 2,
   "user_a_seen_at" : ISODate("2020-02-18T21:30:12.418Z"),
   "user_b_seen_at" : ISODate("2020-02-18T15:30:12.418Z"),
   "messages" : [
                {
                        "text" : "Hello",
                        "_id" : ObjectId("5e4c57649fad2e2cac9f8cd4"),
                        "from_id" : 1,
                        "to_id" : 2,
                        "created_at" : ISODate("2020-02-18T21:30:12.409Z")
                }
        ],
    "created_at" : ISODate("2020-02-18T21:30:12.418Z"),
    "last_activity" : ISODate("2020-02-18T21:30:12.418Z"),
    "__v" : 0
}

Body:
You need to use $cond operator to evaluate a boolean expression to return one of the two specified return expressions

{ $cond: { if: <boolean-expression>, then: <true-case>, else: <false-case> } }
//or simplified
{ $cond: [ <boolean-expression>, <true-case>, <false-case> ] }

db.collection.aggregate([
  {
    $project: {
      unread_messages: {
        $size: {
          $filter: {
            input: "$messages",
            cond: {
              $and: [
                {
                  $eq: [
                    "$$this.to_id",
                    socket.user_id
                  ]
                },
                {
                  $gt: [
                    "$$this.created_at",
                    {
                      $cond: [
                        {
                          $eq: [
                            "$user_a_id",
                            socket.user_id
                          ]
                        },
                        "$user_a_seen_at",
                        "$user_b_seen_at"
                      ]
                    }
                  ]
                }
              ]
            }
          }
        }
      }
    }
  }
])

MongoPlayground


问:
move the text downwards using css and setInterval
using CSS and setinterval, I need to move the text downwards with a "start" button.
suppose, there is a text box and when I press the start button the text should move downwards and when I press stop button, it should stop the text motion. </p>

```<code><style>
.class1{
    position: relative;
    padding-top: 10px;
}
<body>
    <p input id="para">Paragraph</p>
    <button id="srt" onclick="start()" >Start</button>
    <button id="stp" onclick="stop()">Stop</button>
    <script>
        var i=document.getElementById("para");
        setInterval(function start(){
            i.className="class1";
        },1000)
    </script>
</body>
</code>```

答:
Here is a crude solution that uses setInterval and CSS to create an animation:

let intervalId;

const increaseMarginTop = () => {
  const el = document.querySelector('#targetEl');
  const currentMarginTop = Number(el.style.marginTop.substring(0, el.style.marginTop.length - 2)) + 1;

  el.style.marginTop = `${currentMarginTop}px`;
};

document.addEventListener('click', e => {
  if (e.target.tagName === 'BUTTON') {
    if (e.target.id === 'stp') {
      intervalId = clearInterval(intervalId);
    } else if (e.target.id === 'srt') {
      if (!intervalId) {
        intervalId = setInterval(increaseMarginTop, 10);
      }
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="srt">Start</button>
<button id="stp">Stop</button>

<div id="targetEl">This will move down</div></code>```

Just FYI - there are better ways to do animations in modern JavaScript.

Body:
Here is a crude solution that uses setInterval and CSS to create an animation:

let intervalId;

const increaseMarginTop = () => {
  const el = document.querySelector('#targetEl');
  const currentMarginTop = Number(el.style.marginTop.substring(0, el.style.marginTop.length - 2)) + 1;

  el.style.marginTop = `${currentMarginTop}px`;
};

document.addEventListener('click', e => {
  if (e.target.tagName === 'BUTTON') {
    if (e.target.id === 'stp') {
      intervalId = clearInterval(intervalId);
    } else if (e.target.id === 'srt') {
      if (!intervalId) {
        intervalId = setInterval(increaseMarginTop, 10);
      }
    }
  }
});

<button id="srt">Start</button>
<button id="stp">Stop</button>

<div id="targetEl">This will move down</div>

Just FYI - there are better ways to do animations in modern JavaScript.


问:
Function to add character between concatenation of strings
Is there a more simplistic way to add characters throughout an string at the time of concatenation? I'm thinking of utilizing an function to do this and can achieve it by doing a concatenation; however, is there an kind of alternative that can be done other than concatenation?

Here is what I need to do...There is Table A which has 8 columns, for this example col1, col2, col3, etc.

```<code>;WITH
 TABLE_A
 AS
 (
  SELECT 'ABC' AS Col1
         , 'COM' AS Col2
         , 'SMALL' AS Col3
         , '1234' AS Col4
         , 'ABC INC.' AS Col5
         , '123456789' AS Col6
         , 'ABC Of New England' AS Col7
         , 'NC123456' AS Col8
 )
  SELECT *
  FROM TABLE_A
</code>```

I need to concatenate the values within the columns with an > between each. I can accomplish this by doing something along the lines of...

```<code>CONCAT(Col1,'>',Col2,'>',Col3,'>',Col4,'^',Col5,'>',Col6,'>',Col7,'>',Col8)
</code>```

but I need it to be dynamic, so for example if col1 - Col3 has a value then the concatenation has to occur for only those CONCAT(Col1,'>',Col2,'>',Col3) and if Col1 - Col5 has values then CONCAT(Col1,'>',Col2,'>',Col3,'>',Col4,'^',Col5) and so on, the concatenation should only go as far as there are values.

Also to add another wrinkle, instead of an > between Col4 and Col5, I need to have a carrot ^ as the delimiter.

Is there an alternative method to do this without using CONCAT? Maybe a loop?

答:
Here's an example of something that will work, although it only has minimal validation to meet your requirements.

```<code>;WITH
 TABLE_A
 AS
 (
  SELECT 'ABC' AS Col1
         , 'COM' AS Col2
         , 'SMALL' AS Col3
         , '1234' AS Col4
         , 'ABC INC.' AS Col5
         , '123456789' AS Col6
         , 'ABC Of New England' AS Col7
         , 'NC123456' AS Col8

 )
  SELECT ConcentenatedString = ISNULL(('>' + NULLIF(a.Col1,'')),'')
        +ISNULL(('>' + NULLIF(a.Col2,'')),'')
        +ISNULL(('>' + NULLIF(a.Col3,'')),'')
        +ISNULL(('>' + NULLIF(a.Col4,'')),'')
        +ISNULL(('^' + NULLIF(a.Col5,'')),'')
        +ISNULL(('>' + NULLIF(a.Col6,'')),'')
        +ISNULL(('>' + NULLIF(a.Col7,'')),'')
        +ISNULL(('>' + NULLIF(a.Col8,'')),'')
  FROM TABLE_A a
</code>```

The NULLIFs are used to convert a blank string to a NULL so that the delimiter will be eliminated when concatenated to the NULL. Those NULLs are then converted back to blanks to prevent the rest of the string from being eliminated.

Body:
Is there a more simplistic way to add characters throughout an string at the time of concatenation? I'm thinking of utilizing an function to do this and can achieve it by doing a concatenation; however, is there an kind of alternative that can be done other than concatenation?

Here is what I need to do...There is Table A which has 8 columns, for this example col1, col2, col3, etc.

;WITH
 TABLE_A
 AS
 (
  SELECT 'ABC' AS Col1
         , 'COM' AS Col2
         , 'SMALL' AS Col3
         , '1234' AS Col4
         , 'ABC INC.' AS Col5
         , '123456789' AS Col6
         , 'ABC Of New England' AS Col7
         , 'NC123456' AS Col8
 )
  SELECT *
  FROM TABLE_A

I need to concatenate the values within the columns with an > between each. I can accomplish this by doing something along the lines of...

CONCAT(Col1,'>',Col2,'>',Col3,'>',Col4,'^',Col5,'>',Col6,'>',Col7,'>',Col8)

but I need it to be dynamic, so for example if col1 - Col3 has a value then the concatenation has to occur for only those CONCAT(Col1,'>',Col2,'>',Col3) and if Col1 - Col5 has values then CONCAT(Col1,'>',Col2,'>',Col3,'>',Col4,'^',Col5) and so on, the concatenation should only go as far as there are values.

Also to add another wrinkle, instead of an > between Col4 and Col5, I need to have a carrot ^ as the delimiter.

Is there an alternative method to do this without using CONCAT? Maybe a loop?

Body:
Here's an example of something that will work, although it only has minimal validation to meet your requirements.

;WITH
 TABLE_A
 AS
 (
  SELECT 'ABC' AS Col1
         , 'COM' AS Col2
         , 'SMALL' AS Col3
         , '1234' AS Col4
         , 'ABC INC.' AS Col5
         , '123456789' AS Col6
         , 'ABC Of New England' AS Col7
         , 'NC123456' AS Col8

 )
  SELECT ConcentenatedString = ISNULL(('>' + NULLIF(a.Col1,'')),'')
        +ISNULL(('>' + NULLIF(a.Col2,'')),'')
        +ISNULL(('>' + NULLIF(a.Col3,'')),'')
        +ISNULL(('>' + NULLIF(a.Col4,'')),'')
        +ISNULL(('^' + NULLIF(a.Col5,'')),'')
        +ISNULL(('>' + NULLIF(a.Col6,'')),'')
        +ISNULL(('>' + NULLIF(a.Col7,'')),'')
        +ISNULL(('>' + NULLIF(a.Col8,'')),'')
  FROM TABLE_A a

The NULLIFs are used to convert a blank string to a NULL so that the delimiter will be eliminated when concatenated to the NULL. Those NULLs are then converted back to blanks to prevent the rest of the string from being eliminated.