问:
How to keep secret key information out of Git repository
I have some files in my repository, and one contains a secret Adafruit key. I want to use Git to store my repository, but I don't want to publish the key.

What's the best way to keep it secret, without having to blank it out everytime I commit and push something?

答:
If you don't have too many secrets to manage, and you do want to keep the secrets in version control, I make the parent repository private.  It contains 2 folders - a secrets folder, and a gitsubmodule for the public repository (in another folder).  I use ansible crypt to encrypt anything in the secrets folder, and a bash script to pass the decrypted contents, and load those secrets as environment vars to ensure the secrets file always stays encrypted.

Ansible crypt can encrypt and decrypt an environment variable, which I wrap in a bash script to do these functions like so-

```<code>testsecret=$(echo 'this is a test secret' | ./scripts/ansible-encrypt.sh --vault-id $vault_key --encrypt)
result=$(./scripts/ansible-encrypt.sh --vault-id $vault_key --decrypt $testsecret)
echo $result
</code>```

testsecret here is the encrypted base64 result, and it can be stored safely in a text file.  Later you could source that file to keep the encrypted result in memory, and finally when you need to use the secret, you can decrypt it ./scripts/ansible-encrypt.sh --vault-id $vault_key --decrypt $testsecret

This bash script referenced above is below (ansible-encrypt.sh).  It wraps ansible crypt functions in a way that can store encrypted variables in base64 which resolves some problems that can occur with encoding.

```<code>#!/bin/bash

# This scripts encrypts an input hidden from the shell and base 64 encodes it so it can be stored as an environment variable
# Optionally can also decrypt an environment variable

vault_id_func () {
    if [[ "$verbose" == true ]]; then
        echo "Parsing vault_id_func option: '--${opt}', value: '${val}'" >&2;
    fi
    vault_key="${val}"
}
secret_name=secret
secret_name_func () {
    if [[ "$verbose" == true ]]; then
        echo "Parsing secret_name option: '--${opt}', value: '${val}'" >&2;
    fi
    secret_name="${val}"
}
decrypt=false
decrypt_func () {
    if [[ "$verbose" == true ]]; then
        echo "Parsing secret_name option: '--${opt}', value: '${val}'" >&2;
    fi
    decrypt=true
    encrypted_secret="${val}"
}

IFS='
'
optspec=":hv-:t:"

encrypt=false

parse_opts () {
    local OPTIND
    OPTIND=0
    while getopts "$optspec" optchar; do
        case "${optchar}" in
            -)
                case "${OPTARG}" in
                    vault-id)
                        val="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
                        opt="${OPTARG}"
                        vault_id_func
                        ;;
                    vault-id=*)
                        val=${OPTARG#*=}
                        opt=${OPTARG%=$val}
                        vault_id_func
                        ;;
                    secret-name)
                        val="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
                        opt="${OPTARG}"
                        secret_name_func
                        ;;
                    secret-name=*)
                        val=${OPTARG#*=}
                        opt=${OPTARG%=$val}
                        secret_name_func
                        ;;
                    decrypt)
                        val="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
                        opt="${OPTARG}"
                        decrypt_func
                        ;;
                    decrypt=*)
                        val=${OPTARG#*=}
                        opt=${OPTARG%=$val}
                        decrypt_func
                        ;;
                    encrypt)
                        encrypt=true
                        ;;
                    *)
                        if [ "$OPTERR" = 1 ] && [ "${optspec:0:1}" != ":" ]; then
                            echo "Unknown option --${OPTARG}" >&2
                        fi
                        ;;
                esac;;
            h)
                help
                ;;
            *)
                if [ "$OPTERR" != 1 ] || [ "${optspec:0:1}" = ":" ]; then
                    echo "Non-option argument: '-${OPTARG}'" >&2
                fi
                ;;
        esac
    done
}
parse_opts "$@"

if [[ "$encrypt" = true ]]; then
    read -s -p "Enter the string to encrypt: `echo $'\n> '`";
    secret=$(echo -n "$REPLY" | ansible-vault encrypt_string --vault-id $vault_key --stdin-name $secret_name | base64 -w 0)
    unset REPLY
    echo $secret
elif [[ "$decrypt" = true ]]; then
    result=$(echo $encrypted_secret | base64 -d | /snap/bin/yq r - "$secret_name" | ansible-vault decrypt --vault-id $vault_key)
    echo $result
else
    # if no arg is passed to encrypt or decrypt, then we a ssume the function will decrypt the firehawksecret env var
    encrypted_secret="${firehawksecret}"
    result=$(echo $encrypted_secret | base64 -d | /snap/bin/yq r - "$secret_name" | ansible-vault decrypt --vault-id $vault_key)
    echo $result
fi
</code>```

Storing encrypted values as environment variables is much more secure than decrypting something at rest and leaving the plaintext result in memory.  That's extremely easy for any process to siphon off.

If you only wish to share the code with others and not the secrets, you can use a git template for the parent private repo structure so that others can inherit that structure, but use their own secrets.  This also allows CI to pickup everything you would need for your tests.

Alternatively, If you don't want your secrets in version control, you can simply use git ignore on a containing folder that will house your secrets.

Personally, this makes me nervous, its possible for user error to still result in publicly committed secrets, since those files are still under the root of a public repo, any number of things could go wrong that could be embarrassing with that approach.

Body:
If you don't have too many secrets to manage, and you do want to keep the secrets in version control, I make the parent repository private.  It contains 2 folders - a secrets folder, and a gitsubmodule for the public repository (in another folder).  I use ansible crypt to encrypt anything in the secrets folder, and a bash script to pass the decrypted contents, and load those secrets as environment vars to ensure the secrets file always stays encrypted.

Ansible crypt can encrypt and decrypt an environment variable, which I wrap in a bash script to do these functions like so-

testsecret=$(echo 'this is a test secret' | ./scripts/ansible-encrypt.sh --vault-id $vault_key --encrypt)
result=$(./scripts/ansible-encrypt.sh --vault-id $vault_key --decrypt $testsecret)
echo $result

testsecret here is the encrypted base64 result, and it can be stored safely in a text file.  Later you could source that file to keep the encrypted result in memory, and finally when you need to use the secret, you can decrypt it ./scripts/ansible-encrypt.sh --vault-id $vault_key --decrypt $testsecret

This bash script referenced above is below (ansible-encrypt.sh).  It wraps ansible crypt functions in a way that can store encrypted variables in base64 which resolves some problems that can occur with encoding.

#!/bin/bash

# This scripts encrypts an input hidden from the shell and base 64 encodes it so it can be stored as an environment variable
# Optionally can also decrypt an environment variable

vault_id_func () {
    if [[ "$verbose" == true ]]; then
        echo "Parsing vault_id_func option: '--${opt}', value: '${val}'" >&2;
    fi
    vault_key="${val}"
}
secret_name=secret
secret_name_func () {
    if [[ "$verbose" == true ]]; then
        echo "Parsing secret_name option: '--${opt}', value: '${val}'" >&2;
    fi
    secret_name="${val}"
}
decrypt=false
decrypt_func () {
    if [[ "$verbose" == true ]]; then
        echo "Parsing secret_name option: '--${opt}', value: '${val}'" >&2;
    fi
    decrypt=true
    encrypted_secret="${val}"
}

IFS='
'
optspec=":hv-:t:"

encrypt=false

parse_opts () {
    local OPTIND
    OPTIND=0
    while getopts "$optspec" optchar; do
        case "${optchar}" in
            -)
                case "${OPTARG}" in
                    vault-id)
                        val="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
                        opt="${OPTARG}"
                        vault_id_func
                        ;;
                    vault-id=*)
                        val=${OPTARG#*=}
                        opt=${OPTARG%=$val}
                        vault_id_func
                        ;;
                    secret-name)
                        val="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
                        opt="${OPTARG}"
                        secret_name_func
                        ;;
                    secret-name=*)
                        val=${OPTARG#*=}
                        opt=${OPTARG%=$val}
                        secret_name_func
                        ;;
                    decrypt)
                        val="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
                        opt="${OPTARG}"
                        decrypt_func
                        ;;
                    decrypt=*)
                        val=${OPTARG#*=}
                        opt=${OPTARG%=$val}
                        decrypt_func
                        ;;
                    encrypt)
                        encrypt=true
                        ;;
                    *)
                        if [ "$OPTERR" = 1 ] && [ "${optspec:0:1}" != ":" ]; then
                            echo "Unknown option --${OPTARG}" >&2
                        fi
                        ;;
                esac;;
            h)
                help
                ;;
            *)
                if [ "$OPTERR" != 1 ] || [ "${optspec:0:1}" = ":" ]; then
                    echo "Non-option argument: '-${OPTARG}'" >&2
                fi
                ;;
        esac
    done
}
parse_opts "$@"

if [[ "$encrypt" = true ]]; then
    read -s -p "Enter the string to encrypt: `echo $'\n> '`";
    secret=$(echo -n "$REPLY" | ansible-vault encrypt_string --vault-id $vault_key --stdin-name $secret_name | base64 -w 0)
    unset REPLY
    echo $secret
elif [[ "$decrypt" = true ]]; then
    result=$(echo $encrypted_secret | base64 -d | /snap/bin/yq r - "$secret_name" | ansible-vault decrypt --vault-id $vault_key)
    echo $result
else
    # if no arg is passed to encrypt or decrypt, then we a ssume the function will decrypt the firehawksecret env var
    encrypted_secret="${firehawksecret}"
    result=$(echo $encrypted_secret | base64 -d | /snap/bin/yq r - "$secret_name" | ansible-vault decrypt --vault-id $vault_key)
    echo $result
fi

Storing encrypted values as environment variables is much more secure than decrypting something at rest and leaving the plaintext result in memory.  That's extremely easy for any process to siphon off.

If you only wish to share the code with others and not the secrets, you can use a git template for the parent private repo structure so that others can inherit that structure, but use their own secrets.  This also allows CI to pickup everything you would need for your tests.

Alternatively, If you don't want your secrets in version control, you can simply use git ignore on a containing folder that will house your secrets.

Personally, this makes me nervous, its possible for user error to still result in publicly committed secrets, since those files are still under the root of a public repo, any number of things could go wrong that could be embarrassing with that approach.


来源: stackexchange

问:
FormType add field from entity relation
In my Symfony 4 project I have a ParametersAdmin entity which contains a OneToOne relation with the Entreprise entity.

    /**
     * @ORM\OneToOne(targetEntity="App\Entity\Entreprise", mappedBy="parametresAdmin", cascade={"persist", "remove"})
     */
    private $entreprise;
```

<p>The <strong>Entreprise</strong> entity has a <strong>nom</strong> field</p>

<p>In my form which is based on <strong>ParametresAdmin</strong> entity, I would like to include the <strong>entreprise.nom</strong> property.</p>

<p>So, I tried this :</p>

<pre class="lang-php prettyprint-override"><code>->add('entreprise', EntityType::class, [
                'label' => "Nom de l'entreprise",
                "class" => Entreprise::class,
                "choice_label" => "nom",
                "required" => false,
            ])
</code>```

I have now the nom value, but it's like a ChoiceType and not a TextType

答:
editing the value of a subentity of the entity you're editing is fairly easy.

you would have to change the type of the form to TextType, as you have probably already assumed, and give the form information on where the data is located on your "parent" entity, this can be done via the property_path option:

