问:
Calculations involving mixed type elements in columns - np.nan, float, string elements
I have a dataframe where columns include mixed type elements and I need to do some calculations among them. Assume this dataframe:

```<code>A=[20, np.nan, 10, 'give', np.nan, np.nan]
B=[10, np.nan, np.nan, np.nan, 10, 'given']

frame=pd.DataFrame(zip(A,B))
frame.columns=['A', 'B']
</code>```

I want to populate the difference of B from A. If I do frame['diff']=frame['A']-frame['B'] it does not give the result I need. Instead, the result I would want is in the 'desired diff' column.

Basically, if A or B has a number, then B or A should be 0. If a string is in A, while B is NaN, then it should write "positive" and, in the vice versa case, it should write "negative". See below:

```<code>frame
      A      B  diff  desired diff
0    20     10    10            10
1   NaN    NaN   NaN           NaN
2    10    NaN   NaN            10
3  give    NaN   NaN      positive
4   NaN     10   NaN           -10
5   NaN  given   NaN      negative
</code>```

Just for the record, I have tried to implement np.where and np.select and some conditions such as np.logical_and(frame['A'].apply(lambda x: isinstance(x, float)), frame['B'].isna()) to achieve the desired output, but without success.

Thanks in advance for your suggestions!

答:
If you want to use a long apply, which I would not recommend:</p>

```<code>frame['diff'] = (frame.fillna(0)
                 .apply(lambda x: x.A-x.B if (isinstance(x.A, (int, float)) & isinstance(x.B, (int, float)))
                        else ('positive' if (isinstance(x.A, str) & (x.B == 0)) else 'negative'),
                        axis=1)
                 .replace(0, np.nan))

      A      B      diff
0    20     10        10
1   NaN    NaN       NaN
2    10    NaN        10
3  give    NaN  positive
4   NaN     10       -10
5   NaN  given  negative
</code>```

Body:
I have a dataframe where columns include mixed type elements and I need to do some calculations among them. Assume this dataframe:

A=[20, np.nan, 10, 'give', np.nan, np.nan]
B=[10, np.nan, np.nan, np.nan, 10, 'given']

frame=pd.DataFrame(zip(A,B))
frame.columns=['A', 'B']

I want to populate the difference of B from A. If I do frame['diff']=frame['A']-frame['B'] it does not give the result I need. Instead, the result I would want is in the 'desired diff' column.

Basically, if A or B has a number, then B or A should be 0. If a string is in A, while B is NaN, then it should write "positive" and, in the vice versa case, it should write "negative". See below:

frame
      A      B  diff  desired diff
0    20     10    10            10
1   NaN    NaN   NaN           NaN
2    10    NaN   NaN            10
3  give    NaN   NaN      positive
4   NaN     10   NaN           -10
5   NaN  given   NaN      negative

Just for the record, I have tried to implement np.where and np.select and some conditions such as np.logical_and(frame['A'].apply(lambda x: isinstance(x, float)), frame['B'].isna()) to achieve the desired output, but without success.

Thanks in advance for your suggestions!

Body:
If you want to use a long apply, which I would not recommend:

frame['diff'] = (frame.fillna(0)
                 .apply(lambda x: x.A-x.B if (isinstance(x.A, (int, float)) & isinstance(x.B, (int, float)))
                        else ('positive' if (isinstance(x.A, str) & (x.B == 0)) else 'negative'),
                        axis=1)
                 .replace(0, np.nan))

      A      B      diff
0    20     10        10
1   NaN    NaN       NaN
2    10    NaN        10
3  give    NaN  positive
4   NaN     10       -10
5   NaN  given  negative


来源: stackexchange

问:
perl decode string in cyrillic
I've got a problem with the following string:

```<code>$str="this is \321\213\321\213\321\213\321\213\321\213 \321\201\320\277\320\260\321\200\321\202\320\260\321\200";
</code>```

This string is located in an ascii text file and I want to store in a Mysql db (utf8). \321\231 ... are cyrillic symbols.

What can I do to make \321\213 look like cyrillic characters in Mysql db

This should be described in RFC2047, end look like it was utf7 to utf8 conversion.. dont know excatly.
its "unicode escape"

working variant:

```<code>use Encode::Escape;
$var1='\321\213';
         print decode 'unicode-escape', $var1;
#correct mysql view in phpmyadmin
$dbh = DBI->connect('DBI:mysql:database=test', 'testuser', 'testpass', { mysql_enable_utf8 => 1});
</code>```

答:
Problem is: perl does not know that the string is UTF-8, so you must turn flag explicitly on.

Encode::_utf8_on($str);

ContentLicense: CC BY-SA 3.0

Title: perl decode string in cyrillic

Body:
I've got a problem with the following string:

$str="this is \321\213\321\213\321\213\321\213\321\213 \321\201\320\277\320\260\321\200\321\202\320\260\321\200";

This string is located in an ascii text file and I want to store in a Mysql db (utf8). \321\231 ... are cyrillic symbols.

What can I do to make \321\213 look like cyrillic characters in Mysql db

This should be described in RFC2047, end look like it was utf7 to utf8 conversion.. dont know excatly.
its "unicode escape"

working variant:

use Encode::Escape;
$var1='\321\213';
         print decode 'unicode-escape', $var1;
#correct mysql view in phpmyadmin
$dbh = DBI->connect('DBI:mysql:database=test', 'testuser', 'testpass', { mysql_enable_utf8 => 1});


问:
AOSP x86_64 Emulator not visible in Android Studio
I am using AOSP emulator for testing my code.
I downloaded the android10_release source code of AOSP in my pc.
Then used the following commands

```<code>source build/envsetup.sh

set_stuff_for_environment

lunch aosp_x86_64-eng

make -j6

emulator
</code>```

now after running these commands I am successfully able to run emulator in my pc
OS of my pc is Ubuntu 18.04
I also installed many libraries for working with AOSP like jdk-8, python, curl, repo, git, and other stuff as per described in AOSP website

I am abe to see my emulator running in terminal by executing following commands

```<code>$ adb devices
</code>```

List of devices attached
emulator-5554   device

I am also able to install my apk in this emulator by executing following commands

```<code>$ adb install myapp.apk
</code>```

and it gets installed and I can see it in emulator

Now coming to my question

Why this emulator not showing in Android studio in devices
Even when I troubleshoot the adb connections in android studio it shows my emulator running but not showing in available devices.

答:
Finally after doing a lot of research I got to know that if I want to use Emulator of AOSP in Android Studio so I need to follow this guide
Sharing AVD system images for others to use with Android Studio

Follow these instructions to share your AVD system images with others. They can use your AVD system images with Android Studio to develop and test apps.

```<code>Make additional sdk and sdk_repo packages:

$ make -j32 sdk sdk_repo

This creates two files under aosp-master/out/host/linux-x86/sdk/sdk_phone_x86:
    sdk-repo-linux-system-images-eng.[username].zip
    repo-sys-img.xml

Host the file sdk-repo-linux-system-images-eng.[username].zip somewhere accessible to your users, and get its URL to use as the AVD System Image URL.

Edit repo-sys-img.xml accordingly:
    Update <sdk:url> to your AVD System Image URL.
    See sdk-sys-img-03.xsd to learn about other updates to the file.

Host repo-sys-img.xml somewhere accessible to your users, and get its URL to use as the Custom Update Site URL.
</code>```

To use a custom AVD image, do the following in the SDK Manager:

```<code>Add the Custom Update Site URL as an SDK Update Site.

This adds your custom AVD system image to the System Images page.

Create an AVD by downloading and selecting the custom AVD system image.
</code>```

This link is helpful for reference

Create avd from AOSP to use in Android Studio and also share with others

ContentLicense: CC BY-SA 4.0

Body:
I am using AOSP emulator for testing my code.
I downloaded the android10_release source code of AOSP in my pc.
Then used the following commands

source build/envsetup.sh

set_stuff_for_environment

lunch aosp_x86_64-eng

make -j6

emulator

now after running these commands I am successfully able to run emulator in my pc
OS of my pc is Ubuntu 18.04
I also installed many libraries for working with AOSP like jdk-8, python, curl, repo, git, and other stuff as per described in AOSP website

I am abe to see my emulator running in terminal by executing following commands

$ adb devices

List of devices attached
emulator-5554   device

I am also able to install my apk in this emulator by executing following commands

$ adb install myapp.apk

and it gets installed and I can see it in emulator

Now coming to my question

Why this emulator not showing in Android studio in devices
Even when I troubleshoot the adb connections in android studio it shows my emulator running but not showing in available devices.

Body:
Finally after doing a lot of research I got to know that if I want to use Emulator of AOSP in Android Studio so I need to follow this guide
Sharing AVD system images for others to use with Android Studio

Follow these instructions to share your AVD system images with others. They can use your AVD system images with Android Studio to develop and test apps.

Make additional sdk and sdk_repo packages:

$ make -j32 sdk sdk_repo

This creates two files under aosp-master/out/host/linux-x86/sdk/sdk_phone_x86:
    sdk-repo-linux-system-images-eng.[username].zip
    repo-sys-img.xml

Host the file sdk-repo-linux-system-images-eng.[username].zip somewhere accessible to your users, and get its URL to use as the AVD System Image URL.

Edit repo-sys-img.xml accordingly:
    Update <sdk:url> to your AVD System Image URL.
    See sdk-sys-img-03.xsd to learn about other updates to the file.

Host repo-sys-img.xml somewhere accessible to your users, and get its URL to use as the Custom Update Site URL.

To use a custom AVD image, do the following in the SDK Manager:

Add the Custom Update Site URL as an SDK Update Site.

This adds your custom AVD system image to the System Images page.

Create an AVD by downloading and selecting the custom AVD system image.

This link is helpful for reference

Create avd from AOSP to use in Android Studio and also share with others


问:
I need to add dependency in my package.json and load module , after taking user input while running npm install
I need to add a dependency in my package.json  and load module, by taking user input in command prompt while running npm install.

Is it possible to do so.

答:
As you haven't provided much information about what exactly you try to accomplish, it's difficult to advise you or give a concrete example. Anyhow, in package.json, you can override the default behavior of npm scripts with the scripts field:

```<code>"scripts": {
    "install": "./scripts/install.sh",
}
</code>```

As someone else has noted before, you cannot call npm install in your custom script, though, as this would lead to infinite recursion. Thus, rather provide a preinstall script, which npm runs before install.

For use cases other than adding dependencies based on user input, I recommend to check how to set the environment variables and configurations, which the user then could override with npm config set project-name:config-name config-value.

Body:
As you haven't provided much information about what exactly you try to accomplish, it's difficult to advise you or give a concrete example. Anyhow, in package.json, you can override the default behavior of npm scripts with the scripts field:

"scripts": {
    "install": "./scripts/install.sh",
}

As someone else has noted before, you cannot call npm install in your custom script, though, as this would lead to infinite recursion. Thus, rather provide a preinstall script, which npm runs before install.

For use cases other than adding dependencies based on user input, I recommend to check how to set the environment variables and configurations, which the user then could override with npm config set project-name:config-name config-value.


问:
Multiple jenkinsfile in one repository
We have a project in a Github repository with multiple Jenkinsfiles:

```<code>my-project
  app
    Jenkinsfile
  lib1
    Jenkinsfile
  lib2
    Jenkinsfile
</code>```

We have created 3 Jenkins pipelines each referring to a Jenkinsfile.

Question: How to avoid triggering "app" and "lib1" pipelines when there is a new commit in "lib2"? We don't want to run N jobs every time a commit happens.

I've seen that the issue is addressed in https://issues.jenkins-ci.org/browse/JENKINS-43749, but I haven't found a solution there.

答:
I achieved to have multiple pipelines (Jenkinsfile) in a single repository. It's not hacky but it was not exactly trivial, requires recent versions of Jenkins with updated Lockable Resources plugin and may require additional steps in the build procedure.

Create a "Source Code Management" only project. In Jenkins
terminology it can be a Freestyle project that will only care about
keeping the source code updated, with a SCM section and a triggered
configured (example name "MyProjectSCM"). In my case I have a git
repository with a polling schedule. Ensure the "Execute concurrent builds if necessary" flag is not checked;

In the project repository commit one or more Jenkins pipeline, for example "JenkinsfileBuild", "JenkinsfileRelease". Ensure the pipelines:

has the the skipDefaultCheckout in the options section;

has a trigger on the SCM project configured ("MyProjectSCM");

locks the SCM project during build.

```<code> pipeline {
     agent any

     options {
         disableConcurrentBuilds()
         skipDefaultCheckout()
     }

     triggers {
         upstream(upstreamProjects: 'MyProjectSCM')
     }

     stages {
         stage('Build') {
             lock('MyProjectSCM') {
                 steps {
                     echo 'Build within MyProjectSCM lock...'
                 }
             }
         }
     }
 }
</code>```