```<code>->add('entreprise_nom', TextType::class, [
      'label' => "Nom de l'entreprise",
      'property_path' => 'entreprise.nom', // <--- this
      'required' => false,
])
</code>```

entreprise.nom essentially tells the form component that it should first access the entreprise property on your entity, and on that value it should access the nom property (you can read more about this on the property access(or) doc page). It will also change (!) the nom property on entreprise, if the form is submitted and the entity manager flushed.

ContentLicense: CC BY-SA 4.0

Title: FormType add field from entity relation

Body:
In my Symfony 4 project I have a ParametersAdmin entity which contains a OneToOne relation with the Entreprise entity.

    /**
     * @ORM\OneToOne(targetEntity="App\Entity\Entreprise", mappedBy="parametresAdmin", cascade={"persist", "remove"})
     */
    private $entreprise;

The Entreprise entity has a nom field

In my form which is based on ParametresAdmin entity, I would like to include the entreprise.nom property.

So, I tried this :

->add('entreprise', EntityType::class, [
                'label' => "Nom de l'entreprise",
                "class" => Entreprise::class,
                "choice_label" => "nom",
                "required" => false,
            ])

I have now the nom value, but it's like a ChoiceType and not a TextType

Body:
editing the value of a subentity of the entity you're editing is fairly easy.

you would have to change the type of the form to TextType, as you have probably already assumed, and give the form information on where the data is located on your "parent" entity, this can be done via the property_path option:

->add('entreprise_nom', TextType::class, [
      'label' => "Nom de l'entreprise",
      'property_path' => 'entreprise.nom', // <--- this
      'required' => false,
])

entreprise.nom essentially tells the form component that it should first access the entreprise property on your entity, and on that value it should access the nom property (you can read more about this on the property access(or) doc page). It will also change (!) the nom property on entreprise, if the form is submitted and the entity manager flushed.


问:
How to call my method at a particular throughput in C#?
I am doing some performance testing so want to call my method at a particular throughput which I can control. With this way I can generate some load and figure out how it behaves under various throughput.

For example: I need to call my doIOStuff method at an approximate rate of x requests per second from multiple threads where x will be less than 2000 mostly but it really doesn't matter in this case. It doesn't have to be accurate so there is some room for an error but the overall idea is I need to make sure that my method doIOStuff is executed no more than x times in a sliding window of y seconds.

Below is the code I got where I am creating 3 different threads and that is calling doIOStuff method in parallel but not able to figure out how to rate limit this method for x requests per second. Is there an easy way where I can control this?

```<code>class Program
{
    static void Main(string[] args)
    {
        var tasks = new List<Task>();

        for(int i = 0; i< 100; i ++)
            tasks.Add(Task.Factory.StartNew(() => doIOStuff(), i));

        Task.WaitAll(tasks.ToArray());
        Console.WriteLine("All threads complete");
    }

    // how to call this method at a particular rate?
    static void doIOStuff()
    {
        // do some IO work
    }
}
</code>```

I want to keep running this test for some duration of time but during that duration it should always make calls to that method at a particular throughput only.

Note:

This is just an idea from me of generating random throughput which I can control but if this doesn't do things correctly then we should try to do it in a better and efficient way if possible but overall idea is to control the random throughput on my own and generate that much load to my method.

答:
Here is a method you could use to stress test an asynchronous doIOStuffAsync method:

```<code>public static async Task<long> StressTestAsync(
    Func<CancellationToken, Task> taskFactory,
    TimeSpan duration,
    int concurrencyLimit,
    int tasksStartedPerSecondLimit,
    IProgress<long> progress = default,
    CancellationToken cancellationToken = default)
{
    long successfullyCompletedCount = 0;
    using (var linkedCTS = CancellationTokenSource
        .CreateLinkedTokenSource(cancellationToken))
    using (var progressTimer = new System.Threading.Timer(_ =>
    {
        progress.Report(Interlocked.Read(ref successfullyCompletedCount));
    }))
    {
        var concurrencySemaphore = new SemaphoreSlim(concurrencyLimit);
        var perSecondSemaphore = new SemaphoreSlim(tasksStartedPerSecondLimit);
        var completionSemaphore = new SemaphoreSlim(0, 1);
        int pendingCount = 1; // The initial 1 represents the while loop
        var exceptions = new ConcurrentQueue<Exception>();
        linkedCTS.CancelAfter(duration);
        if (progress != null)
            progressTimer.Change(1000, 1000); // Report progress every second
        while (true)
        {
            try
            {
                await concurrencySemaphore.WaitAsync(linkedCTS.Token)
                    .ConfigureAwait(false);
                await perSecondSemaphore.WaitAsync(linkedCTS.Token)
                    .ConfigureAwait(false);
            }
            catch (OperationCanceledException) { break; }
            ReleaseSemaphoreAfterOneSecond();
            StartOneTask();
        }
        if (Interlocked.Decrement(ref pendingCount) == 0)
            completionSemaphore.Release();
        await completionSemaphore.WaitAsync().ConfigureAwait(false); // No token
        cancellationToken.ThrowIfCancellationRequested();
        if (!exceptions.IsEmpty) throw new AggregateException(exceptions);

        async void ReleaseSemaphoreAfterOneSecond()
        {
            try
            {
                await Task.Delay(1000, linkedCTS.Token).ConfigureAwait(false);
            }
            catch (OperationCanceledException) { } // Ignore
            finally
            {
                perSecondSemaphore.Release();
            }
        }

        async void StartOneTask()
        {
            Interlocked.Increment(ref pendingCount);
            try
            {
                var task = taskFactory(linkedCTS.Token);
                await task.ConfigureAwait(false);
                Interlocked.Increment(ref successfullyCompletedCount);
            }
            catch (OperationCanceledException) { } // Ignore
            catch (Exception ex)
            {
                exceptions.Enqueue(ex);
                linkedCTS.Cancel();
            }
            finally
            {
                if (Interlocked.Decrement(ref pendingCount) == 0)
                    completionSemaphore.Release();
                concurrencySemaphore.Release();
            }
        }

    }
    return Interlocked.Read(ref successfullyCompletedCount);
}
</code>```

Usage example:

```<code>await StressTestAsync(
    taskFactory: async ct => await doIOStuffAsync(ct),
    duration: TimeSpan.FromSeconds(30),
    concurrencyLimit: 1000,
    tasksStartedPerSecondLimit: 1000);
</code>```

The concurrencyLimit parameter is the maximum number of tasks that can be running concurrently at any given moment. The tasksStartedPerSecondLimit parameter is the maximum number of tasks that can be started during any 1-second time span. These two limits compete with each other, so normally only one of them will be the limiting factor of the throughput. If the tasks are fast, the concurrencyLimit will be the limiting factor. If the tasks are slow, the tasksStartedPerSecondLimit will be the limiting factor.

The StressTestAsync does not tolerate exceptions. Any exception thrown by the taskFactory method, or if any of the created tasks completes in a faulted state, will cause the termination of the test.

A Progress<long> can be passed as an optional argument, to propagate progress reports about the current number of successfully completed tasks.

Body:
I am doing some performance testing so want to call my method at a particular throughput which I can control. With this way I can generate some load and figure out how it behaves under various throughput.

For example: I need to call my doIOStuff method at an approximate rate of x requests per second from multiple threads where x will be less than 2000 mostly but it really doesn't matter in this case. It doesn't have to be accurate so there is some room for an error but the overall idea is I need to make sure that my method doIOStuff is executed no more than x times in a sliding window of y seconds.

Below is the code I got where I am creating 3 different threads and that is calling doIOStuff method in parallel but not able to figure out how to rate limit this method for x requests per second. Is there an easy way where I can control this?

class Program
{
    static void Main(string[] args)
    {
        var tasks = new List<Task>();

        for(int i = 0; i< 100; i ++)
            tasks.Add(Task.Factory.StartNew(() => doIOStuff(), i));

        Task.WaitAll(tasks.ToArray());
        Console.WriteLine("All threads complete");
    }

    // how to call this method at a particular rate?
    static void doIOStuff()
    {
        // do some IO work
    }
}

I want to keep running this test for some duration of time but during that duration it should always make calls to that method at a particular throughput only.

Note:

This is just an idea from me of generating random throughput which I can control but if this doesn't do things correctly then we should try to do it in a better and efficient way if possible but overall idea is to control the random throughput on my own and generate that much load to my method.

Body:
Here is a method you could use to stress test an asynchronous doIOStuffAsync method:

public static async Task<long> StressTestAsync(
    Func<CancellationToken, Task> taskFactory,
    TimeSpan duration,
    int concurrencyLimit,
    int tasksStartedPerSecondLimit,
    IProgress<long> progress = default,
    CancellationToken cancellationToken = default)
{
    long successfullyCompletedCount = 0;
    using (var linkedCTS = CancellationTokenSource
        .CreateLinkedTokenSource(cancellationToken))
    using (var progressTimer = new System.Threading.Timer(_ =>
    {
        progress.Report(Interlocked.Read(ref successfullyCompletedCount));
    }))
    {
        var concurrencySemaphore = new SemaphoreSlim(concurrencyLimit);
        var perSecondSemaphore = new SemaphoreSlim(tasksStartedPerSecondLimit);
        var completionSemaphore = new SemaphoreSlim(0, 1);
        int pendingCount = 1; // The initial 1 represents the while loop
        var exceptions = new ConcurrentQueue<Exception>();
        linkedCTS.CancelAfter(duration);
        if (progress != null)
            progressTimer.Change(1000, 1000); // Report progress every second
        while (true)
        {
            try
            {
                await concurrencySemaphore.WaitAsync(linkedCTS.Token)
                    .ConfigureAwait(false);
                await perSecondSemaphore.WaitAsync(linkedCTS.Token)
                    .ConfigureAwait(false);
            }
            catch (OperationCanceledException) { break; }
            ReleaseSemaphoreAfterOneSecond();
            StartOneTask();
        }
        if (Interlocked.Decrement(ref pendingCount) == 0)
            completionSemaphore.Release();
        await completionSemaphore.WaitAsync().ConfigureAwait(false); // No token
        cancellationToken.ThrowIfCancellationRequested();
        if (!exceptions.IsEmpty) throw new AggregateException(exceptions);

        async void ReleaseSemaphoreAfterOneSecond()
        {
            try
            {
                await Task.Delay(1000, linkedCTS.Token).ConfigureAwait(false);
            }
            catch (OperationCanceledException) { } // Ignore
            finally
            {
                perSecondSemaphore.Release();
            }
        }

        async void StartOneTask()
        {
            Interlocked.Increment(ref pendingCount);
            try
            {
                var task = taskFactory(linkedCTS.Token);
                await task.ConfigureAwait(false);
                Interlocked.Increment(ref successfullyCompletedCount);
            }
            catch (OperationCanceledException) { } // Ignore
            catch (Exception ex)
            {
                exceptions.Enqueue(ex);
                linkedCTS.Cancel();
            }
            finally
            {
                if (Interlocked.Decrement(ref pendingCount) == 0)
                    completionSemaphore.Release();
                concurrencySemaphore.Release();
            }
        }

    }
    return Interlocked.Read(ref successfullyCompletedCount);
}

Usage example:

await StressTestAsync(
    taskFactory: async ct => await doIOStuffAsync(ct),
    duration: TimeSpan.FromSeconds(30),
    concurrencyLimit: 1000,
    tasksStartedPerSecondLimit: 1000);

The concurrencyLimit parameter is the maximum number of tasks that can be running concurrently at any given moment. The tasksStartedPerSecondLimit parameter is the maximum number of tasks that can be started during any 1-second time span. These two limits compete with each other, so normally only one of them will be the limiting factor of the throughput. If the tasks are fast, the concurrencyLimit will be the limiting factor. If the tasks are slow, the tasksStartedPerSecondLimit will be the limiting factor.

The StressTestAsync does not tolerate exceptions. Any exception thrown by the taskFactory method, or if any of the created tasks completes in a faulted state, will cause the termination of the test.

A Progress<long> can be passed as an optional argument, to propagate progress reports about the current number of successfully completed tasks.


问:
How to delete folders that are older than some days using camel
I wanted to poll a directory and delete the files and folders that are older than a specified time. I wrote the following code :-

```<code>            from("file:input?filterFile=${date:file:yyyyMMddHHmm} <= ${date:now-240h:yyyyMMddHHmm}&delay=60000&delete=true")
            .log("The headers are ${headers}");
</code>```

It works fine for files and the old files are deleted but this does not work on folders. Can anyone suggest a way to make it work on folders also?

答:
For only for sub directories you can use you can try http://www.instanceofjava.com/2018/02/java-8-delete-folder-and-subfolders.html or something similar to

```<code>File directory = new File(dirWay);
if(directory.exists()){

File[] listFiles = directory.listFiles();
long purgeTime = System.currentTimeMillis() - (daysBack * 24 * 60 * 60 * 1000);

for(File listFile : listFiles) {
    if(listFile.lastModified() < purgeTime) {
      FileUtils.forceDelete(new File(listFile.getPath())); // or your way to delete
    }
  }
}
</code>```

public static void forceDelete(File file)
                        throws IOException

Deletes a file. If file is a directory, delete it and all sub-directories. https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FileUtils.html#forceDelete(java.io.File)

Body:
I wanted to poll a directory and delete the files and folders that are older than a specified time. I wrote the following code :-

            from("file:input?filterFile=${date:file:yyyyMMddHHmm} <= ${date:now-240h:yyyyMMddHHmm}&delay=60000&delete=true")
            .log("The headers are ${headers}");

It works fine for files and the old files are deleted but this does not work on folders. Can anyone suggest a way to make it work on folders also?

Body:
For only for sub directories you can use you can try http://www.instanceofjava.com/2018/02/java-8-delete-folder-and-subfolders.html or something similar to

File directory = new File(dirWay);
if(directory.exists()){

File[] listFiles = directory.listFiles();
long purgeTime = System.currentTimeMillis() - (daysBack * 24 * 60 * 60 * 1000);

for(File listFile : listFiles) {
    if(listFile.lastModified() < purgeTime) {
      FileUtils.forceDelete(new File(listFile.getPath())); // or your way to delete
    }
  }
}

public static void forceDelete(File file)
                        throws IOException

Deletes a file. If file is a directory, delete it and all sub-directories. https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FileUtils.html#forceDelete(java.io.File)


问:
How to get all values inside multidimensional array in PHP
I am working on online TV series website and can't figure out this one need to get values from array which is inside array.

This is structure contains $seasons variable:

```<code>Array
(
    [0] => Array
        (
            [0] => link1-1
            [1] => link1-2
            [2] => link1-3
        )

    [1] => Array
        (
            [0] => link2-1
            [1] => link2-2
            [2] => link2-3
        )

)
</code>```

i need to get values like:

```<code>0
    link1-1
    link1-2
    link1-3
1
    link2-1
    link2-2
    link2-3
</code>```

and then put them inside html video tag, but i can't figure out how to get values correctly

tried:

```<code>while ($row = $result->fetch_assoc()) {

    $season_count = $row['season_count'];
    $seasons = array_map("str_getcsv", explode("___", $row['en_url']));
    array_shift($seasons);
    for($i = 0; $i < count($seasons); $i++){
        print_r($seasons[$i][*]); // i need equivalent of * to select all values of each array
    }
    break;
}
</code>```

答:
```<code>foreach ($seasons as $season){
    foreach ($season as $link) {
        echo '<video src="' . $link . '"><video>';
    }
}
</code>```

And next time - please formulate your task clearly.

Body:
I am working on online TV series website and can't figure out this one need to get values from array which is inside array.

This is structure contains $seasons variable:

Array
(
    [0] => Array
        (
            [0] => link1-1
            [1] => link1-2
            [2] => link1-3
        )

    [1] => Array
        (
            [0] => link2-1
            [1] => link2-2
            [2] => link2-3
        )

)

i need to get values like:

0
    link1-1
    link1-2
    link1-3
1
    link2-1
    link2-2
    link2-3

and then put them inside html video tag, but i can't figure out how to get values correctly

tried:

while ($row = $result->fetch_assoc()) {

    $season_count = $row['season_count'];
    $seasons = array_map("str_getcsv", explode("___", $row['en_url']));
    array_shift($seasons);
    for($i = 0; $i < count($seasons); $i++){
        print_r($seasons[$i][*]); // i need equivalent of * to select all values of each array
    }
    break;
}

Body:
foreach ($seasons as $season){
    foreach ($season as $link) {
        echo '<video src="' . $link . '"><video>';
    }
}

And next time - please formulate your task clearly.


问:
Don't redirect specific folder to https in .htaccess
On my web I am using HTTPS connection and in my .htaccess I specified the redirect from http to https like this:

```<code>RewriteCond %{HTTP:HTTPS} !on  [OR]
RewriteCond %{HTTP_HOST} ^example.com
RewriteRule (.*) https://www.example.com/$1 [R=301,QSA,L]
</code>```

This is working fine, so if someone enters the page with http, it will redirect to https.

But I want to exclude from this redirect one specific folder, let's say 'application'.

If I put it above the statement, the Rewriterule will redirect it. If I put it after, then the web is already redirected to https and I don't want to call redirect to http again.

So how can I exclude one folder?

The reason is, I have very often a TLS handshake taking more than 30 seconds on my web.
And the files in that application folders are API php files, which are only called from my mobile app, so they will never be shown in browser.

As there are serious connection issues from mobile app due to TLS problems, I want to call these files via http only to avoid TLS connection. I don't care about security in these files, however I want to keep the rest of my web with https.

答:
Well, I think I found some solution. I used that folder as an exception via !application:

```<code>RewriteCond %{HTTPS} !on
RewriteCond %{THE_REQUEST} !application [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]
</code>```

Still testing, but seems working fine. Hope I am doing it the right way.

Body:
On my web I am using HTTPS connection and in my .htaccess I specified the redirect from http to https like this:

RewriteCond %{HTTP:HTTPS} !on  [OR]
RewriteCond %{HTTP_HOST} ^example.com
RewriteRule (.*) https://www.example.com/$1 [R=301,QSA,L]

This is working fine, so if someone enters the page with http, it will redirect to https.

But I want to exclude from this redirect one specific folder, let's say 'application'.

If I put it above the statement, the Rewriterule will redirect it. If I put it after, then the web is already redirected to https and I don't want to call redirect to http again.

So how can I exclude one folder?

The reason is, I have very often a TLS handshake taking more than 30 seconds on my web.
And the files in that application folders are API php files, which are only called from my mobile app, so they will never be shown in browser.

As there are serious connection issues from mobile app due to TLS problems, I want to call these files via http only to avoid TLS connection. I don't care about security in these files, however I want to keep the rest of my web with https.

Body:
Well, I think I found some solution. I used that folder as an exception via !application:

RewriteCond %{HTTPS} !on
RewriteCond %{THE_REQUEST} !application [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]

Still testing, but seems working fine. Hope I am doing it the right way.


问:
Convert to Ascii. Extended ASCII characters not working. C language
Extended 8-bit ASCII characters are not working
I'm trying to make a table with
putchar(218); putchar(196); putchar(194);
Instead of lines or ascii char i get Ĵ and Ŀ.
Everything i've tried was not working.</p>

答: input / output. There is not much to explain . Extended ASCII chars are not displayed at all. That L or J is a random combination.</p>


问:
pd.read_feather problems with decimal / thousands separator and rounding problems for floats
I'd like to use .ftr files to quickly analyze hundreds of tables. Unfortunately I have some problems with decimal and thousands separator, similar to that post, just that read_feather does not allow for decimal=',', thousands='.' options. I've tried the following approaches:

```<code>df['numberofx'] = (
    df['numberofx']
    .apply(lambda x: x.str.replace(".","", regex=True)
                      .str.replace(",",".", regex=True))
</code>```

resulting in

```<code>AttributeError: 'str' object has no attribute 'str'
</code>```

when I change it to

```<code>df['numberofx'] = (
    df['numberofx']
    .apply(lambda x: x.replace(".","").replace(",","."))
</code>```

I receive some strange (rounding) mistakes in the results, like 22359999999999998 instead of 2236 for some numbers that are higher than 1k. All below 1k are 10 times the real result, which is probably because of deleting the "." of the float and creating an int of that number.

Trying

```<code>df['numberofx'] = df['numberofx'].str.replace('.', '', regex=True)
</code>```

also leads to some strange behavior in the results, as some numbers are going in the 10^12 and others remain at 10^3 as they should.

Here is how I create my .ftr files from multiple Excel files. I know I could simply create DataFrames from the Excel files but that would slowdown my daily calculations to much.

How can I solve that issue?

EDIT: The issue seems to come from reading in an excel file as df  with non US standard regarding decimal and thousands separator and than saving it as feather. using pd.read_excel(f, encoding='utf-8', decimal=',', thousands='.') options for reading in the excel file solved my issue. That leads to the next question:

why does saving floats in a feather file lead to strange rounding errors like changing 2.236 to 2.2359999999999998?

答:
As mentioned in my edit here is what solved my initial problem:

```<code>path = r"pathname\*_somename*.xlsx"
file_list = glob.glob(path)
for f in file_list:
    df = pd.read_excel(f, encoding='utf-8', decimal=',', thousands='.')
    for col in df.columns:
            w= (df[[col]].applymap(type) != df[[col]].iloc[0].apply(type)).any(axis=1)
            if len(df[w]) > 0:

                df[col] = df[col].astype(str)

            if df[col].dtype == list:
                df[col] = df[col].astype(str)
    pathname = f[:-4] + "ftr"
    df.to_feather(pathname)
df.head()

</code>```

I had to add the decimal=',', thousands='.' option for reading in an excel file, which I later saved as feather. So the problem did not arise when working with .ftr files but before. The rounding problems seem to come from saving numbers with different decimal and thousand separators as .ftr files.

Body:
I'd like to use .ftr files to quickly analyze hundreds of tables. Unfortunately I have some problems with decimal and thousands separator, similar to that post, just that read_feather does not allow for decimal=',', thousands='.' options. I've tried the following approaches:

df['numberofx'] = (
    df['numberofx']
    .apply(lambda x: x.str.replace(".","", regex=True)
                      .str.replace(",",".", regex=True))

resulting in

AttributeError: 'str' object has no attribute 'str'

when I change it to

df['numberofx'] = (
    df['numberofx']
    .apply(lambda x: x.replace(".","").replace(",","."))

I receive some strange (rounding) mistakes in the results, like 22359999999999998 instead of 2236 for some numbers that are higher than 1k. All below 1k are 10 times the real result, which is probably because of deleting the "." of the float and creating an int of that number.

Trying

df['numberofx'] = df['numberofx'].str.replace('.', '', regex=True)

also leads to some strange behavior in the results, as some numbers are going in the 10^12 and others remain at 10^3 as they should.

Here is how I create my .ftr files from multiple Excel files. I know I could simply create DataFrames from the Excel files but that would slowdown my daily calculations to much.

How can I solve that issue?

EDIT: The issue seems to come from reading in an excel file as df  with non US standard regarding decimal and thousands separator and than saving it as feather. using pd.read_excel(f, encoding='utf-8', decimal=',', thousands='.') options for reading in the excel file solved my issue. That leads to the next question:

why does saving floats in a feather file lead to strange rounding errors like changing 2.236 to 2.2359999999999998?

Body:
As mentioned in my edit here is what solved my initial problem:

path = r"pathname\*_somename*.xlsx"
file_list = glob.glob(path)
for f in file_list:
    df = pd.read_excel(f, encoding='utf-8', decimal=',', thousands='.')
    for col in df.columns:
            w= (df[[col]].applymap(type) != df[[col]].iloc[0].apply(type)).any(axis=1)
            if len(df[w]) > 0:

                df[col] = df[col].astype(str)

            if df[col].dtype == list:
                df[col] = df[col].astype(str)
    pathname = f[:-4] + "ftr"
    df.to_feather(pathname)
df.head()

I had to add the decimal=',', thousands='.' option for reading in an excel file, which I later saved as feather. So the problem did not arise when working with .ftr files but before. The rounding problems seem to come from saving numbers with different decimal and thousand separators as .ftr files.


问:
Python Merging Dataframes using multiple Columns
I have 2 dataframes that l need to merge intersecting multiple columns. I'm not getting the results l need as the resulting dataframe has mismatched dates.

I want to merge a pair of columns Date & Segment from dataframe1 to (tmcN & date) | (tmcP & date) from dataframe2 as common columns. Specifically column Segment will match either tmcN or tmcP while at the same time the Date column will be matched to date. I've tried several different ways and can't configure it properly.

My Code:

```<code>left2 = Speed.rename({'key':'Segment'}, axis=1)
right2 = Incident.rename({'key':'tmcN'}, axis=1)

Test = left2.merge(right2, left_on='Segment', right_on='tmcN', how='outer')
</code>```

This only matches Segment to tmcN and my laptop crashes when trying to double merge Segment to tmcP. Thank you for the assistance.

答:
You could try this ( assuming that df1 is the first dataframe and df2 is the second dataframe )

Using tmcN of the second dataframe

```<code>df = pd.merge(df1, df2, left_on=['Date', 'Segment'], right_on=['date', 'tmcN'])
</code>```

Using tmcP of the second dataframe

```<code>df = pd.merge(df1, df2, left_on=['Date', 'Segment'], right_on=['date', 'tmcP'])
</code>```

Body:
I have 2 dataframes that l need to merge intersecting multiple columns. I'm not getting the results l need as the resulting dataframe has mismatched dates.

I want to merge a pair of columns Date & Segment from dataframe1 to (tmcN & date) | (tmcP & date) from dataframe2 as common columns. Specifically column Segment will match either tmcN or tmcP while at the same time the Date column will be matched to date. I've tried several different ways and can't configure it properly.

My Code:

left2 = Speed.rename({'key':'Segment'}, axis=1)
right2 = Incident.rename({'key':'tmcN'}, axis=1)

Test = left2.merge(right2, left_on='Segment', right_on='tmcN', how='outer')

This only matches Segment to tmcN and my laptop crashes when trying to double merge Segment to tmcP. Thank you for the assistance.

Body:
You could try this ( assuming that df1 is the first dataframe and df2 is the second dataframe )

Using tmcN of the second dataframe

df = pd.merge(df1, df2, left_on=['Date', 'Segment'], right_on=['date', 'tmcN'])

Using tmcP of the second dataframe

df = pd.merge(df1, df2, left_on=['Date', 'Segment'], right_on=['date', 'tmcP'])


答:
There is a way to do it. While I am not very sure but it should work.</p>

```<code>df['date'] = pd.to_datetime(df['date'], format='%y-%m-%d')
start_date =[]
end_date = []
first_ittr = True;
index = 0

for i in df['date']:
    if(first_ittr):
        start_date[index] = i
        end_date[index]=i
        first_ittr = False

    elif(i>end_date):
        end_date[index] = i

    elif(i<start_date):
        start_date[index] = i

df['startdate'] = start_date
df['enddate'] = end_date
</code>```

Title: Create column of start date and end date from given date record

Body:
supposed my dataset

Name date
A    15-01-01
A    15-01-31
A    16-02-02
A    16-03-04
B    17-04-05
B    17-05-08
B    17-07-09
C    18-01-02
C    18-02-03

I want to add each person's first and last dates to a new column..

result what I want

Name date     startdate enddate
A    15-01-01 15-01-01  16-03-04
A    15-01-31 15-01-01  16-03-04
A    16-02-02 15-01-01  16-03-04
A    16-03-04 15-01-01  16-03-04
B    17-04-05 17-04-05  17-07-09
B    17-05-08 17-04-05  17-07-09
B    17-07-09 17-04-05  17-07-09
C    18-01-02 18-01-02  18-02-03
C    18-02-03 18-01-02  18-02-03

Is there a method to make this possible? I would appreciate it if you let me know.

thank you for reading

Body:
There is a way to do it. While I am not very sure but it should work.

df['date'] = pd.to_datetime(df['date'], format='%y-%m-%d')
start_date =[]
end_date = []
first_ittr = True;
index = 0

for i in df['date']:
    if(first_ittr):
        start_date[index] = i
        end_date[index]=i
        first_ittr = False

    elif(i>end_date):
        end_date[index] = i

    elif(i<start_date):
        start_date[index] = i

df['startdate'] = start_date
df['enddate'] = end_date


问:
Connection String and Datacontext in LINQ
I am developing a site using ASP.NET, SQL 2008 and LINQ. I want to ask about the connection string. I have made a class like that to get the datacontext in each page:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

public static class DatabaseConnection
{
    static DataClassesDataContext datacontext;
    public static DataClassesDataContext getConnection()
    {
       datacontext = new DataClassesDataContext(@"Data Source=localhost;Initial Catalog=dbname; Integrated Security=True");
        return datacontext;
    }
}
</code>```

Is that a correct way to get the connection in each page?

Also about 'Data Source', when I deploy the site what will it be? And what is the difference between data source and address keywords?

答:
Much better if you place your Connection string on your Web.Config File

```<code><?xml version="1.0"?>
<configuration>
    <configSections>
<connectionStrings>
    <add name="DB" connectionString="Data Source=localhost;Initial Catalog=dbname; Integrated Security=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>

</configuration>
</code>```

Have a look at this:

LINQ To SQL and the Web.Config ConnectionString Value

LINQ to SQL Connection Strings with class library projects

Regards

ContentLicense: CC BY-SA 3.0

Body:
I am developing a site using ASP.NET, SQL 2008 and LINQ. I want to ask about the connection string. I have made a class like that to get the datacontext in each page:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

public static class DatabaseConnection
{
    static DataClassesDataContext datacontext;
    public static DataClassesDataContext getConnection()
    {
       datacontext = new DataClassesDataContext(@"Data Source=localhost;Initial Catalog=dbname; Integrated Security=True");
        return datacontext;
    }
}

Is that a correct way to get the connection in each page?

Also about 'Data Source', when I deploy the site what will it be? And what is the difference between data source and address keywords?

Body:
Much better if you place your Connection string on your Web.Config File

<?xml version="1.0"?>
<configuration>
    <configSections>
<connectionStrings>
    <add name="DB" connectionString="Data Source=localhost;Initial Catalog=dbname; Integrated Security=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>

</configuration>

Have a look at this:

LINQ To SQL and the Web.Config ConnectionString Value

LINQ to SQL Connection Strings with class library projects

Regards


问:
How do I create an x-axis with Swift Charts with 1 unit per day instead of 1 unit per data point?
I have a chart that takes time series data.  The time series data is recorded at most once per day, but on an irregular schedule.  I.e., the data could look like this:

```<code>1/1, 1500
1/13, 1600
1/14, 1700
2/22, 1800
5/1, 1400
</code>```

Using Charts, my line graph populates the x-axis with one unit per data point (i.e., in the example above, there would be 5 units on the xaxis, instead of ~120 days)

How do I create the x-axis with units for all dates in range?

The code for my chart:

```<code>    func setChartData(data: ([String], [Double])) {
        var yVals1 = [ChartDataEntry]()
        for i in 0 ..< data.0.count {
            yVals1.append(ChartDataEntry(value: data.1[i], xIndex: i))
        }

        let set1: LineChartDataSet = LineChartDataSet(yVals: yVals1, label: nil)
        set1.axisDependency = .Left

        set1.setColor(UIColor(red:0.502, green:0.580, blue:0.784, alpha:1.000))
        set1.lineWidth = 2.0
        set1.fillAlpha = 1
        set1.fillColor = UIColor(red:0.502, green:0.580, blue:0.784, alpha:1.000)
        set1.highlightColor = UIColor.whiteColor()
        set1.drawValuesEnabled = false
        set1.drawCirclesEnabled = false
        set1.drawFilledEnabled = true

        var dataSets : [LineChartDataSet] = [LineChartDataSet]()
        dataSets.append(set1)

        let data: LineChartData = LineChartData(xVals: data.0, dataSets: dataSets)
        data.setValueTextColor(UIColor.whiteColor())

        let legend = lineChartView.legend
        legend.enabled = false

        let xAxis = lineChartView.xAxis
        xAxis.drawGridLinesEnabled = false
        xAxis.drawAxisLineEnabled = false
        xAxis.labelPosition = .Bottom

        let rightAxis = lineChartView.rightAxis
        rightAxis.drawAxisLineEnabled = false
        rightAxis.drawLabelsEnabled = false
        rightAxis.drawGridLinesEnabled = false

        let leftAxis = lineChartView.leftAxis
        leftAxis.drawAxisLineEnabled = false
        leftAxis.gridColor = UIColor.blackColor().colorWithAlphaComponent(0.1)
        leftAxis.gridLineWidth = 2

        self.lineChartView.data = data
    }
</code>```

答:
The accepted answer is obsolete due to Chart API changes.

ChartDataEntry values must consist of (x, y): (Double, Double) and cannot
contain String, though you use a custom display formatter to show the data instead.

Setup a MonthTimeXAxisValueFormatter which implements the protocol IAxisValueFormatter to return String values:

class MonthTimeXAxisValueFormatter: IAxisValueFormatter {
  func stringForValue(_ value: Double, axis: AxisBase?) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd MMM"
    let timeStamp = Date(timeIntervalSince1970: value)
    return dateFormatter.string(from: timeStamp)
  }
}
```

<pre class="lang-swift prettyprint-override"><code>// Setup the x-axis with this formatter.
lineChart.xAxis.valueFormatter = MonthTimeXAxisValueFormatter()

</code>```

The x-values here should be generated as:

  func chartDataPoints(from xYValues: [Date: Double]) -> [ChartDataEntry] {
    assert(!xYValues.isEmpty)
    var dataPoints: [ChartDataEntry] = []
    var startDate = xYValues.keys.sorted(by: <).first!
    let endDate = xYValues.keys.sorted(by: >).first!

    repeat {
      guard let yValue = xYValues[startDate] else {
        startDate = startDate.advanced(by: TimeInterval(24 * 60 * 60))
        continue
      }
      dataPoints.append(ChartDataEntry(x: Double(startDate.timeIntervalSince1970), y: yValue))
      startDate = startDate.advanced(by: TimeInterval(24 * 60 * 60))
    } while startDate <= endDate
    return dataPoints
  }
```

Body:
I have a chart that takes time series data.  The time series data is recorded at most once per day, but on an irregular schedule.  I.e., the data could look like this:

1/1, 1500
1/13, 1600
1/14, 1700
2/22, 1800
5/1, 1400

Using Charts, my line graph populates the x-axis with one unit per data point (i.e., in the example above, there would be 5 units on the xaxis, instead of ~120 days)

How do I create the x-axis with units for all dates in range?

The code for my chart:

    func setChartData(data: ([String], [Double])) {
        var yVals1 = [ChartDataEntry]()
        for i in 0 ..< data.0.count {
            yVals1.append(ChartDataEntry(value: data.1[i], xIndex: i))
        }

        let set1: LineChartDataSet = LineChartDataSet(yVals: yVals1, label: nil)
        set1.axisDependency = .Left

        set1.setColor(UIColor(red:0.502, green:0.580, blue:0.784, alpha:1.000))
        set1.lineWidth = 2.0
        set1.fillAlpha = 1
        set1.fillColor = UIColor(red:0.502, green:0.580, blue:0.784, alpha:1.000)
        set1.highlightColor = UIColor.whiteColor()
        set1.drawValuesEnabled = false
        set1.drawCirclesEnabled = false
        set1.drawFilledEnabled = true

        var dataSets : [LineChartDataSet] = [LineChartDataSet]()
        dataSets.append(set1)

        let data: LineChartData = LineChartData(xVals: data.0, dataSets: dataSets)
        data.setValueTextColor(UIColor.whiteColor())

        let legend = lineChartView.legend
        legend.enabled = false

        let xAxis = lineChartView.xAxis
        xAxis.drawGridLinesEnabled = false
        xAxis.drawAxisLineEnabled = false
        xAxis.labelPosition = .Bottom

        let rightAxis = lineChartView.rightAxis
        rightAxis.drawAxisLineEnabled = false
        rightAxis.drawLabelsEnabled = false
        rightAxis.drawGridLinesEnabled = false

        let leftAxis = lineChartView.leftAxis
        leftAxis.drawAxisLineEnabled = false
        leftAxis.gridColor = UIColor.blackColor().colorWithAlphaComponent(0.1)
        leftAxis.gridLineWidth = 2

        self.lineChartView.data = data
    }

Body:
The accepted answer is obsolete due to Chart API changes.

ChartDataEntry values must consist of (x, y): (Double, Double) and cannot
contain String, though you use a custom display formatter to show the data instead.

Setup a MonthTimeXAxisValueFormatter which implements the protocol IAxisValueFormatter to return String values:

class MonthTimeXAxisValueFormatter: IAxisValueFormatter {
  func stringForValue(_ value: Double, axis: AxisBase?) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd MMM"
    let timeStamp = Date(timeIntervalSince1970: value)
    return dateFormatter.string(from: timeStamp)
  }
}

// Setup the x-axis with this formatter.
lineChart.xAxis.valueFormatter = MonthTimeXAxisValueFormatter()

The x-values here should be generated as:

  func chartDataPoints(from xYValues: [Date: Double]) -> [ChartDataEntry] {
    assert(!xYValues.isEmpty)
    var dataPoints: [ChartDataEntry] = []
    var startDate = xYValues.keys.sorted(by: <).first!
    let endDate = xYValues.keys.sorted(by: >).first!

    repeat {
      guard let yValue = xYValues[startDate] else {
        startDate = startDate.advanced(by: TimeInterval(24 * 60 * 60))
        continue
      }
      dataPoints.append(ChartDataEntry(x: Double(startDate.timeIntervalSince1970), y: yValue))
      startDate = startDate.advanced(by: TimeInterval(24 * 60 * 60))
    } while startDate <= endDate
    return dataPoints
  }


问:
Update documents in a collection if one of the document field value exists in array
I have a collection1 with collection1Column and another column presentInArray1,

```<code>--------------------------------------------
| collection1Column | presentInArray1      |
--------------------------------------------
| A                 | null                 |
| B                 | null                 |
| C                 | null                 |
| D                 | null                 |
| E                 | null                 |
--------------------------------------------
</code>```

I have an array1 like this:

```<code>let array1 = ['A', 'C', 'D'];
</code>```

Now I need to update collection1's column presentInArray1 only if an exact match of collection1Column is found in array1. In the example given - the matches are A, C & D.

One possible javascript solution I have thought is the following:

Get all the values from both the collection & array.

Once the values are available, take up one by one values from collection1's collection1Column  and iterate on array1 to find a match.

Once the match is found, will update the presentInArray1 with true

In this scenario - How do I update documents in the collection collection1 if one of the document field collection1Column value exists in array1?

Also, here is the code I have tried so far:

```<code>collection1.update({
    'collection1Column': {
      $in: array1
    }
  }, {
    $set: {
      'presentInArray1': true
    }
  }, {
    multi: true
  },
  function(err, result) {
    if (err) throw err;
  });
</code>```

This also seems to be not working. I'm not sure why:

```<code>{"result":{"n":217,"nModified":0,"opTime":{"ts":"6833283007906840577","t":13},"electionId":"7fffffff000000000000000d","ok":1,"$clusterTime":{"clusterTime":"6833283007906840577","signature":{"hash":"W1KNoy0a9d2iTU3OiIa2jlc4y00=","keyId":"6803936209337843714"}},"operationTime":"6833283007906840577"},"connection":{"id":5,"host":"cluster0-shard-00-01-foobar.mongodb.net","port":27017},"modifiedCount":0,"upsertedId":null,"upsertedCount":0,"matchedCount":217,"n":217,"nModified":0,"opTime":{"ts":"6833283007906840577","t":13},"electionId":"7fffffff000000000000000d","ok":1,"$clusterTime":{"clusterTime":"6833283007906840577","signature":{"hash":"W1KNoy0a9d2iTU3OiIa2jlc4y00=","keyId":"6803936209337843714"}},"operationTime":"6833283007906840577"}
</code>```

This looks very expensive in terms of memory and performance to me.

Please suggest!

In simple words, how to perform V Lookup in MongoDB?

MongoDB server version: 4.2.6

答: I used updateMany instead of update and it works.

Body:
I have a collection1 with collection1Column and another column presentInArray1,

--------------------------------------------
| collection1Column | presentInArray1      |
--------------------------------------------
| A                 | null                 |
| B                 | null                 |
| C                 | null                 |
| D                 | null                 |
| E                 | null                 |
--------------------------------------------

I have an array1 like this:

let array1 = ['A', 'C', 'D'];

Now I need to update collection1's column presentInArray1 only if an exact match of collection1Column is found in array1. In the example given - the matches are A, C & D.

One possible javascript solution I have thought is the following:

Get all the values from both the collection & array.

Once the values are available, take up one by one values from collection1's collection1Column  and iterate on array1 to find a match.

Once the match is found, will update the presentInArray1 with true

In this scenario - How do I update documents in the collection collection1 if one of the document field collection1Column value exists in array1?

Also, here is the code I have tried so far:

collection1.update({
    'collection1Column': {
      $in: array1
    }
  }, {
    $set: {
      'presentInArray1': true
    }
  }, {
    multi: true
  },
  function(err, result) {
    if (err) throw err;
  });

This also seems to be not working. I'm not sure why:

{"result":{"n":217,"nModified":0,"opTime":{"ts":"6833283007906840577","t":13},"electionId":"7fffffff000000000000000d","ok":1,"$clusterTime":{"clusterTime":"6833283007906840577","signature":{"hash":"W1KNoy0a9d2iTU3OiIa2jlc4y00=","keyId":"6803936209337843714"}},"operationTime":"6833283007906840577"},"connection":{"id":5,"host":"cluster0-shard-00-01-foobar.mongodb.net","port":27017},"modifiedCount":0,"upsertedId":null,"upsertedCount":0,"matchedCount":217,"n":217,"nModified":0,"opTime":{"ts":"6833283007906840577","t":13},"electionId":"7fffffff000000000000000d","ok":1,"$clusterTime":{"clusterTime":"6833283007906840577","signature":{"hash":"W1KNoy0a9d2iTU3OiIa2jlc4y00=","keyId":"6803936209337843714"}},"operationTime":"6833283007906840577"}

This looks very expensive in terms of memory and performance to me.

Please suggest!

In simple words, how to perform V Lookup in MongoDB?

MongoDB server version: 4.2.6


问:
How to get all the elements of an association?
I have created a CDS views as follows:

```<code>define view YGAC_I_REQUEST_ROLE
  with parameters
    pm_req_id    : grfn_guid,
    @Consumption.defaultValue: 'ROL'
    pm_item_type : grac_prov_item_type,
    @Consumption.defaultValue: 'AP'
    pm_approval  : grac_approval_status
  as select from YGAC_I_REQ_PROVISION_ITEM as provitem

  association [1..1] to YGAC_I_ROLE as _Role on _Role.RoleId = provitem.ProvisionItemId

  association [1..*] to YGAC_I_ROLE_RS as _Relation on _Relation.RoleId1 = provitem.ProvisionItemId

{
  key ReqId,
  key ReqIdItem,
      Connector,
      ProvisionItemId,
      ActionType,
      ValidFrom,
      ValidTo,

      _Role.RoleId,
      _Role.RoleName,
      _Role.RoleType,

      _Role,
      _Relation
}
where
      ReqId             = $parameters.pm_req_id
  and ProvisionItemType = $parameters.pm_item_type
  and ApprovalStatus    = $parameters.pm_approval
</code>```

Then I have consumed in ABAP:

```<code>  SELECT
    FROM ygac_i_request_role( pm_req_id = @lv_test,
                              pm_item_type = @lv_item_type,
                              pm_approval = @lv_approval
                            )
    FIELDS reqid,
           connector,
           provisionitemid
  INTO TABLE @DATA(lt_result).
</code>```

How to get the list of _Relation according to selection above.

答:
This is generally not possible like in ABAP SQL queries:

```<code>SELECT m~*, kt~*
  FROM mara AS m
  JOIN makt AS kt
...
</code>```

This contradicts the whole idea of CDS associations, because they were created to join on-demand and to reduce redundant calls to database. Fetching all fields negates the whole idea of "lazy join".

However, there is another syntax in FROM clause which is enabled by path expressions that allows querying underlining associations both fully and by separate elements. Here is how

```<code>SELECT *
  FROM ygac_i_request_role( pm_req_id = @lv_test )
       \_Role AS role
  INTO TABLE @DATA(lt_result).
</code>```

This fetches all the fields of _Role association into internal table.

Note: remember, it is not possible to fetch all the published associations of current view simultaneously, only one path per query.

Possible workaround is to use JOIN

```<code>SELECT *
  FROM ygac_i_request_role AS main
  JOIN ygac_i_request_role
       \_Role AS role
    ON main~ProvisionItemId = role~RoleId
  JOIN ygac_i_request_role
       \_Relation AS relation
    ON main~ProvisionItemId = relation~RoleId1
  INTO TABLE @DATA(lt_table).
</code>```

This creates deep-structured type with dedicated structure for every join association like this:

If you are not comfortable with such structure for you task, lt_table should be declared statically to put up all the fields in a flat way

```<code>TYPES BEGIN OF ty_table.
        INCLUDE TYPE ygac_i_request_role.
        INCLUDE TYPE ygac_i_role.
        INCLUDE TYPE ygac_i_role_rs.
TYPES END OF ty_table.
</code>```

Body:
I have created a CDS views as follows:

define view YGAC_I_REQUEST_ROLE
  with parameters
    pm_req_id    : grfn_guid,
    @Consumption.defaultValue: 'ROL'
    pm_item_type : grac_prov_item_type,
    @Consumption.defaultValue: 'AP'
    pm_approval  : grac_approval_status
  as select from YGAC_I_REQ_PROVISION_ITEM as provitem

  association [1..1] to YGAC_I_ROLE as _Role on _Role.RoleId = provitem.ProvisionItemId

  association [1..*] to YGAC_I_ROLE_RS as _Relation on _Relation.RoleId1 = provitem.ProvisionItemId

{
  key ReqId,
  key ReqIdItem,
      Connector,
      ProvisionItemId,
      ActionType,
      ValidFrom,
      ValidTo,

      _Role.RoleId,
      _Role.RoleName,
      _Role.RoleType,

      _Role,
      _Relation
}
where
      ReqId             = $parameters.pm_req_id
  and ProvisionItemType = $parameters.pm_item_type
  and ApprovalStatus    = $parameters.pm_approval

Then I have consumed in ABAP:

  SELECT
    FROM ygac_i_request_role( pm_req_id = @lv_test,
                              pm_item_type = @lv_item_type,
                              pm_approval = @lv_approval
                            )
    FIELDS reqid,
           connector,
           provisionitemid
  INTO TABLE @DATA(lt_result).

How to get the list of _Relation according to selection above.

Body:
This is generally not possible like in ABAP SQL queries:

SELECT m~*, kt~*
  FROM mara AS m
  JOIN makt AS kt
...

This contradicts the whole idea of CDS associations, because they were created to join on-demand and to reduce redundant calls to database. Fetching all fields negates the whole idea of "lazy join".

However, there is another syntax in FROM clause which is enabled by path expressions that allows querying underlining associations both fully and by separate elements. Here is how

SELECT *
  FROM ygac_i_request_role( pm_req_id = @lv_test )
       \_Role AS role
  INTO TABLE @DATA(lt_result).

This fetches all the fields of _Role association into internal table.

Note: remember, it is not possible to fetch all the published associations of current view simultaneously, only one path per query.

Possible workaround is to use JOIN

SELECT *
  FROM ygac_i_request_role AS main
  JOIN ygac_i_request_role
       \_Role AS role
    ON main~ProvisionItemId = role~RoleId
  JOIN ygac_i_request_role
       \_Relation AS relation
    ON main~ProvisionItemId = relation~RoleId1
  INTO TABLE @DATA(lt_table).

This creates deep-structured type with dedicated structure for every join association like this:

If you are not comfortable with such structure for you task, lt_table should be declared statically to put up all the fields in a flat way

TYPES BEGIN OF ty_table.
        INCLUDE TYPE ygac_i_request_role.
        INCLUDE TYPE ygac_i_role.
        INCLUDE TYPE ygac_i_role_rs.
TYPES END OF ty_table.


问:
How to define mutual recursion with closures?
I can do something like this:

```<code>fn func() -> (Vec<i32>, Vec<i32>) {
    let mut u = vec![0;5];
    let mut v = vec![0;5];

    fn foo(u: &mut [i32], v: &mut [i32], i: usize, j: usize) {
        for k in i+1..u.len() {
            u[k] += 1;
            bar(u, v, k, j);
        }
    }
    fn bar(u: &mut [i32], v: &mut [i32], i: usize, j: usize) {
        for k in j+1..v.len() {
            v[k] += 1;
            foo(u, v, i, k);
        }
    }
    foo(&mut u, &mut v, 0, 0);
    (u,v)
}

fn main() {
    let (u,v) = func();
    println!("{:?}", u);
    println!("{:?}", v);
}
</code>```

but I would prefer to do something like this:

```<code>fn func() -> (Vec<i32>, Vec<i32>) {
    let mut u = vec![0;5];
    let mut v = vec![0;5];

    let foo = |i, j| {
        for k in i+1..u.len() {
            u[k] += 1;
            bar(k, j);
        }
    };
    let bar = |i, j| {
        for k in j+1..v.len() {
            v[k] += 1;
            foo(i, k);
        }
    };
    foo(0, 0);
    (u,v)
}

fn main() {
    let (u,v) = func();
    println!("{:?}", u);
    println!("{:?}", v);
}
</code>```

The second example doesn't compile with the error: unresolved name bar.
In my task I can do it through one recursion, but it will not look clear.
Does anyone have any other suggestions?

答:
While defining mutually recursive closures works in some cases, as demonstrated in the answer by Alex Knauth, I don't think that's an approach you should usually take. It is kind of opaque, has some limitations pointed out in the other answer, and it also has a performance overhead since it uses trait objects and dynamic dispatch at runtime.

Closures in Rust can be thought of as functions with associated structs storing the data you closed over. So a more general solution is to define your own struct storing the data you want to close over, and define methods on that struct instead of closures. For this case, the code could look like this:

```<code>pub struct FooBar {
    pub u: Vec<i32>,
    pub v: Vec<i32>,
}

impl FooBar {
    fn new(u: Vec<i32>, v: Vec<i32>) -> Self {
        Self { u, v }
    }

    fn foo(&mut self, i: usize, j: usize) {
        for k in i+1..self.u.len() {
            self.u[k] += 1;
            self.bar(k, j);
        }
    }

    fn bar(&mut self, i: usize, j: usize) {
        for k in j+1..self.v.len() {
            self.v[k] += 1;
            self.foo(i, k);
        }
    }
}

fn main() {
    let mut x = FooBar::new(vec![0;5], vec![0;5]);
    x.foo(0, 0);
    println!("{:?}", x.u);
    println!("{:?}", x.v);
}
</code>```

(Playground)

While this can get slightly more verbose than closures, and requires a few more explicit type annotations, it's more flexible and easier to read, so I would generally prefer this approach.

Body:
I can do something like this:

fn func() -> (Vec<i32>, Vec<i32>) {
    let mut u = vec![0;5];
    let mut v = vec![0;5];

    fn foo(u: &mut [i32], v: &mut [i32], i: usize, j: usize) {
        for k in i+1..u.len() {
            u[k] += 1;
            bar(u, v, k, j);
        }
    }
    fn bar(u: &mut [i32], v: &mut [i32], i: usize, j: usize) {
        for k in j+1..v.len() {
            v[k] += 1;
            foo(u, v, i, k);
        }
    }
    foo(&mut u, &mut v, 0, 0);
    (u,v)
}

fn main() {
    let (u,v) = func();
    println!("{:?}", u);
    println!("{:?}", v);
}

but I would prefer to do something like this:

fn func() -> (Vec<i32>, Vec<i32>) {
    let mut u = vec![0;5];
    let mut v = vec![0;5];

    let foo = |i, j| {
        for k in i+1..u.len() {
            u[k] += 1;
            bar(k, j);
        }
    };
    let bar = |i, j| {
        for k in j+1..v.len() {
            v[k] += 1;
            foo(i, k);
        }
    };
    foo(0, 0);
    (u,v)
}

fn main() {
    let (u,v) = func();
    println!("{:?}", u);
    println!("{:?}", v);
}

The second example doesn't compile with the error: unresolved name bar.
In my task I can do it through one recursion, but it will not look clear.
Does anyone have any other suggestions?

Body:
While defining mutually recursive closures works in some cases, as demonstrated in the answer by Alex Knauth, I don't think that's an approach you should usually take. It is kind of opaque, has some limitations pointed out in the other answer, and it also has a performance overhead since it uses trait objects and dynamic dispatch at runtime.

Closures in Rust can be thought of as functions with associated structs storing the data you closed over. So a more general solution is to define your own struct storing the data you want to close over, and define methods on that struct instead of closures. For this case, the code could look like this:

pub struct FooBar {
    pub u: Vec<i32>,
    pub v: Vec<i32>,
}

impl FooBar {
    fn new(u: Vec<i32>, v: Vec<i32>) -> Self {
        Self { u, v }
    }

    fn foo(&mut self, i: usize, j: usize) {
        for k in i+1..self.u.len() {
            self.u[k] += 1;
            self.bar(k, j);
        }
    }

    fn bar(&mut self, i: usize, j: usize) {
        for k in j+1..self.v.len() {
            self.v[k] += 1;
            self.foo(i, k);
        }
    }
}

fn main() {
    let mut x = FooBar::new(vec![0;5], vec![0;5]);
    x.foo(0, 0);
    println!("{:?}", x.u);
    println!("{:?}", x.v);
}

(Playground)

While this can get slightly more verbose than closures, and requires a few more explicit type annotations, it's more flexible and easier to read, so I would generally prefer this approach.


问:
How can I get a list of camera devices from my PC C#
How can I get a list all of camera devices attached to my PC using USB (WebCams) but also the build in camera that the laptops have. </p>

答:
A simple solution without any external library is to use WMI.

Add using System.Management; and then:

```<code>public static List<string> GetAllConnectedCameras()
{
    var cameraNames = new List<string>();
    using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE (PNPClass = 'Image' OR PNPClass = 'Camera')"))
    {
        foreach (var device in searcher.Get())
        {
            cameraNames.Add(device["Caption"].ToString());
        }
    }

    return cameraNames;
}
</code>```

Body:
A simple solution without any external library is to use WMI.

Add using System.Management; and then:

public static List<string> GetAllConnectedCameras()
{
    var cameraNames = new List<string>();
    using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE (PNPClass = 'Image' OR PNPClass = 'Camera')"))
    {
        foreach (var device in searcher.Get())
        {
            cameraNames.Add(device["Caption"].ToString());
        }
    }

    return cameraNames;
}


问:
Old file fragment understanding - For those up for a challenge
I am trying to grab PVS (rendering with line of sight) information from an old game format. It has documentation and I have been able to translate everything into C++ code up to this point. This part however confuses the heck out of me. I spent a few hours today trying to understand where to start but alas, I have nothing. Again, this is only for those that might be up for a challenge or can lend some advice or even pseudocode for how I would accomplish this.

Thank you

Data6 entries (There are Size6 of these):

Data6Size1 : WORD
Tells the number of entries in the Data6Data field.

Data6Data : Either BYTEs or WORDs

This is a complicated field. It contains run-length-encoded data that tells the client which regions are “nearby”. The purpose appears to be so that the client can determine which mobs in the zone have to have their Z coordinates checked, so that they will fall to the ground (or until they land on something). Since it’s expensive to do this, it makes sense to only do it for regions that are visible to the player instead of doing it for all mobs in the entire zone (repeatedly).

I’ve only encountered data where the stream is a list of BYTEs instead of WORDs. The following discussion describes RLE encoding a BYTE stream.

The idea here is to form a sorted list of all region IDs that are within a certain distance, and then write that list as an RLE-encoded stream to save space. The procedure is as follows:

Set an initial region ID value to zero.

If this region ID is not present in the (sorted) list, skip forward to the first one that is in the list. Write something to the stream that tells it how many IDs were skipped.

Form a block of consecutive IDs that are in the list and write something to the stream that tells the client that there are this many IDs that are in the list.

If there are more region IDs in the list, go back to step 2.

When writing to the stream, either one or three bytes are written:

0x00..0x3E skip forward by this many region IDs

0x3F, WORD skip forward by the amount given in the following 16-bit WORD

0x40..0x7F skip forward based on bits 3..5, then include the number of IDs based on bits 0..2

0x80..0xBF include the number of IDs based on bits 3..5, then skip forward based on bits 0..2

0xC0..0xFE subtracting 0xC0, this many region IDs are nearby

0xFF, WORD the number of region IDs given by the following WORD are nearby

It should be noted that the values in the range 0x40..0xBF allow skipping and including of no more than seven IDs at a time. Also, they are not necessary to encode a region list:     they merely allow better compression.

答:
This is my attempt to implement that unpacker. Not tested as there is no example data to test it with... (not even compiled, actually)

```<code>std::vector<int> regions(std::vector<unsigned char>& data6)
{
    int rp = 0, sz = data6.size();
    std::vector<int> result;
    int current_id = 0;
    while (rp < sz)
    {
        int c = data6[rp++];
        if (c <= 0x3E)
        {
            // 0x00..0x3E : skip forward by this many region IDs
            current_id += c;
        }
        else if (c == 0x3F)
        {
            // 0x3F WORD skip forward by the amount given in the following 16-bit WORD
            if (rp + 2 > sz) throw std::runtime_error("Invalid data");
            int count = data[rp] + (data[rp + 1] << 8); // (NOTE: May be H/L ?)
            rp += 2;
            current_id += count;
        }
        else if (c <= 0x7F)
        {
            // 0x40..0x7F skip forward based on bits 3..5,
            // then include the number of IDs based on bits 0..2
            int keep = (c & 7);
            int skip = (c >> 3) & 7;
            current_id += skip;
            for (int i=0; i<keep; i++)
                result.push_back(current_id++);
        }
        else if (c <= 0xBF)
        {
            // 0x80..0xBF include the number of IDs based on bits 3..5,
            // then skip the number of IDs based on bits 0..2
            int skip = (c & 7);
            int keep = (c >> 3) & 7;
            for (int i=0; i<keep; i++)
                result.push_back(current_id++);
            current_id += skip;
        }
        else if (c <= 0xFE)
        {
            // 0xC0..0xFE subtracting 0xC0, this many region IDs are nearby
            int keep = c - 0xC0;
            for (int i=0; i<keep; i++)
                result.push_back(current_id++);
        }
        else
        {
            // 0xFF WORD the number of region IDs given by the following WORD are nearby
            if (rp + 2 > sz) throw std::runtime_error("Invalid data");
            int count = data[rp] + (data[rp + 1] << 8); // (NOTE: May be H/L ?)
            rp += 2;
            for (int i=0; i<count; i++)
                result.push_back(current_id++);
        }
    }
    return result;
}
</code>```

I assumed that WORDs are encoded as low/high, but may be it's the opposite...

Body:
This is my attempt to implement that unpacker. Not tested as there is no example data to test it with... (not even compiled, actually)

std::vector<int> regions(std::vector<unsigned char>& data6)
{
    int rp = 0, sz = data6.size();
    std::vector<int> result;
    int current_id = 0;
    while (rp < sz)
    {
        int c = data6[rp++];
        if (c <= 0x3E)
        {
            // 0x00..0x3E : skip forward by this many region IDs
            current_id += c;
        }
        else if (c == 0x3F)
        {
            // 0x3F WORD skip forward by the amount given in the following 16-bit WORD
            if (rp + 2 > sz) throw std::runtime_error("Invalid data");
            int count = data[rp] + (data[rp + 1] << 8); // (NOTE: May be H/L ?)
            rp += 2;
            current_id += count;
        }
        else if (c <= 0x7F)
        {
            // 0x40..0x7F skip forward based on bits 3..5,
            // then include the number of IDs based on bits 0..2
            int keep = (c & 7);
            int skip = (c >> 3) & 7;
            current_id += skip;
            for (int i=0; i<keep; i++)
                result.push_back(current_id++);
        }
        else if (c <= 0xBF)
        {
            // 0x80..0xBF include the number of IDs based on bits 3..5,
            // then skip the number of IDs based on bits 0..2
            int skip = (c & 7);
            int keep = (c >> 3) & 7;
            for (int i=0; i<keep; i++)
                result.push_back(current_id++);
            current_id += skip;
        }
        else if (c <= 0xFE)
        {
            // 0xC0..0xFE subtracting 0xC0, this many region IDs are nearby
            int keep = c - 0xC0;
            for (int i=0; i<keep; i++)
                result.push_back(current_id++);
        }
        else
        {
            // 0xFF WORD the number of region IDs given by the following WORD are nearby
            if (rp + 2 > sz) throw std::runtime_error("Invalid data");
            int count = data[rp] + (data[rp + 1] << 8); // (NOTE: May be H/L ?)
            rp += 2;
            for (int i=0; i<count; i++)
                result.push_back(current_id++);
        }
    }
    return result;
}

I assumed that WORDs are encoded as low/high, but may be it's the opposite...


问:
Cant access key values from an Object in Reactjs after fetching
I have a user details page in Reactjs where I'm fetching the user details and populating it to the corresponding fields. But I'm not able to access key values from the user object.

My sample code is

```<code>function EditProfile(props) {
    const [user, setUser] = useState()
    useEffect(() => {
        const fetchUserInfo = async () => {
            const profileConfig = {
                method: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + auth.token
                }
            };
            fetch(`http://localhost:4000/api/v1/user/me`, profileConfig)
            .then(response => response.json())
            .then(response => {
                console.log("response: ", response.user);
                if (response.success === true) {
                    setUser(response.user)
                } else {
                    alert(response.message)
                }
            },
            (error) => {
                alert('User fetching faied: ' + error)
            })
        }
        fetchUserInfo()
    }, [])

    return (
       <div>{user.name}</div>
    )
}