Create Pipeline projects, one per each Jenkinsfile you committed in the repository. The pipeline should have a configured "Pipeline script from SCM" (in this example the pipeline can be named "MyProject_Build", with a configured "JenkinsfileBuild"), with the "Lightweight checkout" flag checked (it's actually the default):

The skipDefaultCheckout directive in "MyProject_Build" pipeline will prevent the checkout of the repository in that workspace, "Lightweight checkout" flag itself strangely it's not enough to prevent the checkout. Because the "MyProject_Build" workspace it's actually empty you have to refer to the SCM only project directory in your build scripts, by means of environment variables or relative paths. The lock directive is useful so a new commit can't happen while actually building the project.

Title: Multiple jenkinsfile in one repository

Body:
We have a project in a Github repository with multiple Jenkinsfiles:

my-project
  app
    Jenkinsfile
  lib1
    Jenkinsfile
  lib2
    Jenkinsfile

We have created 3 Jenkins pipelines each referring to a Jenkinsfile.

Question: How to avoid triggering "app" and "lib1" pipelines when there is a new commit in "lib2"? We don't want to run N jobs every time a commit happens.

I've seen that the issue is addressed in https://issues.jenkins-ci.org/browse/JENKINS-43749, but I haven't found a solution there.

Body:
I achieved to have multiple pipelines (Jenkinsfile) in a single repository. It's not hacky but it was not exactly trivial, requires recent versions of Jenkins with updated Lockable Resources plugin and may require additional steps in the build procedure.

Create a "Source Code Management" only project. In Jenkins
terminology it can be a Freestyle project that will only care about
keeping the source code updated, with a SCM section and a triggered
configured (example name "MyProjectSCM"). In my case I have a git
repository with a polling schedule. Ensure the "Execute concurrent builds if necessary" flag is not checked;

In the project repository commit one or more Jenkins pipeline, for example "JenkinsfileBuild", "JenkinsfileRelease". Ensure the pipelines:

has the the skipDefaultCheckout in the options section;

has a trigger on the SCM project configured ("MyProjectSCM");

locks the SCM project during build.

 pipeline {
     agent any

     options {
         disableConcurrentBuilds()
         skipDefaultCheckout()
     }

     triggers {
         upstream(upstreamProjects: 'MyProjectSCM')
     }

     stages {
         stage('Build') {
             lock('MyProjectSCM') {
                 steps {
                     echo 'Build within MyProjectSCM lock...'
                 }
             }
         }
     }
 }

Create Pipeline projects, one per each Jenkinsfile you committed in the repository. The pipeline should have a configured "Pipeline script from SCM" (in this example the pipeline can be named "MyProject_Build", with a configured "JenkinsfileBuild"), with the "Lightweight checkout" flag checked (it's actually the default):

The skipDefaultCheckout directive in "MyProject_Build" pipeline will prevent the checkout of the repository in that workspace, "Lightweight checkout" flag itself strangely it's not enough to prevent the checkout. Because the "MyProject_Build" workspace it's actually empty you have to refer to the SCM only project directory in your build scripts, by means of environment variables or relative paths. The lock directive is useful so a new commit can't happen while actually building the project.


问:
Is there a way to DeserializeObject without empty constructor?
I am currently in the progress of enabling non-nullable reference types for my .net core api.

The problem is that the integrationtest fails when trying to deserializeObject because it has no empty constructor. I can't have an empty constructor because that will make property: possible null.

The problem:

JsonConvert.DeserializeObject<ViewModel>(result); calls the constructor which has a constructor with an object argument ViewModel(Model model). In the test this is null.

I have made a simple sample:

The api:

```<code>public class Dog
    {
        public string Name { get; set; } = null!;
    }

    public class DogViewModel
    {

        public DogViewModel(Dog dog)
        {
            Name = dog.Name;
        }

        public string Name { get; set; }
    }

    [HttpGet]
    [Route("dog")]
    public DogViewModel GetDog()
    {
        var dog = new Dog
        {
            Name = "Fido"
        };
        return new DogViewModel(dog);
    }
</code>```

This works when I use a client to call the api, but it fails from the tests:

Test

```<code>    [Fact]
    public async Task GetDog()
    {

        var response = await Client.GetAsync("dog");

        var result = response.Content.ReadAsStringAsync().Result;
        Assert.True(response.IsSuccessStatusCode, result);
        var responeseAsObject = JsonConvert.DeserializeObject<DogViewModel>(result); <----- this is where it breaks
        Assert.IsType<string>(responeseAsObject.Name);
        Assert.NotNull(responeseAsObject);
    }
</code>```

JsonConvert.DeserializeObject calls the constructor of DogViewModel;  DogViewModel(Dog dog), but dog is null.

答:
Populate the class with default values. With null able reference types, the default value would be null, so in your case just assign the default value that you expect.

```<code>public class ClassName
{
    public ClassName()
    {
        Name = string.Empty; //Default value
    }

    public ClassName(Dog dog)
    {
        Name = dog.Name;
    }

}
</code>```

Or

```<code>public class ClassName
{
    public string Name { get; set; } = string.Empty;

    public ClassName() {}

    public ClassName(Dog dog)
    {
        Name = dog.Name;
    }

}
</code>```

The serializer will construct a new object. The object contains a string member, and you have disabled null-able reference types. Thus you need to specify what the value will be when the object is created.

If you don't want to use the default constructor (An empty constructor), you can tell the serialiser the constructor you would like to use:
https://www.newtonsoft.com/json/help/html/JsonConstructorAttribute.htm

Body:
I am currently in the progress of enabling non-nullable reference types for my .net core api.

The problem is that the integrationtest fails when trying to deserializeObject because it has no empty constructor. I can't have an empty constructor because that will make property: possible null.

The problem:

JsonConvert.DeserializeObject<ViewModel>(result); calls the constructor which has a constructor with an object argument ViewModel(Model model). In the test this is null.

I have made a simple sample:

The api:

public class Dog
    {
        public string Name { get; set; } = null!;
    }

    public class DogViewModel
    {

        public DogViewModel(Dog dog)
        {
            Name = dog.Name;
        }

        public string Name { get; set; }
    }

    [HttpGet]
    [Route("dog")]
    public DogViewModel GetDog()
    {
        var dog = new Dog
        {
            Name = "Fido"
        };
        return new DogViewModel(dog);
    }

This works when I use a client to call the api, but it fails from the tests:

Test

    [Fact]
    public async Task GetDog()
    {

        var response = await Client.GetAsync("dog");

        var result = response.Content.ReadAsStringAsync().Result;
        Assert.True(response.IsSuccessStatusCode, result);
        var responeseAsObject = JsonConvert.DeserializeObject<DogViewModel>(result); <----- this is where it breaks
        Assert.IsType<string>(responeseAsObject.Name);
        Assert.NotNull(responeseAsObject);
    }

JsonConvert.DeserializeObject calls the constructor of DogViewModel;  DogViewModel(Dog dog), but dog is null.

Body:
Populate the class with default values. With null able reference types, the default value would be null, so in your case just assign the default value that you expect.

public class ClassName
{
    public ClassName()
    {
        Name = string.Empty; //Default value
    }

    public ClassName(Dog dog)
    {
        Name = dog.Name;
    }

}

Or

public class ClassName
{
    public string Name { get; set; } = string.Empty;

    public ClassName() {}

    public ClassName(Dog dog)
    {
        Name = dog.Name;
    }

}

The serializer will construct a new object. The object contains a string member, and you have disabled null-able reference types. Thus you need to specify what the value will be when the object is created.

If you don't want to use the default constructor (An empty constructor), you can tell the serialiser the constructor you would like to use:
https://www.newtonsoft.com/json/help/html/JsonConstructorAttribute.htm


问:
Logic error with an encode/decode program (C)
I am a beginner in a C programming class, and our assignment for the third chapter of our textbook was to create an encode/decode program that takes in four digits from user input and rearranges them depending on whether or not the user wants them to be either encoded or decoded. I am also having trouble with getting the program to do both decoding and encoding in one file. However, when I fire up the program, whenever I select encode and type in my four digits, the program not only gives me a massive number that should only be four digits as the encoded result. It also gives me the "press any key to continue" prompt, signifying the end of the program, instead of starting over completely and going back to where it asks the user to either decode or encode.

The output is also attached.

I've tried looking around and changing some of the variables from int to double, as well as checking my math... I'm not 100% sure why the encryption and decryption aren't limited to anything besides four digits.

As for getting the program to start over, I've tried using a do-while loop, but it still didn't seem to work, so I deleted it.. I also tried using another if statement and then using break, but it was marked as an error.

The assignment says that, "each digit should be encrypted by adding 7 and taking the remainder after division by 10; after encrypting each digit, swap the first and third digits, and then swap the second and fourth digits. Decryption should reverse the process. Program must do encode and decode in one file.

Here is the example that my instructor posted for this, this is what the output should look like.

```<code>Enter a four digit number: 1234
Encoded Digits: 0189
Continue (1) Exit (0): 1
Encode (1) Decode (2): 2
Enter a four digit number: 0189
Decoded Digits: 1234
Continue (1) Exit (0): 0
</code>```

Here is my code:

```<code>///Compiler used: Microsoft Visual Studio
///Language: C
#include <string>
#pragma warning(disable: 4996)
#include <math.h>
#include<stdio.h>
#include<stdlib.h>

int main()
{

    int Encodechoice = 1;
    int inputdigit1 = 0;
    int Decodechoice = 2;
    int UserChoice = 0;
    int ContinueChoice = 0;
    int UserDigit1 = 0;
    int UserDigit2 = 0;
    int UserDigit3 = 0;
    int UserDigit4 = 0;

    {
        printf("(1) Encode, (2) Decode\n");
        printf("Make your selection.\n");//Asks user to make selection
        scanf_s("%d", &UserChoice);

        if (UserChoice == 1)//begin encryption

        {
            UserDigit1 = 0;
            UserDigit2 = 0;
            UserDigit3 = 0;
            UserDigit4 = 0;
            printf("Encode: Enter FOUR integers.\n");
            scanf_s("%d", &UserDigit1, &UserDigit2, &UserDigit3, &UserDigit4);
            int EncodedIntegers1 = (UserDigit1 + 7) % 10;
            int EncodedIntegers2 = (UserDigit2 + 7) % 10;
            int EncodedIntegers3 = (UserDigit3 + 7) % 10;
            int EncodedIntegers4 = (UserDigit4 + 7) % 10;
            printf("Encoded result:\n");
            printf("%d", "%d", "%d", "%d\n", EncodedIntegers3, &EncodedIntegers4, &EncodedIntegers1, &EncodedIntegers2); /// swap order of integers
        }///end if

        if (UserChoice == 2)///begin decryption
        {
            UserDigit1 = 0;
            UserDigit2 = 0;
            UserDigit3 = 0;
            UserDigit4 = 0;
            printf("Decode: Enter FOUR integers.\n");
            scanf_s("%d", &UserDigit1, &UserDigit2, &UserDigit3, &UserDigit4);
            int DecodedIntegers1 = (UserDigit1 - 7) * 10;
            int DecodedIntegers2 = (UserDigit2 - 7) * 10;
            int DecodedIntegers3 = (UserDigit3 - 7) * 10;
            int DecodedIntegers4 = (UserDigit4 - 7) * 10;
            printf("Decoded result:\n");
            printf("%d", "%d", "%d", "%d\n", DecodedIntegers1, &DecodedIntegers2, &DecodedIntegers3, &DecodedIntegers4); /// keep order the same to decrypt
        }///end if
        system("pause");
        return 0;
    }
}
</code>```

Output:

```<code>Make your selection.
1
Encode: Enter FOUR integers.
1234
Encoded result:
11893608 Continue? (1) Yes, (0) No
Make your selection.
1
Press any key to continue . . .```

```

答:
The easiest way is probably work directly on a string consisting of the four digits:

```<code>char d[5], e[5] = { 0 };
scanf("%4s", d)
</code>```

This is for encoding:

```<code>for (int i = 0; i < 4; i++) e[(i+2)%4]=(d[i]-41)%10+'0';
</code>```

For decoding, you have to change the magic 41 to 45. The result is in e.

Body:
I am a beginner in a C programming class, and our assignment for the third chapter of our textbook was to create an encode/decode program that takes in four digits from user input and rearranges them depending on whether or not the user wants them to be either encoded or decoded. I am also having trouble with getting the program to do both decoding and encoding in one file. However, when I fire up the program, whenever I select encode and type in my four digits, the program not only gives me a massive number that should only be four digits as the encoded result. It also gives me the "press any key to continue" prompt, signifying the end of the program, instead of starting over completely and going back to where it asks the user to either decode or encode.

The output is also attached.

I've tried looking around and changing some of the variables from int to double, as well as checking my math... I'm not 100% sure why the encryption and decryption aren't limited to anything besides four digits.

As for getting the program to start over, I've tried using a do-while loop, but it still didn't seem to work, so I deleted it.. I also tried using another if statement and then using break, but it was marked as an error.

The assignment says that, "each digit should be encrypted by adding 7 and taking the remainder after division by 10; after encrypting each digit, swap the first and third digits, and then swap the second and fourth digits. Decryption should reverse the process. Program must do encode and decode in one file.

Here is the example that my instructor posted for this, this is what the output should look like.

Enter a four digit number: 1234
Encoded Digits: 0189
Continue (1) Exit (0): 1
Encode (1) Decode (2): 2
Enter a four digit number: 0189
Decoded Digits: 1234
Continue (1) Exit (0): 0

Here is my code:

///Compiler used: Microsoft Visual Studio
///Language: C
#include <string>
#pragma warning(disable: 4996)
#include <math.h>
#include<stdio.h>
#include<stdlib.h>

int main()
{

    int Encodechoice = 1;
    int inputdigit1 = 0;
    int Decodechoice = 2;
    int UserChoice = 0;
    int ContinueChoice = 0;
    int UserDigit1 = 0;
    int UserDigit2 = 0;
    int UserDigit3 = 0;
    int UserDigit4 = 0;

    {
        printf("(1) Encode, (2) Decode\n");
        printf("Make your selection.\n");//Asks user to make selection
        scanf_s("%d", &UserChoice);

        if (UserChoice == 1)//begin encryption

        {
            UserDigit1 = 0;
            UserDigit2 = 0;
            UserDigit3 = 0;
            UserDigit4 = 0;
            printf("Encode: Enter FOUR integers.\n");
            scanf_s("%d", &UserDigit1, &UserDigit2, &UserDigit3, &UserDigit4);
            int EncodedIntegers1 = (UserDigit1 + 7) % 10;
            int EncodedIntegers2 = (UserDigit2 + 7) % 10;
            int EncodedIntegers3 = (UserDigit3 + 7) % 10;
            int EncodedIntegers4 = (UserDigit4 + 7) % 10;
            printf("Encoded result:\n");
            printf("%d", "%d", "%d", "%d\n", EncodedIntegers3, &EncodedIntegers4, &EncodedIntegers1, &EncodedIntegers2); /// swap order of integers
        }///end if

        if (UserChoice == 2)///begin decryption
        {
            UserDigit1 = 0;
            UserDigit2 = 0;
            UserDigit3 = 0;
            UserDigit4 = 0;
            printf("Decode: Enter FOUR integers.\n");
            scanf_s("%d", &UserDigit1, &UserDigit2, &UserDigit3, &UserDigit4);
            int DecodedIntegers1 = (UserDigit1 - 7) * 10;
            int DecodedIntegers2 = (UserDigit2 - 7) * 10;
            int DecodedIntegers3 = (UserDigit3 - 7) * 10;
            int DecodedIntegers4 = (UserDigit4 - 7) * 10;
            printf("Decoded result:\n");
            printf("%d", "%d", "%d", "%d\n", DecodedIntegers1, &DecodedIntegers2, &DecodedIntegers3, &DecodedIntegers4); /// keep order the same to decrypt
        }///end if
        system("pause");
        return 0;
    }
}

Output:

Make your selection.
1
Encode: Enter FOUR integers.
1234
Encoded result:
11893608 Continue? (1) Yes, (0) No
Make your selection.
1
Press any key to continue . . .```

Body:
The easiest way is probably work directly on a string consisting of the four digits:

char d[5], e[5] = { 0 };
scanf("%4s", d)

This is for encoding:

for (int i = 0; i < 4; i++) e[(i+2)%4]=(d[i]-41)%10+'0';

For decoding, you have to change the magic 41 to 45. The result is in e.


问:
How to skip "You cannot add another to your cart" Error in woocommerce and directly jump to Checkout?
What Woocommerce Does is...

When products are Sold Individually, and when the product already exists in the Cart and customer clicks on Add to Cart, Woocommerce shows Error Message "You cannot add another to your cart.....View Cart"

Instead of the above flow I want..

When customer clicks on Add to Cart and if the product already exists in the Cart then woocommerce should redirect to Checkout page straightway.

I think this can be achieved by editing few lines of code in class-wc-cart.php of Woocommerce Plugin.

The is given below:

```<code>// Force quantity to 1 if sold individually and check for existing item in cart
                if ( $product_data->is_sold_individually() ) {
                    $quantity         = apply_filters( 'woocommerce_add_to_cart_sold_individually_quantity', 1, $quantity, $product_id, $variation_id, $cart_item_data );
                    $in_cart_quantity = $cart_item_key ? $this->cart_contents[ $cart_item_key ]['quantity'] : 0;

                    if ( $in_cart_quantity > 0 ) {
                        throw new Exception( sprintf( '<a href="%s" class="button wc-forward">%s</a> %s', wc_get_cart_url(), __( 'View Cart', 'woocommerce' ), sprintf( __( 'You cannot add another "%s" to your cart.', 'woocommerce' ), $product_data->get_title() ) ) );
                    }
                }
</code>```

答:
Try this it will work:

add_filter( 'woocommerce_add_to_cart_sold_individually_quantity', 'vipcomment_change_quantity_to_zero', 10, 5 );
function vipcomment_change_quantity_to_zero( $one, $quantity, $product_id, $variation_id, $cart_item_data ) {
    $your_product_id = 96;
    if ( $product_id == $your_product_id ) {
        $product_cart_id = WC()->cart->generate_cart_id( $product_id );
        $in_cart         = WC()->cart->find_product_in_cart( $product_cart_id );
        if ( $in_cart ) {
            return 0;
        } else {
            return $quantity;
        }
    } else {
        return $quantity;
    }
}

add_filter( 'woocommerce_add_to_cart_sold_individually_found_in_cart', 'vipcomment_is_product_exist_in_cart', 10, 5 );
function vipcomment_is_product_exist_in_cart( $exist, $product_id, $variation_id, $cart_item_data, $cart_id ) {
    $your_product_id = 96;
    if ( $product_id == $your_product_id ) {
        return false;
    } else {
        return $exist;
    }
}
```

Body:
What Woocommerce Does is...

When products are Sold Individually, and when the product already exists in the Cart and customer clicks on Add to Cart, Woocommerce shows Error Message "You cannot add another to your cart.....View Cart"

Instead of the above flow I want..

When customer clicks on Add to Cart and if the product already exists in the Cart then woocommerce should redirect to Checkout page straightway.

I think this can be achieved by editing few lines of code in class-wc-cart.php of Woocommerce Plugin.

The is given below:

// Force quantity to 1 if sold individually and check for existing item in cart
                if ( $product_data->is_sold_individually() ) {
                    $quantity         = apply_filters( 'woocommerce_add_to_cart_sold_individually_quantity', 1, $quantity, $product_id, $variation_id, $cart_item_data );
                    $in_cart_quantity = $cart_item_key ? $this->cart_contents[ $cart_item_key ]['quantity'] : 0;

                    if ( $in_cart_quantity > 0 ) {
                        throw new Exception( sprintf( '%s %s', wc_get_cart_url(), __( 'View Cart', 'woocommerce' ), sprintf( __( 'You cannot add another "%s" to your cart.', 'woocommerce' ), $product_data->get_title() ) ) );
                    }
                }


问:
Dynamically populating the manual intervention message
In my release pipeline I want to dynamically populate the message box that shows up for a manual intervention. The use case is like so:

I have a manual test plan that I would like the stage approver to refer to before giving his/her approval. I want to populate the manual intervention message box with a link to the specific Manual Test Plan's test run chart in AzDo portal.

Since this is dynamic information, how can I apply the message to the manual intervention message box dynamically at release creation workflow execution time.

答:
This cannot be achieved. Azure release pipeline does not support this feature to populate message box currently.

You can submit a feature request(Click Suggest a Feature and Choose Azure Devops) to Microsoft Development team. Hope they will consider implement this feature in the future.


问:
React-router-dom: Very simple nested routing does not work
I have searched through different tutorials and multiple stackOverflow questions. And none of which, helped me solve a very basic problem:

Implement nested routes with react-router-dom

Here's my code so far:

App.js

```<code>  <Route exact path="/home" name="Home" component={DefaultLayout} />
</code>```

DefaultLayout.js

```<code> <Route path="/home/users" component={Users} />
</code>```

When I go to /home/users, I get a blank screen because react-router-dom is looking-up the definition of that route inside App.js instead of searching it inside DefaultLayout.js..

So I have two questions:

QUESION 1: What am I doing wrong exactly?

QUESTION 2: How does react-router-dom know that it should look for the nested route inside DefaultLayout.js instead of inside App.js?

It has been two days and I still cannot solve this simple problem.

Any help is very much appreciated.

EDIT 1: I have started a new project just for the sake of implementing a very simple nested routing:

App.js

```<code>import React from "react";
import { BrowserRouter, Switch, Route } from "react-router-dom";

import ParentComponent from "./nestedComponents/ParentComponent";

function App() {
  return (
    <div>
      <BrowserRouter>
        <Switch>
          <Route exact path="/home" name="Home" component={ParentComponent} />
        </Switch>
      </BrowserRouter>
    </div>
  );
}

export default App;
</code>```

ParentComponent.js

```<code>import React from "react";
import nestedComponentOne from "./nestedComponentOne";
import nestedComponentTwo from "./nestedComponentTwo";
import { Switch, Route } from "react-router-dom";

export default function ParentComponent() {
  return (
    <div>
      PARENT COMPONENT
      <Switch>
        <Route path="home/nestedComponentOne" component={nestedComponentOne} />
        <Route path="home/nestedComponentTwo" component={nestedComponentTwo} />
      </Switch>
    </div>
  );
}
</code>```

nestedComponentOne.js

```<code>import React from "react";

export default function nestedComponentOne() {
  return <div>NESTED COMPONENT 1</div>;
}
</code>```

nestedComponentTwo.js

```<code>import React from "react";

export default function nestedComponentTwo() {
  return <div>NESTED COMPONENT 2</div>;
}
</code>```

But, I still get a blank screen whenever I try to access a nested component...

答:
You have this problem:

React-router urls don't work when refreshing or writing manually

The simplest fix is to replace the BrowserRouter with a HashRouter

Body:
I have searched through different tutorials and multiple stackOverflow questions. And none of which, helped me solve a very basic problem:

Implement nested routes with react-router-dom

Here's my code so far:

App.js

  <Route exact path="/home" name="Home" component={DefaultLayout} />

DefaultLayout.js

 <Route path="/home/users" component={Users} />

When I go to /home/users, I get a blank screen because react-router-dom is looking-up the definition of that route inside App.js instead of searching it inside DefaultLayout.js..

So I have two questions:

QUESION 1: What am I doing wrong exactly?

QUESTION 2: How does react-router-dom know that it should look for the nested route inside DefaultLayout.js instead of inside App.js?

It has been two days and I still cannot solve this simple problem.

Any help is very much appreciated.

EDIT 1: I have started a new project just for the sake of implementing a very simple nested routing:

App.js

import React from "react";
import { BrowserRouter, Switch, Route } from "react-router-dom";

import ParentComponent from "./nestedComponents/ParentComponent";

function App() {
  return (

      <BrowserRouter>
        <Switch>
          <Route exact path="/home" name="Home" component={ParentComponent} />
        </Switch>
      </BrowserRouter>

  );
}

export default App;

ParentComponent.js

import React from "react";
import nestedComponentOne from "./nestedComponentOne";
import nestedComponentTwo from "./nestedComponentTwo";
import { Switch, Route } from "react-router-dom";

export default function ParentComponent() {
  return (

      PARENT COMPONENT
      <Switch>
        <Route path="home/nestedComponentOne" component={nestedComponentOne} />
        <Route path="home/nestedComponentTwo" component={nestedComponentTwo} />
      </Switch>

  );
}

nestedComponentOne.js

import React from "react";

export default function nestedComponentOne() {
  return
NESTED COMPONENT 1
;
}

nestedComponentTwo.js

import React from "react";

export default function nestedComponentTwo() {
  return
NESTED COMPONENT 2
;
}

But, I still get a blank screen whenever I try to access a nested component...


问:
What to do when laravel routing is duplicated in laravel
I have added two routes, as described below.

I want the following behavior.
/api/user/1 or /api/user/2 or . . . → UserController@show is excute

/api/user/auth → UserController@showAuthUser is excute

However, when call /api/user/auth, UserController@show is excuted.

How do I get what I want?

```<code>Route::get('user/{user_id}', 'Api\UserController@show');

Route::get('user/auth', 'Api\UserController@showAuthUser');
</code>```

答:
Switch the order of your routes

```<code>Route::get('user/auth', 'Api\UserController@showAuthUser');
Route::get('user/{user_id}', 'Api\UserController@show');
</code>```

Otherwise it expects 'auth' to be a 'user_id'

Body:
I have added two routes, as described below.

I want the following behavior.
/api/user/1 or /api/user/2 or . . . → UserController@show is excute

/api/user/auth → UserController@showAuthUser is excute

However, when call /api/user/auth, UserController@show is excuted.

How do I get what I want?

Route::get('user/{user_id}', 'Api\UserController@show');

Route::get('user/auth', 'Api\UserController@showAuthUser');

Body:
Switch the order of your routes

Route::get('user/auth', 'Api\UserController@showAuthUser');
Route::get('user/{user_id}', 'Api\UserController@show');

Otherwise it expects 'auth' to be a 'user_id'


问:
how to build singularity container from dockerfile
I want to build singularity container from dockerfile.

I have pulled and run docker images from docker hub with singularity.

```<code>singularity pull docker://ubuntu:latest
</code>```

I  have also build the image from singularity recipe file.

```<code>singularity build  cpp.sif singularity_file
</code>```

But I want to build singularity image from dockerfile.

Anyone know how to do it. Is it possible ???

答:
You cannot build a singularity container directly from a Dockerfile, but you can do it in a two-step process.

```<code>docker build -t local/my_container:latest .
sudo singularity build my_container.sif docker-daemon://local/my_container:latest
</code>```

Using docker://my_container looks for the container on Docker Hub. When you use docker-daemon, it looks at your locally built docker containers. You can also use Bootstrap: docker-daemon in a Singularity definition file.

EDIT: Both singularity and apptainer now require an explicit tag name for the source docker container. Answer updated accordingly.

Body:
I want to build singularity container from dockerfile.

I have pulled and run docker images from docker hub with singularity.

singularity pull docker://ubuntu:latest

I  have also build the image from singularity recipe file.

singularity build  cpp.sif singularity_file

But I want to build singularity image from dockerfile.

Anyone know how to do it. Is it possible ???

Body:
You cannot build a singularity container directly from a Dockerfile, but you can do it in a two-step process.

docker build -t local/my_container:latest .
sudo singularity build my_container.sif docker-daemon://local/my_container:latest

Using docker://my_container looks for the container on Docker Hub. When you use docker-daemon, it looks at your locally built docker containers. You can also use Bootstrap: docker-daemon in a Singularity definition file.

EDIT: Both singularity and apptainer now require an explicit tag name for the source docker container. Answer updated accordingly.


答: Without knowing what you want your regex to do it's hard to optimise it, but you could try passing RegexOptions.Compiled to the Regex constructor. This will take longer to construct the regex object but will mean it performs it's searches more quickly.</p>

Title: Reg Exp optimisation

Body:
I need to optimise the following reg exp so that it executes faster. Can anyone help?

([\d\w]{15}[\x01]\d{12}[\x01]\d{2}(.){6}((13((0[0-9]|([1-4][0-9])|5[0-9]))|14((0[0-9]|([1-2][0-9])|30)))[0-5][0-9])801(?:.*))

Thanks


问:
How to pass command line argument from oc start-build to dockerfile to set environment variable inside dockerfile
Used the below commands but the value for environment is not getting passed in Dockerfile.
Running these instances in oc container through groovy script:

oc start-build -e environment=ipte2 ipte2-isell-api-7 --from-dir=./isell-python-wrapper --follow=true

```<code>**WARNING**: Specifying environment variables with binary builds is not supported.
Uploading directory "isell-python-wrapper" as binary input for the build ...
build "ipte2-isell-api-7-1" started
2)oc start-build --build-arg environment=ipte2 ipte2-isell-api-5 --from-dir=./isell-python-wrapper --follow=true

**WARNING**: Specifying build arguments with binary builds is not supported.
Uploading directory "isell-python-wrapper" as binary input for the build ...
build "ipte2-isell-api-5-1" started

error
Removing intermediate container f7ff031b18b1
Step 35/44 : COPY script/${environment}-local.conf /sum/lpp/ebb/local.conf
error: build error: lstat script/-local.conf: no such file or directory
</code>```

Dockerfile

```<code>FROM wlp-base:0.1 #from statement base image
ARG environment

ENV environment=${environment}

COPY script/${environment}-local.conf
</code>```

I need to pass above environment value inside the copy command
if i pass ENV environment=ipte2
directly inside Dockerfile its working fine. But sending a command line argument, it doesn't get it.

答:
You may try automate editing of the YAML manifest file with the BuildConfig (e.g. with the yaml python package) to add entries to the buildArgs array, which is located in the dockerStrategy definition of the BuildConfig. For example:

```<code>dockerStrategy:
...
  buildArgs:
    - name: "foo"
      value: "bar"
</code>```

Refer to the relevant Openshift docs for more details.

Body:
Used the below commands but the value for environment is not getting passed in Dockerfile.
Running these instances in oc container through groovy script:

oc start-build -e environment=ipte2 ipte2-isell-api-7 --from-dir=./isell-python-wrapper --follow=true

**WARNING**: Specifying environment variables with binary builds is not supported.
Uploading directory "isell-python-wrapper" as binary input for the build ...
build "ipte2-isell-api-7-1" started
2)oc start-build --build-arg environment=ipte2 ipte2-isell-api-5 --from-dir=./isell-python-wrapper --follow=true

**WARNING**: Specifying build arguments with binary builds is not supported.
Uploading directory "isell-python-wrapper" as binary input for the build ...
build "ipte2-isell-api-5-1" started

error
Removing intermediate container f7ff031b18b1
Step 35/44 : COPY script/${environment}-local.conf /sum/lpp/ebb/local.conf
error: build error: lstat script/-local.conf: no such file or directory

Dockerfile

FROM wlp-base:0.1 #from statement base image
ARG environment

ENV environment=${environment}

COPY script/${environment}-local.conf

I need to pass above environment value inside the copy command
if i pass ENV environment=ipte2
directly inside Dockerfile its working fine. But sending a command line argument, it doesn't get it.

Body:
You may try automate editing of the YAML manifest file with the BuildConfig (e.g. with the yaml python package) to add entries to the buildArgs array, which is located in the dockerStrategy definition of the BuildConfig. For example:

dockerStrategy:
...
  buildArgs:
    - name: "foo"
      value: "bar"

Refer to the relevant Openshift docs for more details.


问:
Upload Large files Django Storages to AWS S3
I am a new Django, and I have a project that should upload large files (sizes from 5G+).

I am using:

django-storages

Amazon S3

Django 3.0.2

Python 3.7.6

JQuery 3.1

In documentation, it says that when the file is larger than 2.5MB, it goes to TemporaryFileUploadHander, which means it goes to /tmp directory first and when the upload is complete, it moves the file to Media Root (which in my case it is the Amazon S3)

Now, the requirement is to stream the upload of file to Amazon S3.
For example: 20Gb file should be uploaded in stream (little by little) to Amazon S3.
How can I implement this requirement to upload the file directly to Amazon S3 directly without having it first in /tmp directory.

Please give me some light.

答:
Streaming the file from the web client, to Django and then to S3 is not possible. Best solution is to split the files into chunks from client side JS and then upload them one by one. Sample code is here.

This solution will still save the smaller files to disk though.


问:
How to print key and values from the following collection?
I have the following collection that holds a dictionary:

```<code> {'EHAM': [78, [55, 23]], 'EGLL': [67, [46, 21]], 'LOWW': [67, [44, 23]], 'LFPG': [75, [43, 32]]}
</code>```

I'd like to print the collection in the following output data format:

```<code> NAME    #TOTAL     #TK     #LA
 EHAM    78         55      23
 EGLL    67         46      21
 LOWW    67         44      23
 LFPG    75         43      32
</code>```

Right now I'm getting the following ouput:

```<code>#NAME #TOTAL #TK #LA
 EHAM [78, [55, 23]]
 EGLL [67, [46, 21]]
 LOWW [67, [44, 23]]
 LFPG [75, [43, 32]]
</code>```

This is the piece of code I'm using:

```<code>#print(topAirpots_dict)
print("\n#NAME"+ " #TOTAL"+ " #TK"+ " #LA\n")
for k in (top_dict):
    print(k,top_dict[k])
</code>```

答:
If the number of elements in the list inside values of the dictionary doesn't change, the following solution works.</p>

```<code>print("\n#NAME"+ " #TOTAL"+ " #TK"+ " #LA\n")
for k in (top_dict):
    print(k, top_dict[k][0], top_dict[k][1][0], top_dict[k][1][1])
</code>```

Body:
I have the following collection that holds a dictionary:

 {'EHAM': [78, [55, 23]], 'EGLL': [67, [46, 21]], 'LOWW': [67, [44, 23]], 'LFPG': [75, [43, 32]]}

I'd like to print the collection in the following output data format:

 NAME    #TOTAL     #TK     #LA
 EHAM    78         55      23
 EGLL    67         46      21
 LOWW    67         44      23
 LFPG    75         43      32

Right now I'm getting the following ouput:

#NAME #TOTAL #TK #LA
 EHAM [78, [55, 23]]
 EGLL [67, [46, 21]]
 LOWW [67, [44, 23]]
 LFPG [75, [43, 32]]

This is the piece of code I'm using:

#print(topAirpots_dict)
print("\n#NAME"+ " #TOTAL"+ " #TK"+ " #LA\n")
for k in (top_dict):
    print(k,top_dict[k])

Body:
If the number of elements in the list inside values of the dictionary doesn't change, the following solution works.

print("\n#NAME"+ " #TOTAL"+ " #TK"+ " #LA\n")
for k in (top_dict):
    print(k, top_dict[k][0], top_dict[k][1][0], top_dict[k][1][1])


问:
Method Chaining based on condition
How can you do method chaining based on condition in laravel 4 ? Say if one value is not false then the method inside will be chained to the method called before the if statement.

Is it possible in laravel?

```<code>$data = User::where('username', $somevariable );

if(isset( $somevar_again ))
{
  $data->where('age', 21);
}
$data->orderBy('reg_date', 'DESC')->get();
return $data->first();
</code>```

// tried code above and its giving me wrong result
in codeigniter I can do this

```<code>$this->db->select('e.*, v.name_en as v_name_en')
    ->from($this->table_name . ' e, ' . $this->ptc_venues . ' v');
  $this->db->where('e.venue_id_en = v.id');

  if(isset($search)){
   $this->db->where('(v.name_en LIKE "%'.$search.'%")');
  }

  $this->db->limit($limit, $start);
  $this->db->order_by('e.added_date_en', 'DESC');
</code>```

答:
From Laravel 5.2 and onward, you can utilise Conditional Clauses/Statements:

Sometimes you may want statements to apply to a query only when
something else is true. For instance you may only want to apply a
where statement if a given input value is present on the incoming
request. You may accomplish this using the when method

The when method only executes the given Closure when the first parameter is true. If the first parameter is false, the Closure will not be executed.

You can use the code as follows:

```<code>$data = User::where('username', $somevariable)
              ->when( isset($somevar_again), function ($query) {
                      return $query->where('age', 21);
                   })
              ->orderBy('reg_date', 'DESC')
              ->get();
return $data->first();
</code>```

Also, note that Laravel 5.3+, it has further been extended as documented below:

You may pass another Closure as the third parameter to the when
method. This Closure will execute if the first parameter evaluates as
false

Title: Method Chaining based on condition

Body:
How can you do method chaining based on condition in laravel 4 ? Say if one value is not false then the method inside will be chained to the method called before the if statement.

Is it possible in laravel?

$data = User::where('username', $somevariable );

if(isset( $somevar_again ))
{
  $data->where('age', 21);
}
$data->orderBy('reg_date', 'DESC')->get();
return $data->first();

// tried code above and its giving me wrong result
in codeigniter I can do this

$this->db->select('e.*, v.name_en as v_name_en')
    ->from($this->table_name . ' e, ' . $this->ptc_venues . ' v');
  $this->db->where('e.venue_id_en = v.id');

  if(isset($search)){
   $this->db->where('(v.name_en LIKE "%'.$search.'%")');
  }

  $this->db->limit($limit, $start);
  $this->db->order_by('e.added_date_en', 'DESC');

Body:
From Laravel 5.2 and onward, you can utilise Conditional Clauses/Statements:

Sometimes you may want statements to apply to a query only when
something else is true. For instance you may only want to apply a
where statement if a given input value is present on the incoming
request. You may accomplish this using the when method

The when method only executes the given Closure when the first parameter is true. If the first parameter is false, the Closure will not be executed.

You can use the code as follows:

$data = User::where('username', $somevariable)
              ->when( isset($somevar_again), function ($query) {
                      return $query->where('age', 21);
                   })
              ->orderBy('reg_date', 'DESC')
              ->get();
return $data->first();

Also, note that Laravel 5.3+, it has further been extended as documented below:

You may pass another Closure as the third parameter to the when
method. This Closure will execute if the first parameter evaluates as
false


问:
How do I upload file to Azure function while publishing the code from Visual Studio?
I have created a Azure Function, which is having a dependency on ini file.

```<code> public class DataProcessingFunction
 {
    FunctionName("DataProcessingFunction")]
    public async Task Run([EventGridTrigger]EventGridEvent eventGridEvent,ILogger log)
    {
        string iniFolderPath = $@"{Directory.GetCurrentDirectory()}\Ini\";
        string iniFileName = "Sample.ini";
        var iniConfig = FileManager.ReadFile(iniFolderPath, iniFileName);
    }
 }