</code>```

The response from the server (user object is)

```<code>{
  "status": true,
  "_id": "5ecfdc403165f709b49a4a0e",
  "name": "Anand OL",
  "gender": "male",
  "dob": "2020-12-13T00:00:00.000Z",
  "email": "anand@gmail.com",
  "phone": "1234567890",
  "createdAt": "2020-05-28T15:44:00.700Z",
  "updatedAt": "2020-06-01T08:38:37.902Z",
  "__v": 136,
  "image": "5ecfdc403165f709b49a4a0e_Image.png"
}
</code>```

when I try to access name from the user object like user.name
I'm getting an error user is not defined

答:
You need to provide some initial state to display (or conditionally render) while the fetch is occuring.

```<code>const [user, setUser] = useState(); // <-- user is undefined!!
</code>```

Conditionally render UI

```<code>return <div>{user && user.name}</div>;
</code>```

or

```<code>return user ? <div>{user.name}</div> : null;
</code>```

Note: Use caution with the former as not all falsey values are created equal, i.e. Consider return
{value && value.property}
, if/when value = 0 a falsey value, then a "0" will actually be rendered.

Or you can provide some default state

```<code>const [user, setUser] = useState({ name: '' });
</code>```

Body:
I have a user details page in Reactjs where I'm fetching the user details and populating it to the corresponding fields. But I'm not able to access key values from the user object.

My sample code is

function EditProfile(props) {
    const [user, setUser] = useState()
    useEffect(() => {
        const fetchUserInfo = async () => {
            const profileConfig = {
                method: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + auth.token
                }
            };
            fetch(`http://localhost:4000/api/v1/user/me`, profileConfig)
            .then(response => response.json())
            .then(response => {
                console.log("response: ", response.user);
                if (response.success === true) {
                    setUser(response.user)
                } else {
                    alert(response.message)
                }
            },
            (error) => {
                alert('User fetching faied: ' + error)
            })
        }
        fetchUserInfo()
    }, [])

    return (

{user.name}

    )
}

The response from the server (user object is)

{
  "status": true,
  "_id": "5ecfdc403165f709b49a4a0e",
  "name": "Anand OL",
  "gender": "male",
  "dob": "2020-12-13T00:00:00.000Z",
  "email": "anand@gmail.com",
  "phone": "1234567890",
  "createdAt": "2020-05-28T15:44:00.700Z",
  "updatedAt": "2020-06-01T08:38:37.902Z",
  "__v": 136,
  "image": "5ecfdc403165f709b49a4a0e_Image.png"
}

when I try to access name from the user object like user.name
I'm getting an error user is not defined

Body:
You need to provide some initial state to display (or conditionally render) while the fetch is occuring.

const [user, setUser] = useState(); // <-- user is undefined!!

Conditionally render UI

return <div>{user && user.name}</div>;

or

return user ? <div>{user.name}</div> : null;

Note: Use caution with the former as not all falsey values are created equal, i.e. Consider return <div>{value && value.property}</div>, if/when value = 0 a falsey value, then a "0" will actually be rendered.

Or you can provide some default state

const [user, setUser] = useState({ name: '' });


问:
SqlDependency OnChange Event not firing on IIS Server
The SqlDenpendency.OnChange event is not firing when the tool is published and deployed on IIS Server.

It is working fine on my local machine.