</code>```

I have selected Copy if never option in Visual Studio while publishing the code to Azure function
Also, I have tried selecting Embedded Resource. But I am not able to find the file

I get an exception

File not found.

Add/Upload option in Azure portal is disabled because I am publishing the function from Visual studio

Question: Do I need to upload file to blob and then refer it in a code?

答:
The final conclusion is that the file was successfully uploaded, the problem is that an error occurred while reading the path. It seems that using Directory.GetCurrentDirectory() in Azure is not reliable.

I just tried it and Directory.GetCurrentDirectory() got the wrong path in azure (I printed it out and it showed "D:\Program Files (x86)\SiteExtensions\Functions\2.0.12961\32bit", This is obviously not the current folder), and eventually it fails to find the Sample.ini file. Since the function is your own, you can set the path to something like "D:\\home\\site\\wwwroot>\\Ini\\Sample.ini". This should read the Sample.ini file.

Body:
I have created a Azure Function, which is having a dependency on ini file.

 public class DataProcessingFunction
 {
    FunctionName("DataProcessingFunction")]
    public async Task Run([EventGridTrigger]EventGridEvent eventGridEvent,ILogger log)
    {
        string iniFolderPath = $@"{Directory.GetCurrentDirectory()}\Ini\";
        string iniFileName = "Sample.ini";
        var iniConfig = FileManager.ReadFile(iniFolderPath, iniFileName);
    }
 }

I have selected Copy if never option in Visual Studio while publishing the code to Azure function
Also, I have tried selecting Embedded Resource. But I am not able to find the file

I get an exception

File not found.

Add/Upload option in Azure portal is disabled because I am publishing the function from Visual studio

Question: Do I need to upload file to blob and then refer it in a code?


问:
Oracle PL/SQL get current timestamp number 19
Is there a way in Oralce PL/SQL to get the current timestamp as a NUMBER ?

Something like '1582185277302'

答:
You can convert the current date/time to an epoch timestamp as follows:

```<code> (sysdate - date '1970-01-01') * 60 * 60 * 24
</code>```

This gives you the number of seconds since January 1st, 1970.

If you want the results in milliseconds, then:

```<code>(cast(systimestamp as date) - date '1970-01-01') * 24 * 60 * 60 * 1000
+ mod( extract(second from systimestamp), 1) * 1000
</code>```

Body:
You can convert the current date/time to an epoch timestamp as follows:

 (sysdate - date '1970-01-01') * 60 * 60 * 24

This gives you the number of seconds since January 1st, 1970.

If you want the results in milliseconds, then:

(cast(systimestamp as date) - date '1970-01-01') * 24 * 60 * 60 * 1000
+ mod( extract(second from systimestamp), 1) * 1000


问:
Is it possible to load new Javascript files with AJAX?
I'm building a new AJAX powered website with distinct sections.  Each section requires a new set of Javascript functions to run.  I'd rather not load every script at the start, as there might be quite a few.

Is there a way to load new scripts using AJAX and remove old ones (so as to make sure there are no compatibility issues with similar variable names or function signatures).

Thanks

Edit - JQuery is fine, it doesn't have to be old school Javascript

答:
I've never try it before...
but, you can try call a php form with ajax and add the new javascript to a div in body element..
I hope it'll work..</p>


问:
How to make the link inside Button change color on hover without hovering over link
My link changes color on hovering over it directly but does not change color when I hover over the button and not the link directly

```<code>btn:hover{
color: black;
}
</code>```

This does not work.

```<code>a:hover{
color:black
}
</code>```

This is working currently but does not do the job as needed.

How do I make the button change the color of the link when I hover over it?
As seen in the first image.

答:
btn is not an element so if it is a class you have to use .btn:hover else you have to use button:hover

The problem is, that your link doesn't fill the whole btn.
You have to use btn:hover but the color should change only on the link:

```<code>.btn:hover > a{
    color: black;
}
</code>```

Body:
My link changes color on hovering over it directly but does not change color when I hover over the button and not the link directly

btn:hover{
color: black;
}

This does not work.

a:hover{
color:black
}

This is working currently but does not do the job as needed.

How do I make the button change the color of the link when I hover over it?
As seen in the first image.

Body:
btn is not an element so if it is a class you have to use .btn:hover else you have to use button:hover

The problem is, that your link doesn't fill the whole btn.
You have to use btn:hover but the color should change only on the link:

.btn:hover > a{
    color: black;
}


问:
How can I use formdata in upload file on vuetify?
I try like this : https://codepen.io/positivethinking639/pen/OJVRjGL?editors=1010

My code :

```<code><v-form>
  <v-file-input multiple
                v-model="documents"
                label="File input"></v-file-input>
  <v-btn color="success" @click="submit()">
    test
  </v-btn>
</v-form>
</code>```

but it does not works

if I upload file and click button test, the formdata empty on the console

How can I solve this problem?

答:
You can simple use the spread operator to view formdata. FormData is part of the XMLHttpRequest spec.</p>

```<code>console.log(...formData);
</code>```

Body:
I try like this : https://codepen.io/positivethinking639/pen/OJVRjGL?editors=1010

My code :

<v-form>
  <v-file-input multiple
                v-model="documents"
                label="File input"></v-file-input>
  <v-btn color="success" @click="submit()">
    test
  </v-btn>
</v-form>

but it does not works

if I upload file and click button test, the formdata empty on the console

How can I solve this problem?

Body:
You can simple use the spread operator to view formdata. FormData is part of the XMLHttpRequest spec.

console.log(...formData);


问:
XML cannot be serialized - parameterless constructor error, even with constructor
I'm trying to serialize an object to xml using XmlSerializer but keep getting this error:

```<code>System.InvalidOperationException: [MySql.Data.MySqlClient.MySqlParameter] cannot be serialized because it does not have a parameterless constructor.
</code>```

I followed the solution to why xml serializable class need a parameterless constructor which seems to have solved the problem for everyone else, but I still get an error. When I add public MyClass() it gives me 'MyClass.MyClass()' must declare a body because it is not marked abstract, extern, or partial, so I add a body and the first error comes back.

Note that originally there aren't any constructors, parameterless or otherwise, so I don't understand why it isn't just automatically creating its own.

What am I doing wrong?

Code added:

MyFile.cs

```<code>public async Task Save(MyClass xmlObj)
{
    XmlSerializer xmlSer = new XmlSerializer(this.GetType()); //I think the problem is likely to be here
    StringWriter strWriter = new StringWriter();

    xmlSer.Serialize(strWriter, xmlObj);
    objToUpdate.ColName = (strWriter.ToString());
    await dbContext.SaveChangesAsync();
}
</code>```

File.cs

```<code>public async Task<IActionResult> SaveData(params...)
{
    await new MyFile<MySqlParameter>(accessParam, dbContext).Save(xmlObj);
}
</code>```

答:
I figured it out...

I had been creating a new XmlSerializer and passing in a parameter as posted in a SO answer:

XmlSerializer xmlSer = new XmlSerializer(this.GetType());

When really it works perfectly fine to use the same XmlSerializer as the deserialization:

XmlSerializer objSer = new XmlSerializer(typeof(MyClass));

Body:
I'm trying to serialize an object to xml using XmlSerializer but keep getting this error:

System.InvalidOperationException: [MySql.Data.MySqlClient.MySqlParameter] cannot be serialized because it does not have a parameterless constructor.

I followed the solution to why xml serializable class need a parameterless constructor which seems to have solved the problem for everyone else, but I still get an error. When I add public MyClass() it gives me 'MyClass.MyClass()' must declare a body because it is not marked abstract, extern, or partial, so I add a body and the first error comes back.

Note that originally there aren't any constructors, parameterless or otherwise, so I don't understand why it isn't just automatically creating its own.

What am I doing wrong?

Code added:

MyFile.cs

public async Task Save(MyClass xmlObj)
{
    XmlSerializer xmlSer = new XmlSerializer(this.GetType()); //I think the problem is likely to be here
    StringWriter strWriter = new StringWriter();

    xmlSer.Serialize(strWriter, xmlObj);
    objToUpdate.ColName = (strWriter.ToString());
    await dbContext.SaveChangesAsync();
}

File.cs

public async Task<IActionResult> SaveData(params...)
{
    await new MyFile<MySqlParameter>(accessParam, dbContext).Save(xmlObj);
}


问:
Reading a file with a skip (or delition) of a certain section of text from a txt.file
I just recently started to study Java and faced with such a problem.

How can I read a .txt file and skip or delete a specific piece of text?
In my case, the section to be deleted always looks like this:
1) Begin with string: ======= (80 equals "=" characters without spaces)
2) End with the same string: ======= (80 equals "=" characters without spaces)
3) Between these lines contains meta-information, which I need to delete or skip while reading, along with the lines of the beginning and end of this section

For example:
file.txt contains:

```<code>================================================================================
<some strings with text here>
================================================================================
abcd
asdfd
sdfgdfdf
</code>```

I need to get only strings:

```<code>abcd
asdfd
sdfgdfdf
</code>```

The maximum Java version to run is 8.

Thanks in advance for your help!

答:
You can read the file line by line and everytime you encounter this special line, start skipping until you encounter it again.

For example: (in is your input stream)

```<code>StringBuilder sb = new StringBuilder();
boolean skip = false;
while((String line = in.readLine()) != null) {
    if(line.equals("") {
        skip = !skip;
    }
    else if(!skip) {
        sb.append(line).append("\r\n");
    }
}
String fileContents = sb.toString();
</code>```

Body:
I just recently started to study Java and faced with such a problem.

How can I read a .txt file and skip or delete a specific piece of text?
In my case, the section to be deleted always looks like this:
1) Begin with string: ======= (80 equals "=" characters without spaces)
2) End with the same string: ======= (80 equals "=" characters without spaces)
3) Between these lines contains meta-information, which I need to delete or skip while reading, along with the lines of the beginning and end of this section

For example:
file.txt contains:

================================================================================
<some strings with text here>
================================================================================
abcd
asdfd
sdfgdfdf

I need to get only strings:

abcd
asdfd
sdfgdfdf

The maximum Java version to run is 8.

Thanks in advance for your help!

Body:
You can read the file line by line and everytime you encounter this special line, start skipping until you encounter it again.

For example: (in is your input stream)

StringBuilder sb = new StringBuilder();
boolean skip = false;
while((String line = in.readLine()) != null) {
    if(line.equals("") {
        skip = !skip;
    }
    else if(!skip) {
        sb.append(line).append("\r\n");
    }
}
String fileContents = sb.toString();


问:
CSS how can I get an inline display with a working ::first-line pseudo-element
This looks very simple, but I couldn't get it working, either with combinations of float, inline-block and so on. I am trying to get more space on the first line so that the second one doesn't "collide" with the header. I know that ::first-line doesn't work on inline elements. I want to keep this layout (the layout is what's important, not the inline display, so whatever works is OK). The solution should have a wide browser support.

My design must stay responsive, so the text shouldn't be cut in different parts. I could do it in javascript and keep it responsive by running a script on resize, but I really would like to avoid this solution.

EDIT: @TemaniAfif's comment about setting inline-block to the header does the trick for my special case, but for curiosity and future readers, it doesn't directly answer for the pseudo-element. For example if someone wanter to capitalize or change color, I feel the question is still valid, so I'm editing the snippet.

.heading {
  padding: 5px;
  background-color: blue;
  color: white;
}
.content {
  margin-left: 5px;
}
.content::first-line {
  line-height: 2;
  text-transform: uppercase;
  color: red;
}
.block {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><b>Display is fine, first-line doesn't work because of inline + margin left works fine:</b>
<br><br>

<span class="heading">header: </span>
<span class="content">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span>

<br><br>
<b>Display is out now that first-line works because of block (or inline-block) + margin left out too:</b>
<br><br>

<span class="heading">header: </span>
<span class="content block">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span></code>```

答:
You can try display: inline-block; in your .heading

.heading {
  padding: 5px;
  background-color: blue;
  color: white;
  display:inline-block;
}
.content {
  margin-left: 5px;
}
.content::first-line {
  line-height: 2;
}
.block {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><b>Display is fine, first-line doesn't work because of inline + margin left works fine:</b>
<br><br>

<span class="heading">header: </span>
<span class="content">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span>

<br><br>
<b>Display is out now that first-line works because of block (or inline-block) + margin left out too:</b>
<br><br>

<span class="heading">header: </span>
<span class="content block">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span></code>```

Body:
This looks very simple, but I couldn't get it working, either with combinations of float, inline-block and so on. I am trying to get more space on the first line so that the second one doesn't "collide" with the header. I know that ::first-line doesn't work on inline elements. I want to keep this layout (the layout is what's important, not the inline display, so whatever works is OK). The solution should have a wide browser support.

My design must stay responsive, so the text shouldn't be cut in different parts. I could do it in javascript and keep it responsive by running a script on resize, but I really would like to avoid this solution.

EDIT: @TemaniAfif's comment about setting inline-block to the header does the trick for my special case, but for curiosity and future readers, it doesn't directly answer for the pseudo-element. For example if someone wanter to capitalize or change color, I feel the question is still valid, so I'm editing the snippet.

.heading {
  padding: 5px;
  background-color: blue;
  color: white;
}
.content {
  margin-left: 5px;
}
.content::first-line {
  line-height: 2;
  text-transform: uppercase;
  color: red;
}
.block {
  display: block;
}

Display is fine, first-line doesn't work because of inline + margin left works fine:

header:
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Display is out now that first-line works because of block (or inline-block) + margin left out too:

header:
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Body:
You can try display: inline-block; in your .heading

.heading {
  padding: 5px;
  background-color: blue;
  color: white;
  display:inline-block;
}
.content {
  margin-left: 5px;
}
.content::first-line {
  line-height: 2;
}
.block {
  display: block;
}

<b>Display is fine, first-line doesn't work because of inline + margin left works fine:</b>
<br><br>

<span class="heading">header: </span>
<span class="content">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span>

<br><br>
<b>Display is out now that first-line works because of block (or inline-block) + margin left out too:</b>
<br><br>

<span class="heading">header: </span>
<span class="content block">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span>


问:
What is the best way to rollout web applications?
I'm trying to create a standard way of rolling out web applications for our company.  Currently we do it with zip files, vbscript/javascript, and manual some steps.

For thick client installs we generate MSI installers using Wise/Wix.  We don't create installers currently for websites as in general they are just xcopy deploy.  However we have some config files that need to be changed, verify that certain handlers are registered in IIS...  The list goes on.

Do most people use MSI installers for web applications as well, or some other tool/scripting language?

答:
I work for a state agency and we do all our deployments using a product called RepliWeb.

It works good because as dev's we have no control over the webservers. But we can deploy to a deployment area and run the RepliWeb job to do the deployment. Not sure on pricing though...

OwnerDisplayName: Mike Schall

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: dragonmantank


问:
FFMpeg library: how to precisely seek in an audio file
Using the FFMpeg library in my Android app, I try to understand how I can seek in an audio file, at a very precise position.

For example, I want to set the current position in my file to the frame #1234567 (in a file encoded at 44100 Hz), which is equivalent to seek at 27994.717 milliseconds.

To achieve that, here is what I tried:

```<code>// this:
av_seek_frame(formatContext, -1, 27994717, 0);

// or this:
av_seek_frame(formatContext, -1, 27994717, AVSEEK_FLAG_ANY);

// or even this:
avformat_seek_file(formatContext, -1, 27994617, 27994717, 27994817, 0);
</code>```

Using a position in microseconds gives me the best result so far.

But for some reason, the positioning is not totally accurate: when I extract the samples from the audio file, it doesn't start exactly at the expected position. There is a slight delay of about 30-40 milliseconds (even if I seek to the position 0, surprisingly...).

Do I use the function the right way, or even the right function?

EDIT

Here is how I can get the position:

```<code>AVPacket packet;
AVStream *stream = NULL;
AVFormatContext *formatContext = NULL;
AVCodec *dec = NULL;

// initialization:
avformat_open_input(&formatContext, filename, NULL, NULL);
avformat_find_stream_info(formatContext, NULL);
int audio_stream_index = av_find_best_stream(formatContext, AVMEDIA_TYPE_AUDIO, -1, -1, &dec, 0);
stream = formatContext->streams[audio_stream_index];

...

// later, when I extract samples, here is how I get my position, in microseconds:
av_read_frame(formatContext, &packet);
long position = (long) (1000000 * (packet.pts * ((float) stream->time_base.num / stream->time_base.den)));
</code>```

Thanks to that piece of code, I can get the position of the beginning of the current frame (frame = bloc of samples, the size depends on the audio format - 1152 samples for mp3, 128 to 1152 for ogg, ...)

The problem is: the value I get in position is not accurate: it's actually 30 ms late, approximately. For example, when it says 1000000, the actual position is approximately 1030000...

What did I do wrong? Is it a bug in FFMpeg?

Thanks for your help.

答:
Late, but hopefully, it helps someone. The idea is to save timestamp when seeking and then compare AVPacket->pts with this value (You can do that with  AVStream->dts, but it wasn't giving good results in my experiments). If pts is still lower than our target timestamp, then skip frames using AV_PKT_DATA_SKIP_SAMPLES ability of AVPacket->side_data.

Code for seeking method:

```<code>void audio_decoder::seek(float seconds) {
    auto stream = m_format_ctx->streams[m_packet->stream_index];

    // convert seconds provided by the user to a timestamp in a correct base,
    // then save it for later.
    m_target_ts = av_rescale_q(seconds * AV_TIME_BASE, AV_TIME_BASE_Q, stream->time_base);

    avcodec_flush_buffers(m_codec_ctx.get());

    // Here we seek within given stream index and the correct timestamp
    // for that stream. Using AVSEEK_FLAG_BACKWARD to make sure we're
    // always *before* requested timestamp.
    if(int err = av_seek_frame(m_format_ctx.get(), m_packet->stream_index, m_target_ts, AVSEEK_FLAG_BACKWARD)) {
        error("audio_decoder: Error while seeking ({})", av_err_str(err));
    }
}
</code>```

And code for decoding method:

```<code>void audio_decoder::decode() {
   <...>

   while(is_decoding) {
       // Read data as usual.
       av_read_frame(m_format_ctx.get(), m_packet.get());

       // Here is the juicy part. We were seeking, but the seek
       // wasn't precise enough so we need to drop some frames.
       if(m_packet->pts > 0 && m_target_ts > 0 && m_packet->pts < m_target_ts) {
            auto stream = m_format_ctx->streams[m_packet->stream_index];

            // Conversion from delta timestamp to frames.
            auto time_delta = static_cast<float>(m_target_ts - m_packet->pts) / stream->time_base.den;
            int64_t skip_frames = time_delta * m_codec_ctx->time_base.den / m_codec_ctx->time_base.num;

            // Next step: we need to provide side data to our packet,
            // and it will tell the codec to drop frames.
            uint8_t *data = av_packet_get_side_data(m_packet.get(), AV_PKT_DATA_SKIP_SAMPLES, nullptr);
            if(!data) {
                 data = av_packet_new_side_data(m_packet.get(), AV_PKT_DATA_SKIP_SAMPLES, 10);
            }

            // Define parameters of side data. You can check them here:
            // https://ffmpeg.org/doxygen/trunk/group__lavc__packet.html#ga9a80bfcacc586b483a973272800edb97
            *reinterpret_cast<uint32_t*>(data) = skip_frames;
            data[8] = 0;
        }

        // Send packet as usual.
        avcodec_send_packet(m_codec_ctx.get(), m_packet.get());

        // Proceed to the receiving frames as usual, nothing to change there.
   }
   <...>
}
</code>```

If it's unclear without context, you can check the same code in my project audio_decoder.cpp.

Body:
Using the FFMpeg library in my Android app, I try to understand how I can seek in an audio file, at a very precise position.

For example, I want to set the current position in my file to the frame #1234567 (in a file encoded at 44100 Hz), which is equivalent to seek at 27994.717 milliseconds.

To achieve that, here is what I tried:

// this:
av_seek_frame(formatContext, -1, 27994717, 0);

// or this:
av_seek_frame(formatContext, -1, 27994717, AVSEEK_FLAG_ANY);

// or even this:
avformat_seek_file(formatContext, -1, 27994617, 27994717, 27994817, 0);

Using a position in microseconds gives me the best result so far.

But for some reason, the positioning is not totally accurate: when I extract the samples from the audio file, it doesn't start exactly at the expected position. There is a slight delay of about 30-40 milliseconds (even if I seek to the position 0, surprisingly...).

Do I use the function the right way, or even the right function?

EDIT

Here is how I can get the position:

AVPacket packet;
AVStream *stream = NULL;
AVFormatContext *formatContext = NULL;
AVCodec *dec = NULL;

// initialization:
avformat_open_input(&formatContext, filename, NULL, NULL);
avformat_find_stream_info(formatContext, NULL);
int audio_stream_index = av_find_best_stream(formatContext, AVMEDIA_TYPE_AUDIO, -1, -1, &dec, 0);
stream = formatContext->streams[audio_stream_index];

...

// later, when I extract samples, here is how I get my position, in microseconds:
av_read_frame(formatContext, &packet);
long position = (long) (1000000 * (packet.pts * ((float) stream->time_base.num / stream->time_base.den)));

Thanks to that piece of code, I can get the position of the beginning of the current frame (frame = bloc of samples, the size depends on the audio format - 1152 samples for mp3, 128 to 1152 for ogg, ...)

The problem is: the value I get in position is not accurate: it's actually 30 ms late, approximately. For example, when it says 1000000, the actual position is approximately 1030000...

What did I do wrong? Is it a bug in FFMpeg?

Thanks for your help.

Body:
Late, but hopefully, it helps someone. The idea is to save timestamp when seeking and then compare AVPacket->pts with this value (You can do that with  AVStream->dts, but it wasn't giving good results in my experiments). If pts is still lower than our target timestamp, then skip frames using AV_PKT_DATA_SKIP_SAMPLES ability of AVPacket->side_data.

Code for seeking method:

void audio_decoder::seek(float seconds) {
    auto stream = m_format_ctx->streams[m_packet->stream_index];

    // convert seconds provided by the user to a timestamp in a correct base,
    // then save it for later.
    m_target_ts = av_rescale_q(seconds * AV_TIME_BASE, AV_TIME_BASE_Q, stream->time_base);

    avcodec_flush_buffers(m_codec_ctx.get());

    // Here we seek within given stream index and the correct timestamp
    // for that stream. Using AVSEEK_FLAG_BACKWARD to make sure we're
    // always *before* requested timestamp.
    if(int err = av_seek_frame(m_format_ctx.get(), m_packet->stream_index, m_target_ts, AVSEEK_FLAG_BACKWARD)) {
        error("audio_decoder: Error while seeking ({})", av_err_str(err));
    }
}

And code for decoding method:

void audio_decoder::decode() {
   <...>

   while(is_decoding) {
       // Read data as usual.
       av_read_frame(m_format_ctx.get(), m_packet.get());

       // Here is the juicy part. We were seeking, but the seek
       // wasn't precise enough so we need to drop some frames.
       if(m_packet->pts > 0 && m_target_ts > 0 && m_packet->pts < m_target_ts) {
            auto stream = m_format_ctx->streams[m_packet->stream_index];

            // Conversion from delta timestamp to frames.
            auto time_delta = static_cast<float>(m_target_ts - m_packet->pts) / stream->time_base.den;
            int64_t skip_frames = time_delta * m_codec_ctx->time_base.den / m_codec_ctx->time_base.num;

            // Next step: we need to provide side data to our packet,
            // and it will tell the codec to drop frames.
            uint8_t *data = av_packet_get_side_data(m_packet.get(), AV_PKT_DATA_SKIP_SAMPLES, nullptr);
            if(!data) {
                 data = av_packet_new_side_data(m_packet.get(), AV_PKT_DATA_SKIP_SAMPLES, 10);
            }

            // Define parameters of side data. You can check them here:
            // https://ffmpeg.org/doxygen/trunk/group__lavc__packet.html#ga9a80bfcacc586b483a973272800edb97
            *reinterpret_cast<uint32_t*>(data) = skip_frames;
            data[8] = 0;
        }

        // Send packet as usual.
        avcodec_send_packet(m_codec_ctx.get(), m_packet.get());

        // Proceed to the receiving frames as usual, nothing to change there.
   }
   <...>
}

If it's unclear without context, you can check the same code in my project audio_decoder.cpp.


问:
How to get values without key from JSON object in JavaScript(HTML)

                 [17/02/2020]      [18/02/2020]    [19/02/2020]
itemseq    1 Allocated        2             6              7
itemname   2 Out Of Order     0             0              0```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>success: function (result) {
                    debugger;
                    var Item1 = JSON.parse(result.Item1)

                    if (Item1.length == 0) {
                        $('<tr><td colspan="4">No Record Found</td></tr>').appendTo($('#Tablev'));
                    }
                    $('#Tablev tr:not(:first)').empty();

                        $('<tr>' +
                            '<th ' + item.itemseq+ '</th>' +
                            '<th>' + item.itemname + '</th>' +
                            (need to get the Date and date values like we got the above 2 things)

                            '</tr>').appendTo($('#Tablev'));
                    });</code>```

I'm trying to add  key values for eg-(dates "16/02/2020"): and the value it contains(0) and show them on a grid, I managed to get the itemseq and itemname but I have no idea how to get the other two key values.The dates and value are received from mssql on user input date ranges.

JSON string in JavaScript I receive is (the json string keeps ongoing on this is half of the code)

```<code>[
  {
    "itemseq": 1,
    "itemname": "Allocated",
    "17/02/2020": 2,
    "18/02/2020": 6,
    "19/02/2020": 7,
    "20/02/2020": 3,
    "21/02/2020": 7,
    "22/02/2020": 6,
    "23/02/2020": 2,
    "24/02/2020": 5
  },
  {
    "itemseq": 2,
    "itemname": "Out Of Order",
    "17/02/2020": 0,
    "18/02/2020": 0,
    "19/02/2020": 0,
    "20/02/2020": 0,
    "21/02/2020": 0,
    "22/02/2020": 0,
    "23/02/2020": 0,
    "24/02/2020": 0
  },
  {
    "itemseq": 3,
    "itemname": "Daily Occupancy %",
    "17/02/2020": 28.57,
    "18/02/2020": 85.71,
    "19/02/2020": 100,
    "20/02/2020": 42.85,
    "21/02/2020": 100,
    "22/02/2020": 85.71,
    "23/02/2020": 28.57,
    "24/02/2020": 71.42
  }
]
</code>```

How could i take the dates and the values of the dates it contains
"(date)18/02/2020": (value)85.71,

when we are using the string we can break the string and get the values like
(item.itemseq item.itemname) and i want to know how could i get the values of dates and the date values because these data are passed to a grid and gonna be used there..

eg-
columns- the dates [18/02/2020] [19/02/2020]
and the rows wise we have the [Allocated][Out Of Order] for the specific date it should contains the value that date has [85.71][100]

Body:
                 [17/02/2020]      [18/02/2020]    [19/02/2020]
itemseq    1 Allocated        2             6              7
itemname   2 Out Of Order     0             0              0

success: function (result) {
                    debugger;
                    var Item1 = JSON.parse(result.Item1)

                    if (Item1.length == 0) {
                        $('
No Record Found
').appendTo($('#Tablev'));
                    }
                    $('#Tablev tr:not(:first)').empty();

                        $('
' +
                            '<th ' + item.itemseq+ '	' +
                            '' + item.itemname + '	' +
                            (need to get the Date and date values like we got the above 2 things)

                            '
').appendTo($('#Tablev'));
                    });

I'm trying to add  key values for eg-(dates "16/02/2020"): and the value it contains(0) and show them on a grid, I managed to get the itemseq and itemname but I have no idea how to get the other two key values.The dates and value are received from mssql on user input date ranges.

JSON string in JavaScript I receive is (the json string keeps ongoing on this is half of the code)

[
  {
    "itemseq": 1,
    "itemname": "Allocated",
    "17/02/2020": 2,
    "18/02/2020": 6,
    "19/02/2020": 7,
    "20/02/2020": 3,
    "21/02/2020": 7,
    "22/02/2020": 6,
    "23/02/2020": 2,
    "24/02/2020": 5
  },
  {
    "itemseq": 2,
    "itemname": "Out Of Order",
    "17/02/2020": 0,
    "18/02/2020": 0,
    "19/02/2020": 0,
    "20/02/2020": 0,
    "21/02/2020": 0,
    "22/02/2020": 0,
    "23/02/2020": 0,
    "24/02/2020": 0
  },
  {
    "itemseq": 3,
    "itemname": "Daily Occupancy %",
    "17/02/2020": 28.57,
    "18/02/2020": 85.71,
    "19/02/2020": 100,
    "20/02/2020": 42.85,
    "21/02/2020": 100,
    "22/02/2020": 85.71,
    "23/02/2020": 28.57,
    "24/02/2020": 71.42
  }
]

How could i take the dates and the values of the dates it contains
"(date)18/02/2020": (value)85.71,

when we are using the string we can break the string and get the values like
(item.itemseq item.itemname) and i want to know how could i get the values of dates and the date values because these data are passed to a grid and gonna be used there..

eg-
columns- the dates [18/02/2020] [19/02/2020]
and the rows wise we have the [Allocated][Out Of Order] for the specific date it should contains the value that date has [85.71][100]

Body:
Try this

const json = [{"itemseq":1,"itemname":"Allocated","17/02/2020":2.0000,"18/02/2020":6.0000,"19/02/2020":7.0000,"20/02/2020":3.0000,"21/02/2020":7.0000,"22/02/2020":6.0000,"23/02/2020":2.0000,"24/02/2020":5.0000},{"itemseq":2,"itemname":"Out Of Order","17/02/2020":0.0000,"18/02/2020":0.0000,"19/02/2020":0.0000,"20/02/2020":0.0000,"21/02/2020":0.0000,"22/02/2020":0.0000,"23/02/2020":0.0000,"24/02/2020":0.0000},{"itemseq":3,"itemname":"Daily Occupancy %","17/02/2020":28.5700,"18/02/2020":85.7100,"19/02/2020":100.0000,"20/02/2020":42.8500,"21/02/2020":100.0000,"22/02/2020":85.7100,"23/02/2020":28.5700,"24/02/2020":71.4200}]

json.map((item) => {
 console.log(item["21/02/2020"])
})

It will return:

7
0
100


问:
Pass parameter to BLOB object URL
Say I've got a reference to a html file as a Blob b and I create a URL for it, url = URL.createObjectURL(b);.

This gives me something that looks like blob:http%3A//example.com/a0440b61-4850-4568-b6d1-329bae4a3276

I then tried opening this in an  with a GET parameter ?foo=bar, but it didn't work. How can I pass the parameter?

```<code>var html ='<html><head><title>Foo</title></head><body><script>document.body.textContent = window.location.search<\/script></body></html>',
    b = new Blob([html], {type: 'text/html'}),
    url = URL.createObjectURL(b),
    ifrm = document.createElement('iframe');
ifrm.src = url + '?foo=bar';
document.body.appendChild(ifrm);

// expect to see ?foo=bar in <iframe>
</code>```

DEMO

答:
If you are doing this with a Javascript Blob for say a WebWorker then you can just to add the parameters into the Blob constructor as a global variable:

```<code>const parameters = 'parameters = ' + JSON.stringify({foo:'bar'});
const body = response.body; // From some previous HTTP request
const blob = new Blob([parameters, body], { type: 'application/javascript' });
new Worker(URL.createObjectURL(blob));
</code>```

Or more general case just store the original URL on the location object

```<code>const location = 'location.originalHref = "' + url + '";';
const body = response.body; // From some previous HTTP request
const blob = new Blob([location, body], { type: 'application/javascript' });
new Worker(URL.createObjectURL(blob));
</code>```

You could also do this with HTML if you can add them say to the root  tag as attributes or use the <BASE> element for the url or insert them as a script tag but this would require you to modify the response HTML rather then just prepend some extra data

Title: Pass parameter to BLOB object URL

Body:
Say I've got a reference to a html file as a Blob b and I create a URL for it, url = URL.createObjectURL(b);.

This gives me something that looks like blob:http%3A//example.com/a0440b61-4850-4568-b6d1-329bae4a3276

I then tried opening this in an  with a GET parameter ?foo=bar, but it didn't work. How can I pass the parameter?

var html ='<title>Foo</title>

Body:
If you are doing this with a Javascript Blob for say a WebWorker then you can just to add the parameters into the Blob constructor as a global variable:

const parameters = 'parameters = ' + JSON.stringify({foo:'bar'});
const body = response.body; // From some previous HTTP request
const blob = new Blob([parameters, body], { type: 'application/javascript' });
new Worker(URL.createObjectURL(blob));

Or more general case just store the original URL on the location object

const location = 'location.originalHref = "' + url + '";';
const body = response.body; // From some previous HTTP request
const blob = new Blob([location, body], { type: 'application/javascript' });
new Worker(URL.createObjectURL(blob));

You could also do this with HTML if you can add them say to the root <HTML> tag as attributes or use the <BASE> element for the url or insert them as a script tag but this would require you to modify the response HTML rather then just prepend some extra data