I have referred to this answer https://stackoverflow.com/a/38917421/6763912

答:
To find the root cause, we need to dig the exception. First of all , please check your event viewer.

If there is any exception thrown from .net runtime, you will find it.  If no exception can be found in event viewer. It might be a first chance exception. Then you need to collect dump file with debug diagnostic collection and analyze the dump file with WINDBG.

How to use the Debug Diagnostics Tool

Debug Diagnostic Tool


问:
How to share Protobuf definitions for gRPC?
Since you have to share .proto files to define data and services for gRPC, service provider and clients need to access the same .proto files. Is there any common strategy to distribute these files? I want to avoid that every project has its own .proto file in its Git repository and our team members need to manual edit these files or share them via email.

Is there any common best practice?

答:
Unfortunately, there is no common practice, although the main goal that you should achieve is to store proto files in one version control repository.

During my investigation, I've found some interesting blog posts about that subject:

https://www.bugsnag.com/blog/libraries-for-grpc-services

https://www.crowdstrike.com/blog/improving-performance-and-reliability-of-microservices-communication-with-grpc/

https://medium.com/namely-labs/how-we-build-grpc-services-at-namely-52a3ae9e7c35

They covers much of gRPC workflow considerations. Hope that helps!


问:
How to deal with cyclic closure calls in Rust?
I have the following code in Rust:

fn main() {
    let global = vec!(1, 2, 3);
    fn fn_a() {
        println!("{:?}", global);
        fn_b();
    };

    fn fn_b() {
        println!("{:?}", global);
        fn_a();
    };

    println!("Done.");
}
```

<p>This does not compile because code in <code>fn</code> cannot capture <code>global</code>, and code in <code>fn_b</code> cannot capture <code>fn_a</code>.</p>

<p>I got the following error:</p>

<pre class="lang-rust prettyprint-override"><code>error[E0434]: can't capture dynamic environment in a fn item
   --> src/main.rs:193:24
    |
193 |         println!("{}", global);
    |                        ^^^^^^
    |
    = help: use the `|| { ... }` closure form instead

error[E0434]: can't capture dynamic environment in a fn item
   --> src/main.rs:198:24
    |
198 |         println!("{}", global);
    |                        ^^^^^^
    |
    = help: use the `|| { ... }` closure form instead

error: aborting due to 2 previous errors
</code>```

(rustc --explain E0434)

So I changed to this:

fn main() {
    let global = vec!(1, 2, 3);

    let closure_a = || {
        println!("{:?}", global);
        closure_b();
    };

    let closure_b = || {
        println!("{:?}", global);
        closure_a();
    };

    println!("Done.");
}
```

<p>but still got an error:</p>

<pre class="lang-rust prettyprint-override"><code>error[E0425]: cannot find function `closure_b` in this scope
   --> src/main.rs:195:9
    |
195 |         closure_b();
    |         ^^^^^^^^^ not found in this scope

error: aborting due to previous error
</code>```

I guess this is because that the closure's scope begins from the line it is declared.

Is there a method to write a function/closure to call another function/closure which captures a global variable?

答:
I have modified your code a little and it worked for me. I

```<code>fn fn_b(global:Vec<i32>) {
    println!(" From B: {:?}", global);
    fn_a(global);
}
fn fn_a(global:Vec<i32>) {
    println!("From A {:?}", global);
    fn_b(global);
}
fn main() {
    let global = vec!(1, 2, 3);
    fn_a(global);
    println!("Done.");
}
</code>```

In the methodology, I am defining the fn_a and fn_b above the function main and passing the vector to a function from the main .

There is another method by adding static to keyword to your vector.

```<code>fn main() {
    static mut Global:Vec<i32> = Vec::new();
    unsafe {
        Global = vec!(1,2,3)
    }
    fn fn_a() {
        unsafe{
            println!("From A {:?}", Global);
            fn_b();
        }

    }
    fn fn_b() {
        unsafe{
            println!(" From B: {:?}", Global);
            fn_a();
        }

    }
    println!("Done.");
}
</code>```

Check here the implementation of unsafe  and also do remember calling your functions fn_a and fn_b

Body:
I have the following code in Rust:

fn main() {
    let global = vec!(1, 2, 3);
    fn fn_a() {
        println!("{:?}", global);
        fn_b();
    };

    fn fn_b() {
        println!("{:?}", global);
        fn_a();
    };

    println!("Done.");
}

This does not compile because code in fn cannot capture global, and code in fn_b cannot capture fn_a.

I got the following error:

error[E0434]: can't capture dynamic environment in a fn item
   --> src/main.rs:193:24
    |
193 |         println!("{}", global);
    |                        ^^^^^^
    |
    = help: use the `|| { ... }` closure form instead

error[E0434]: can't capture dynamic environment in a fn item
   --> src/main.rs:198:24
    |
198 |         println!("{}", global);
    |                        ^^^^^^
    |
    = help: use the `|| { ... }` closure form instead

error: aborting due to 2 previous errors

(rustc --explain E0434)

So I changed to this:

fn main() {
    let global = vec!(1, 2, 3);

    let closure_a = || {
        println!("{:?}", global);
        closure_b();
    };

    let closure_b = || {
        println!("{:?}", global);
        closure_a();
    };

    println!("Done.");
}

but still got an error:

error[E0425]: cannot find function `closure_b` in this scope
   --> src/main.rs:195:9
    |
195 |         closure_b();
    |         ^^^^^^^^^ not found in this scope

error: aborting due to previous error

I guess this is because that the closure's scope begins from the line it is declared.

Is there a method to write a function/closure to call another function/closure which captures a global variable?

Body:
I have modified your code a little and it worked for me. I

fn fn_b(global:Vec<i32>) {
    println!(" From B: {:?}", global);
    fn_a(global);
}
fn fn_a(global:Vec<i32>) {
    println!("From A {:?}", global);
    fn_b(global);
}
fn main() {
    let global = vec!(1, 2, 3);
    fn_a(global);
    println!("Done.");
}

In the methodology, I am defining the fn_a and fn_b above the function main and passing the vector to a function from the main .

There is another method by adding static to keyword to your vector.

fn main() {
    static mut Global:Vec<i32> = Vec::new();
    unsafe {
        Global = vec!(1,2,3)
    }
    fn fn_a() {
        unsafe{
            println!("From A {:?}", Global);
            fn_b();
        }

    }
    fn fn_b() {
        unsafe{
            println!(" From B: {:?}", Global);
            fn_a();
        }

    }
    println!("Done.");
}

Check here the implementation of unsafe  and also do remember calling your functions fn_a and fn_b


问:
C# Getting a list of names of the webcams
I have searched for several days to no avail.  I am trying to simply list to a text file the Image Device Names i.e. webcams using c#.  I know I can use System.IO.Ports to get comports, which I am doing, but I cannot find a simple way to list the Image Devices.

I have been able to find the WIA devices with this code but not non-WIA Devices:

```<code>    private static void DoWork()
    {
        var deviceManager1 = new DeviceManager();
        for (int i = 1; (i <= deviceManager1.DeviceInfos.Count); i++)
        {
           // if (deviceManager1.DeviceInfos[i].Type !=
     WiaDeviceType.VideoDeviceType) { continue; }

     Console.WriteLine(deviceManager1.DeviceInfos[i].
     Properties["Name"].get_Value().  ToString());
     }
</code>```

答:
As I answered in this question, you can do it without external libraries by using WMI.

Add using System.Management; and then:

```<code>public static List<string> GetAllConnectedCameras()
{
    var cameraNames = new List<string>();
    using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE (PNPClass = 'Image' OR PNPClass = 'Camera')"))
    {
        foreach (var device in searcher.Get())
        {
            cameraNames.Add(device["Caption"].ToString());
        }
    }

    return cameraNames;
}
</code>```

Body:
I have searched for several days to no avail.  I am trying to simply list to a text file the Image Device Names i.e. webcams using c#.  I know I can use System.IO.Ports to get comports, which I am doing, but I cannot find a simple way to list the Image Devices.

I have been able to find the WIA devices with this code but not non-WIA Devices:

    private static void DoWork()
    {
        var deviceManager1 = new DeviceManager();
        for (int i = 1; (i <= deviceManager1.DeviceInfos.Count); i++)
        {
           // if (deviceManager1.DeviceInfos[i].Type !=
     WiaDeviceType.VideoDeviceType) { continue; }

     Console.WriteLine(deviceManager1.DeviceInfos[i].
     Properties["Name"].get_Value().  ToString());
     }

Body:
As I answered in this question, you can do it without external libraries by using WMI.

Add using System.Management; and then:

public static List<string> GetAllConnectedCameras()
{
    var cameraNames = new List<string>();
    using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE (PNPClass = 'Image' OR PNPClass = 'Camera')"))
    {
        foreach (var device in searcher.Get())
        {
            cameraNames.Add(device["Caption"].ToString());
        }
    }

    return cameraNames;
}


问:
Static resources response with 503 in Nginx over k8s Ingress
I have setup an Ingress for my nginx service,and I can access this service(my-domain.com) with a 200 response.But it always returns 503 when the html page trying to get its static resources(my-domain.com/foo/static/). But everything goes right when I simply pull my image and expose the port on local machine.

pieces of code:

```<code>nginx.conf
location / {
   root html;
   index index.html;
}

ingress.yml
http:
  paths:
    - path : /
    backend:
      serviceName: nginx
      servicePort: 8000

directories and fies inner nginx/html:
- html
  - foo
    - static
      - css
      - js
      - image
    index.html
</code>```

答: In nginx.conf I should Specify server_name the same as k8s service name in the same k8s cluster.

Body:
I have setup an Ingress for my nginx service,and I can access this service(my-domain.com) with a 200 response.But it always returns 503 when the html page trying to get its static resources(my-domain.com/foo/static/). But everything goes right when I simply pull my image and expose the port on local machine.

pieces of code:

nginx.conf
location / {
   root html;
   index index.html;
}

ingress.yml
http:
  paths:
    - path : /
    backend:
      serviceName: nginx
      servicePort: 8000

directories and fies inner nginx/html:
- html
  - foo
    - static
      - css
      - js
      - image
    index.html


问:
Prioritize reading versus writing in the tarantool slave
Can anyone tell me if there is a way to prioritize reading versus writing in the tarantool slave? There is a task which is more important to read than to write, but during writing to the master, the changed records are blocked for some time on the slave. In general, I understand that this is the correct behavior for databases. But maybe there is an opportunity to prioritize reading versus writing on a slave?</p>

答:
all transactions (both read and write) are served in a single thread, there is not prioritization between them.

You can read about it in more details here: https://www.tarantool.io/en/doc/1.10/book/box/atomic/


问:
Materialize CSS reduce gap between Input field and label
I have a form created using materialize CSS. In the form there is an email field, the default gap between the email input field and the label does not suit me, I would like reduce the gap. I have tried the following CSS but it did not work.

CSS Class tried

```<code>.EmailInputFieldSettings{
    margin-top:-1rem;
 }
</code>```

Here is how it appears

Here is the code for the email input field

```<code> <div class="row">
    <form class="col s12">
      <div class="row">
        <div class="input-field col s12">
          <input id="email" type="email" class="validate EmailInputFieldSettings">
          <label for="email">Email</label>
        </div>
      </div>
    </form>
  </div>
</code>```

How can I achieve this?

Thank you.

答:
Change top CSS</p>

```<code>.input-field > label {
    top: 9px;
}
</code>```

Body:
I have a form created using materialize CSS. In the form there is an email field, the default gap between the email input field and the label does not suit me, I would like reduce the gap. I have tried the following CSS but it did not work.

CSS Class tried

.EmailInputFieldSettings{
    margin-top:-1rem;
 }

Here is how it appears

Here is the code for the email input field

    <form class="col s12">

          <input id="email" type="email" class="validate EmailInputFieldSettings">
          Email

    </form>

How can I achieve this?

Thank you.

Body:
Change top CSS

.input-field > label {
    top: 9px;
}


问:
Update Processor returns empty String: Converting string date to long in NIFI
Converting a string date with the format mentioned on the image to a number (long) but the output I get is empty string.

Using a JSON reader and writer;

where in input JSON it is a string and in the output JSON it is of type long.

Tried to keep the output JSON type as a String and tried to evaluate the following expression but that was also empty string

${DATE1.value:toDate('yyyy-MM-dd HH:mm:ss'):toNumber():toString()}

Sample data trying to convert: {"DATE1" : "2018-01-17 00:00:00"}

Tried to follow the solution on this link but still getting empty string.

答:
Check value before converts to Date by using isEmpty() and ifElse().</p>

```<code>${field.value:isEmpty():ifElse('', ${field.value:toDate('yyyy-MM-dd HH:mm:ss'):toNumber()})}
</code>```

Body:
Check value before converts to Date by using isEmpty() and ifElse().

${field.value:isEmpty():ifElse('', ${field.value:toDate('yyyy-MM-dd HH:mm:ss'):toNumber()})}