问:
Extract first integer in a string with PHP
Consider the following strings:

```<code>$strings = array(
    "8.-10. stage",
    "8. stage"
);
</code>```

I would like to extract the first integer of each string, so it would return

```<code>8
8
</code>```

I tried to filter out numbers with preg_replace but it returns all integers and I only want the first.

```<code>foreach($strings as $string)
{
    echo preg_replace("/[^0-9]/", '',$string);
}
</code>```

Any suggestions?

答:
How to filter out all characters except for the first occurring whole integer:

It is possible that the target integer is not at the start of the string (even if the OP's question only provides samples that start with an integer -- other researchers are likely to require more utility ...like the pages that I closed today using this page). It is also possible that the input contains no integers, or no leading / no trailing non-numeric characters.

The following is a regex expression has two checks:

It targets all non-numeric characters from the start of the string -- it stops immediately before the first encountered digit, if there is one at all.

It matches/consumes the first encountered whole integer, then immediatelly forgets/releases it (using \K) before matching/consuming ANY encountered characters in the remainder of the string.

My snippet will make 0, 1, or 2 replacements depending on the quality of the string.

Code: (Demo)

```<code>$strings = [
    'stage', // expect empty string
    '8.-10. stage', // expect 8
    '8. stage', // expect 8
    '8.-10. stage 1st', // expect 8
    'Test 8. stage 2020', // expect 8
    'Test 8.-10. stage - 2020 test', // expect 8
    'A1B2C3D4D5E6F7G8', // expect 1
    '1000', // expect 1000
    'Test 2020', // expect 2020
];

var_export(
    preg_replace('/^\D+|\d+\K.*/', '', $strings)
);
</code>```

Or: (Demo)

```<code>preg_replace('/^\D*(\d+).*/', '$1', $strings)
</code>```

Output:

```<code>array (
  0 => '',
  1 => '8',
  2 => '8',
  3 => '8',
  4 => '8',
  5 => '8',
  6 => '1',
  7 => '1000',
  8 => '2020',
)
</code>```

Body:
Consider the following strings:

$strings = array(
    "8.-10. stage",
    "8. stage"
);

I would like to extract the first integer of each string, so it would return

8
8

I tried to filter out numbers with preg_replace but it returns all integers and I only want the first.

foreach($strings as $string)
{
    echo preg_replace("/[^0-9]/", '',$string);
}

Any suggestions?

Body:
How to filter out all characters except for the first occurring whole integer:

It is possible that the target integer is not at the start of the string (even if the OP's question only provides samples that start with an integer -- other researchers are likely to require more utility ...like the pages that I closed today using this page). It is also possible that the input contains no integers, or no leading / no trailing non-numeric characters.

The following is a regex expression has two checks:

It targets all non-numeric characters from the start of the string -- it stops immediately before the first encountered digit, if there is one at all.

It matches/consumes the first encountered whole integer, then immediatelly forgets/releases it (using \K) before matching/consuming ANY encountered characters in the remainder of the string.

My snippet will make 0, 1, or 2 replacements depending on the quality of the string.

Code: (Demo)

$strings = [
    'stage', // expect empty string
    '8.-10. stage', // expect 8
    '8. stage', // expect 8
    '8.-10. stage 1st', // expect 8
    'Test 8. stage 2020', // expect 8
    'Test 8.-10. stage - 2020 test', // expect 8
    'A1B2C3D4D5E6F7G8', // expect 1
    '1000', // expect 1000
    'Test 2020', // expect 2020
];

var_export(
    preg_replace('/^\D+|\d+\K.*/', '', $strings)
);

Or: (Demo)

preg_replace('/^\D*(\d+).*/', '$1', $strings)

Output:

array (
  0 => '',
  1 => '8',
  2 => '8',
  3 => '8',
  4 => '8',
  5 => '8',
  6 => '1',
  7 => '1000',
  8 => '2020',
)


来源: stackexchange

问:
Using Entity Framework Core DbContext Pooling with Simple Injector
Looking at the examples of how to use db context pool I see it was designed to be used with ServiceCollection:

```<code>var serviceProvider = new ServiceCollection()
    .AddDbContextPool<AdventureWorksContext>(options => { //options })
    .BuildServiceProvider();
</code>```

But what about Simple Injector? is it possible to register DB pooling in the Simple Injector container?

p.s. My app is not ASP.NET MVC, it's just a kinda DAL

答:
Adding to @Steven's excellent answer, here's his console application answer, but with the context (implicitly) using UseInternalServiceProvider.

```<code>var services = new ServiceCollection();
services.AddEntityFrameworkSqlServer();
services.AddSingleton<Microsoft.Extensions.Logging.ILoggerFactory>(new Microsoft.Extensions.Logging.LoggerFactory());
services.AddSingleton<IInterface>(new MyImplemenation());

services.AddDbContextPool<EFViewAndManyToManyDb>(optionsBuilder => {
  optionsBuilder.UseSqlServer("");
});

services.AddSimpleInjector(container);

services
  .BuildServiceProvider(validateScopes: true)
  .UseSimpleInjector(container);
</code>```

Here's why you'd want to use UseInternalServiceProvider. TLDR: if your DbContext has a dependencies, e.g. IInterface. You'll also need to add the SimpleInjector.Integration.ServiceCollection Nuget package.

ContentLicense: CC BY-SA 4.0

Body:
Looking at the examples of how to use db context pool I see it was designed to be used with ServiceCollection:

var serviceProvider = new ServiceCollection()
    .AddDbContextPool<AdventureWorksContext>(options => { //options })
    .BuildServiceProvider();

But what about Simple Injector? is it possible to register DB pooling in the Simple Injector container?

p.s. My app is not ASP.NET MVC, it's just a kinda DAL

Body:
Adding to @Steven's excellent answer, here's his console application answer, but with the context (implicitly) using UseInternalServiceProvider.

var services = new ServiceCollection();
services.AddEntityFrameworkSqlServer();
services.AddSingleton<Microsoft.Extensions.Logging.ILoggerFactory>(new Microsoft.Extensions.Logging.LoggerFactory());
services.AddSingleton<IInterface>(new MyImplemenation());

services.AddDbContextPool<EFViewAndManyToManyDb>(optionsBuilder => {
  optionsBuilder.UseSqlServer("");
});

services.AddSimpleInjector(container);

services
  .BuildServiceProvider(validateScopes: true)
  .UseSimpleInjector(container);

Here's why you'd want to use UseInternalServiceProvider. TLDR: if your DbContext has a dependencies, e.g. IInterface. You'll also need to add the SimpleInjector.Integration.ServiceCollection Nuget package.


问:
automatically execute commands on anaconda prompt startup
In linux I can put commands in my .bashrc file that will automatically execute every time I open terminal. For example, I I have this line in my bashrc

```<code>conda info --envs
</code>```

I get a list of all the environments. How can I set up my windows installation of anaconda 3 to do the same?

答:
I figured it out and am posting the working result in case anyone asks the same question.
Open the anaconda directory and in there open the scripts directory. Open the file 'activate.bat' in a text editor. add any commands you want to execute after 'line 26 :END'
with the prefix '@CALL' So for example my line 27 read '@CALL conda info --envs'. Now every time I open an anaconda prompt, that command executes.</p>

Body:
In linux I can put commands in my .bashrc file that will automatically execute every time I open terminal. For example, I I have this line in my bashrc

conda info --envs

I get a list of all the environments. How can I set up my windows installation of anaconda 3 to do the same?


问:
How do i get the position of a child element
i need to find the position of a child element.

i have a table and when a td is clicked, i want the position of the td(0,1 or 2)

```<code><table>
<tr>
 <td>

 </td>
 <td>

 </td>
 <td>

 </td>
</tr>
</table>
</code>```

and a script like this

```<code><script>
$("td").click(function(){
  //how do i get the position of the td?
  alert("column " + columnPosition + "is clicked")
});
</script>
</code>```

答:
```<code><script>
$("td").click(function(){
  //how do i get the position of the td?
  alert("column " + $(this).parent().children().index(this) + " is clicked")
});
</script>
</code>```

edit: I tested it, and it works

OwnerDisplayName: MichaelD

ContentLicense: CC BY-SA 3.0

Body:
i need to find the position of a child element.

i have a table and when a td is clicked, i want the position of the td(0,1 or 2)

and a script like this

Body:
<script>
$("td").click(function(){
  //how do i get the position of the td?
  alert("column " + $(this).parent().children().index(this) + " is clicked")
});
</script>

edit: I tested it, and it works

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Paolo Bergantino


问:
Android retain callback state after configuration change
I understand pretty well about Android lifecycle. I post here because I've observed one weird behavior, anyway this is my own thought.

My case is like this: One activity will use a simple layout with just a single EditText. In the activity onCreate method, i set some default text to the EditText and in later part of the method, assign a TextWatcher to the EditText so whenever user types in anything, i can response in my own way.

Everything is alright until I rotate the screen. The TextWatcher callback starts to react against the code that initialize the EditText.

According to the normal code flow, the TextWatcher is assigned later after initializing text value of the EditText. so it's not supposed to fire because of the text assignment in the onCreate method.

Could anyone here explain this?

答:
Here is why you see this behavior:

When 'onCreate' method is called first time, it has no saved state. Which means Bundle savedInstanceState parameter is null.

When configuration changed, Android paths non-null value in savedInstanceState parameter.

After configuration is changed, and onCreate returns, Android calls onRestoreInstateState.

By default, all views that have id are trying to restore their state, EditText restores its state too (actually, that TextView who restores most of it).

At some place during state restoration (but after onCreate method is completed) your EditText control calls setText on himself in order to restore text that it had just before configuration changed.

Your new TextWatcher that you added in onCreate method is notified about this change.

Just to make this clear, your old TextWatcher, that you added on first call to onCreate, is not preserved! Its new TextWatcher, that was added on last call to onCreate, which receives the text change notification.

You can examine TextView.onRestoreInstanceState yourself.


问:
First job in second stage contains previous job's state in GitLab
I have run across an issue where the first job in my test stage receives the entire state of my previous build job when I don't expect it too. I've simplified the problem down as much as possible in order to still reproduce the issue. Essentially, build runs and checks out my repo. ls -al prints the working directory out which contains my checked out repo. test-one runs, skips the git checkout, and prints the working directory which contains the git checkout from the previous build job. test-two runs, skips the git checkout, and prints the working directory which contains an empty directory as expected.

My questions are, did I configure my .gitlab-ci.yml file incorrectly, do my expectations lack understanding of how GitLab should work, is GitLab or the runner improperly configured, or is this a bug?

Things to note:

I am using GitLab version: 12.6.4-ee

I am NOT the GitLab administrator

The jobs do not depend on each other and the scripts simply print the current working directory.

My docker image is simply a clean base image of a Linux distro with nothing but common Linux commands installed.

linux-runner is a GitLab-runner running as a service on my Linux server.

I disable git from checking out my repo in the test jobs in order to see that the checkout from the build job is present in test-one.

Below is my .gitlab-ci.yml file simplified:

```<code>image: $DOCKER_REGISTRY/my-image:latest

build:
    stage: build
    tags:
        - linux-runner
    script:
        - ls -al

test-one:
    stage: test
    tags:
        - linux-runner
    variables:
        GIT_STRATEGY: none
    script:
        - ls -al

 test-two:
    stage: test
    tags:
        - linux-runner
    variables:
        GIT_STRATEGY: none
    script:
        - ls -al
</code>```

答:
image: $DOCKER_REGISTRY/my-image:latest

```<code>stages: # <-- add them all
  - build
  - test1
  - test2

build:
    stage: build
    tags:
        - linux-runner
    script:
        - ls -al

test-one:
    stage: test1 # <-- change this
    tags:
        - linux-runner
    variables:
        GIT_STRATEGY: none
    script:
        - ls -al

 test-two:
    stage: test2 # <-- change this
    tags:
        - linux-runner
    variables:
        GIT_STRATEGY: none
    script:
        - ls -al
</code>```

On your case test-one & test-two share the same "kind of" environment.

By setting up two different stages, they'll have their own environment

Body:
I have run across an issue where the first job in my test stage receives the entire state of my previous build job when I don't expect it too. I've simplified the problem down as much as possible in order to still reproduce the issue. Essentially, build runs and checks out my repo. ls -al prints the working directory out which contains my checked out repo. test-one runs, skips the git checkout, and prints the working directory which contains the git checkout from the previous build job. test-two runs, skips the git checkout, and prints the working directory which contains an empty directory as expected.

My questions are, did I configure my .gitlab-ci.yml file incorrectly, do my expectations lack understanding of how GitLab should work, is GitLab or the runner improperly configured, or is this a bug?

Things to note:

I am using GitLab version: 12.6.4-ee

I am NOT the GitLab administrator

The jobs do not depend on each other and the scripts simply print the current working directory.

My docker image is simply a clean base image of a Linux distro with nothing but common Linux commands installed.

linux-runner is a GitLab-runner running as a service on my Linux server.

I disable git from checking out my repo in the test jobs in order to see that the checkout from the build job is present in test-one.

Below is my .gitlab-ci.yml file simplified:

image: $DOCKER_REGISTRY/my-image:latest

build:
    stage: build
    tags:
        - linux-runner
    script:
        - ls -al

test-one:
    stage: test
    tags:
        - linux-runner
    variables:
        GIT_STRATEGY: none
    script:
        - ls -al

 test-two:
    stage: test
    tags:
        - linux-runner
    variables:
        GIT_STRATEGY: none
    script:
        - ls -al

Body:
image: $DOCKER_REGISTRY/my-image:latest

stages: # <-- add them all
  - build
  - test1
  - test2

build:
    stage: build
    tags:
        - linux-runner
    script:
        - ls -al

test-one:
    stage: test1 # <-- change this
    tags:
        - linux-runner
    variables:
        GIT_STRATEGY: none
    script:
        - ls -al

 test-two:
    stage: test2 # <-- change this
    tags:
        - linux-runner
    variables:
        GIT_STRATEGY: none
    script:
        - ls -al

On your case test-one & test-two share the same "kind of" environment.

By setting up two different stages, they'll have their own environment


问:
Display my .NET Standard assembly in the Add Reference dialog for a UWP application
I am trying to figure out how to display my .NET Standard assembly in the Visual Studio Reference Manager under Assemblies/Extensions for a UWP application.

I currently do this with a .NET Framework assembly for .NET Framework applications by setting the proper registry key (from the Microsoft docs article):

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft.NETFramework\\AssemblyFoldersEx\MyAssemblies]@=""

This works great for .NET Framework, but I cannot figure out how to do the same thing for my .NET Standard 2.0 assembly and UWP applications.

For example, with the above registry addition and a .NET Framework project, my .NET Framework assembly is automatically shown in the Reference Manager dialog under Assemblies/Extensions.  In addition, projects that have a reference to the assembly know where it is located.

I can't seem to do this with a .NET Standard 2.0 assembly and a UWP project.  The registry entry appears to be only for .NET Framework assemblies, not assemblies used with UWP.  Part of the registry key is the lowest version of the .NET Framework my assembly supports.  For example:
HKEY_LOCAL_MACHINE\Software\Microsoft.NETFramework\v2.0.50727\AssemblyFoldersEx\My Assembly\

I tried creating a registry key with the .NET Framework version 4.6.1 and my .NET Standard assembly does show up in the Reference Manager for projects targeting .NET Framework 4.6.1 or newer, but it still does not show up in Reference Manager for UWP projects.  I have to manually browse to the assembly file.

Is there a way to have the .NET Standard 2.0 assembly automatically show in Reference Manager for UWP projects like I am able to do for the .NET Framework assembly?

答:
.NET Standard 2.0 assemblies should appear by default as long as your app has a minimum target of 1709 (build 16299 aka "RS3") or higher (source).

If your min-version is lower than that, you can only use .NET Standard 1.4 (source).


问:
php regex get div content
why my code not working

my php code

```<code>preg_match('@<div id="table-1"(.*?)></div>@si', $data, $table);
</code>```

the div that i want to get the content

```<code><div id="table-1" aria-labelledby="id-1" class="tabs-panel widget-content" role="tabpanel" aria-hidden="true" style="display: none;">
<!-- content -->
</div>
</code>```

答:
I also think it's a better idea to use DOMDocument unless the html code you have doesn't validate.

If you still want to use a expression to get the content in this case it could be done this way:

```<code>preg_match('@<div id="table-1".*?>([^<]*)</div>@si', $data, $matches);
</code>```

And the content will be on $matches[1].

You can see it working here http://sandbox.onlinephpfunctions.com/code/95f612d313e699add224efca4527417338c7b739

Title: php regex get div content

Body:
why my code not working

my php code

preg_match('@

@si', $data, $table);

the div that i want to get the content

Body:
I also think it's a better idea to use DOMDocument unless the html code you have doesn't validate.

If you still want to use a expression to get the content in this case it could be done this way:

preg_match('@<div id="table-1".*?>([^<]*)</div>@si', $data, $matches);

And the content will be on $matches[1].

You can see it working here http://sandbox.onlinephpfunctions.com/code/95f612d313e699add224efca4527417338c7b739


问:
Why does this.<variable> or this.<method()> in Parent Class have no effect? Java
I am wondering why this.(...) has no effect in this scenario. The following is a Task of my Exam:

```<code>class PARENT {
    public int x;
    public PARENT(int a)    {this.x = a;}

    public int getX()   {return this.x;}
    public int getY()   {return this.getX();}
}

class CHILD1 extends PARENT {
    public int x;
    public CHILD1(int b) {super(b); this.x = 2 * b;}
}

class CHILD2 extends PARENT {
    public CHILD2(int c)    {super(c);}

    public int getX()   {return 5;}
}

public class ThisTestMain {
    public static void main(String[] args)  {
        PARENT PP = new PARENT(10);
        PARENT PC1 = new CHILD1(100);
        PARENT PC2 = new CHILD2(1000);
        System.out.println(PP.getY());
        System.out.println(PC1.getY());
        System.out.println(PC2.getY());

        CHILD1 CC = new CHILD1(10);
        System.out.println(CC.getY());
    }
}
</code>```

The output is:

```<code>10
100
5
10
</code>```

My question now is why at System.out.println(PC1); the output is NOT 200. Because when I debug the code in IntelliJ I can see that this has the reference
CHILD1@799 and the Object can see the values x and PARENT.x.

At this point why is getX() choosing PARENT.x and not CHILD1.x?

By overriding methods this has also no effect. In this case for example System.out.println(PC2); uses always the getX() in CHILD2, no matter if you write in the getY() Method return this.getX(); or return getX();.

Can someone summerize the system behind that? Maybe also considering super? Thanks!

答:
In CHILD1 you have no overridden methods.

So when you call getY() it then calls getX() from the PARENT. The method from the PARENT has no idea about variables in its child classes.

You must override method getX() in CHILD1 to get access to the variable CHILD1.x.

Body:
I am wondering why this.(...) has no effect in this scenario. The following is a Task of my Exam:

class PARENT {
    public int x;
    public PARENT(int a)    {this.x = a;}

    public int getX()   {return this.x;}
    public int getY()   {return this.getX();}
}

class CHILD1 extends PARENT {
    public int x;
    public CHILD1(int b) {super(b); this.x = 2 * b;}
}

class CHILD2 extends PARENT {
    public CHILD2(int c)    {super(c);}

    public int getX()   {return 5;}
}

public class ThisTestMain {
    public static void main(String[] args)  {
        PARENT PP = new PARENT(10);
        PARENT PC1 = new CHILD1(100);
        PARENT PC2 = new CHILD2(1000);
        System.out.println(PP.getY());
        System.out.println(PC1.getY());
        System.out.println(PC2.getY());

        CHILD1 CC = new CHILD1(10);
        System.out.println(CC.getY());
    }
}

The output is:

10
100
5
10

My question now is why at System.out.println(PC1); the output is NOT 200. Because when I debug the code in IntelliJ I can see that this has the reference
CHILD1@799 and the Object can see the values x and PARENT.x.

At this point why is getX() choosing PARENT.x and not CHILD1.x?

By overriding methods this has also no effect. In this case for example System.out.println(PC2); uses always the getX() in CHILD2, no matter if you write in the getY() Method return this.getX(); or return getX();.

Can someone summerize the system behind that? Maybe also considering super? Thanks!


问:
Exact math with big numbers in Python 3
I'm trying to implement a system for encryption similar to Shamir's Secret Sharing using Python. Essentially, I have code that will generate a list of points that can be used to find a password at the y-intercept of the gradient formed by these points. The password is a number in ASCII (using two digits per ASCII character), thus is gets to be a pretty big number with larger passwords. For example, the password ThisIsAPassword will generate a list of points that looks like this:

```<code>x    y
9556 66707086867915126140753213946756441607861037300900
4083 28502040182447127964404994111341362715565457349000
9684 67600608880657662915204624898507424633297513499300
9197 64201036847801292531159022293017356403707170463200
</code>```

To be clear, these points are generated upon a randomly chosen slope (this is fine since it's the y-intercept that matters).

The problem arises in trying to make a program to decode a password. Using normal math, Python is unable to accurately find the password because of the size of the numbers. Here's the code I have:

```<code>def findYint(x,y):
    slope = (y[1] - y[0]) / (x[1] - x[0])
    yint = int(y[0] - slope * x[0])
    return yint

def asciiToString(num):
    chars = [num[i:i+3] for i in range(0, len(num), 3)]

    return ''.join(chr(int(i)) for i in chars)

def main():
    fi = open('pass.txt','r')
    x,y = [], []
    for i in fi:
        row = i.split()
        x.append(int(row[0]))
        y.append(int(row[1]))
    fi.close()
    yint = findYint(x,y)
    pword = asciiToString(str(yint))

    print(pword)

main()
</code>```

Output (with the password "ThisIsAPassword"):

```<code>͉)3 ǢΜĩũć»¢ǔ¼
</code>```

Typically my code will work with shorter passwords such as "pass" or "word", but the bigger numbers presumably aren't computed with the exact accuracy needed to convert them into ASCII. Any solutions for using either precise math or something else?

Also here's the code for generating points in case it's important:

```<code>import random

def encryptWord(word):
    numlist = []
    for i in range(len(word)):
        numlist.append(str(ord(word[i])).zfill(3))
    num = int("".join(numlist))
    return num

def createPoints(pwd, pts):
    yint = pwd
    gradient = pwd*random.randint(10,100)
    xvals = []
    yvals = []
    for i in range(pts):
        n = random.randint(1000,10000)
        xvals.append(n)
        yvals.append(((n) * gradient) + pwd)

    return xvals, yvals

def main():
    pword = input("Enter a password to encrypt: ")
    pword = encryptWord(pword)
    numpoints = int(input("How many points to generate? "))
    if numpoints < 2:
        numpoints = 2
    xpts, ypts = createPoints(pword, numpoints)

    fi = open("pass.txt","w")
    for i in range(len(xpts)):
        fi.write(str(xpts[i]))
        fi.write(' ')
        fi.write(str(ypts[i]))
        fi.write('\n')
    fi.close()
    print("Sent to file (pass.txt)")
main()
</code>```

答:
Fractions, and rewriting for all integer math are good.

For truly large integers, you may find yourself wanting https://pypi.org/project/gmpy/ instead of the builtin int type.  I've successfully used it for testing for large primes.

Or if you really do want numbers with a decimal point, maybe try decimal.Decimal("1") - just for example.

Title: Exact math with big numbers in Python 3

Body:
I'm trying to implement a system for encryption similar to Shamir's Secret Sharing using Python. Essentially, I have code that will generate a list of points that can be used to find a password at the y-intercept of the gradient formed by these points. The password is a number in ASCII (using two digits per ASCII character), thus is gets to be a pretty big number with larger passwords. For example, the password ThisIsAPassword will generate a list of points that looks like this:

x    y
9556 66707086867915126140753213946756441607861037300900
4083 28502040182447127964404994111341362715565457349000
9684 67600608880657662915204624898507424633297513499300
9197 64201036847801292531159022293017356403707170463200

To be clear, these points are generated upon a randomly chosen slope (this is fine since it's the y-intercept that matters).

The problem arises in trying to make a program to decode a password. Using normal math, Python is unable to accurately find the password because of the size of the numbers. Here's the code I have:

def findYint(x,y):
    slope = (y[1] - y[0]) / (x[1] - x[0])
    yint = int(y[0] - slope * x[0])
    return yint

def asciiToString(num):
    chars = [num[i:i+3] for i in range(0, len(num), 3)]

    return ''.join(chr(int(i)) for i in chars)

def main():
    fi = open('pass.txt','r')
    x,y = [], []
    for i in fi:
        row = i.split()
        x.append(int(row[0]))
        y.append(int(row[1]))
    fi.close()
    yint = findYint(x,y)
    pword = asciiToString(str(yint))

    print(pword)

main()

Output (with the password "ThisIsAPassword"):

͉)3 ǢΜĩũć»¢ǔ¼

Typically my code will work with shorter passwords such as "pass" or "word", but the bigger numbers presumably aren't computed with the exact accuracy needed to convert them into ASCII. Any solutions for using either precise math or something else?

Also here's the code for generating points in case it's important:

import random

def encryptWord(word):
    numlist = []
    for i in range(len(word)):
        numlist.append(str(ord(word[i])).zfill(3))
    num = int("".join(numlist))
    return num

def createPoints(pwd, pts):
    yint = pwd
    gradient = pwd*random.randint(10,100)
    xvals = []
    yvals = []
    for i in range(pts):
        n = random.randint(1000,10000)
        xvals.append(n)
        yvals.append(((n) * gradient) + pwd)

    return xvals, yvals

def main():
    pword = input("Enter a password to encrypt: ")
    pword = encryptWord(pword)
    numpoints = int(input("How many points to generate? "))
    if numpoints < 2:
        numpoints = 2
    xpts, ypts = createPoints(pword, numpoints)

    fi = open("pass.txt","w")
    for i in range(len(xpts)):
        fi.write(str(xpts[i]))
        fi.write(' ')
        fi.write(str(ypts[i]))
        fi.write('\n')
    fi.close()
    print("Sent to file (pass.txt)")
main()


问:
C++ Program skipping second fuction call
I have a problem in my C++, I call a first funtion (verif) which runs very well and then when I try to run an other one (dateIncrement), she just dont run and it skips to the next if, I saw it with the debugger, here is my code :

```<code>#include <iostream>
using namespace std;

bool verif(int day, int month, int year) {
    bool verifStatus;
    bool month31;
    bool month30;
    bool anneeBis;
    bool feb29;
    bool feb;
    month31 = ((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) && day > 0 && day < 32);
    month30 = ((month == 4 || month == 6 || month == 9 || month == 11) && day > 0 && day < 31);
    anneeBis = (year % 4 == 0 && year % 100 != 0);
    feb = (month == 2 && day > 0 && day < 29);
    feb29 = ((month == 2 && day == 29) && anneeBis);
    verifStatus = (month31 || month30 || feb || feb29);
    return verifStatus;
}

int dateIncrement(int day, int month, int year) {
    bool month31;
    bool month30;
    bool anneeBis;
    bool feb29;
    bool feb;
    bool dec;
    bool dec31;
    month31 = ((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10) && day > 0 && day < 32);
    month30 = ((month == 4 || month == 6 || month == 9 || month == 11) && day > 0 && day < 31);
    anneeBis = (year % 4 == 0 && year % 100 != 0);
    feb = (month == 2 && day > 0 && day < 29);
    feb29 = ((month == 2 && day == 29) && anneeBis);
    dec = (month == 12 && day > 0 && day < 31);
    dec31 = (month == 12 && day == 31);

    if (month31) {
        if (day == 31) {
            day = 1;
            month++;
        }

        if (day < 31) day++;
    }

    if (month30) {
        if (day == 30) {
            day = 1;
            month++;
        }

        if (day < 30) day += 1;
    }

    if(feb) day += 1;
    if (feb29) {
        day = 1;
        month++;
    }

    if (dec31) {
        day = 1;
        month = 1;
        year++;
    }
    if (dec) day++;
    return day, month, year;
}

int main()
{
    int day, month, year;

    do {
        day = 0;
        month = 0; // Mise et remise à 0 des variables à chaque essai
        year = 0;

        cout << "Entrez jour (666 pour quitter le programme) : " << endl;
        cin >> day;
        cout << "Entrez Mois :" << endl;
        cin >> month;
        cout << "Entrez ann\202e : " << endl;
        cin >> year;
        if (verif(day, month, year)) { // First function call works
            cout << "Le " << day << "/" << month << "/" << year << " est une date valide ! " << endl;
        }
        dateIncrement(day, month, year); // This is skipped
        if (verif(day, month, year)) { // It goes there without calling dateIncrement...
            cout << "Le " << day << "/" << month << "/" << year << " est aussi une date valide ! " << endl;
        }

        else {
            cout << "Le " << day << "/" << month << "/" << year << " n'est pas une date valide ! " << endl;
        }
    } while (day != 666);
    return 0;
}
</code>```

I also know that if I add a system("pause"); or a _getch(); between the first and second call, it works well, but I dont want the user to make anything after putting his date (and I also dont want to add batch in my C++).
I hope one of you can tell me why and how to solve it, thanks.

PS : I tried to say hello but this text editor wont :(

答:
The function dateIncrement is declared with the return type int

```<code>int dateIncrement(int day, int month, int year) {
</code>```

So it can return one scalar object of the type.

However in this return statement

```<code>return day, month, year;
</code>```

you are trying to return at once three objects.

Actually this return statement is equivalent to the following

```<code>return year;
</code>```

because there is used the comma operator and its value is the value of the last operand.

Moreover in main you are ignoring the returned value.

```<code>dateIncrement(day, month, year);
</code>```

What you need is to pass the arguments to the function by reference. It means that the function should be declared like

```<code>void dateIncrement(int &day, int &month, int &year) {
</code>```

As the function has the return type void then do not specify any expression in a return statement if such a statement will be present in the function.

Pay attention to that you are determining the leap year incorrectly

```<code>anneeBis = (year % 4 == 0 && year % 100 != 0);
</code>```

And in this statement

```<code>feb29 = ((month == 2 && day == 29) && anneeBis);
                ^^^         ^^^
</code>```

there are typos.

Body:
I have a problem in my C++, I call a first funtion (verif) which runs very well and then when I try to run an other one (dateIncrement), she just dont run and it skips to the next if, I saw it with the debugger, here is my code :

#include <iostream>
using namespace std;

bool verif(int day, int month, int year) {
    bool verifStatus;
    bool month31;
    bool month30;
    bool anneeBis;
    bool feb29;
    bool feb;
    month31 = ((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) && day > 0 && day < 32);
    month30 = ((month == 4 || month == 6 || month == 9 || month == 11) && day > 0 && day < 31);
    anneeBis = (year % 4 == 0 && year % 100 != 0);
    feb = (month == 2 && day > 0 && day < 29);
    feb29 = ((month == 2 && day == 29) && anneeBis);
    verifStatus = (month31 || month30 || feb || feb29);
    return verifStatus;
}

int dateIncrement(int day, int month, int year) {
    bool month31;
    bool month30;
    bool anneeBis;
    bool feb29;
    bool feb;
    bool dec;
    bool dec31;
    month31 = ((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10) && day > 0 && day < 32);
    month30 = ((month == 4 || month == 6 || month == 9 || month == 11) && day > 0 && day < 31);
    anneeBis = (year % 4 == 0 && year % 100 != 0);
    feb = (month == 2 && day > 0 && day < 29);
    feb29 = ((month == 2 && day == 29) && anneeBis);
    dec = (month == 12 && day > 0 && day < 31);
    dec31 = (month == 12 && day == 31);

    if (month31) {
        if (day == 31) {
            day = 1;
            month++;
        }

        if (day < 31) day++;
    }

    if (month30) {
        if (day == 30) {
            day = 1;
            month++;
        }

        if (day < 30) day += 1;
    }

    if(feb) day += 1;
    if (feb29) {
        day = 1;
        month++;
    }

    if (dec31) {
        day = 1;
        month = 1;
        year++;
    }
    if (dec) day++;
    return day, month, year;
}

int main()
{
    int day, month, year;

    do {
        day = 0;
        month = 0; // Mise et remise à 0 des variables à chaque essai
        year = 0;

        cout << "Entrez jour (666 pour quitter le programme) : " << endl;
        cin >> day;
        cout << "Entrez Mois :" << endl;
        cin >> month;
        cout << "Entrez ann\202e : " << endl;
        cin >> year;
        if (verif(day, month, year)) { // First function call works
            cout << "Le " << day << "/" << month << "/" << year << " est une date valide ! " << endl;
        }
        dateIncrement(day, month, year); // This is skipped
        if (verif(day, month, year)) { // It goes there without calling dateIncrement...
            cout << "Le " << day << "/" << month << "/" << year << " est aussi une date valide ! " << endl;
        }

        else {
            cout << "Le " << day << "/" << month << "/" << year << " n'est pas une date valide ! " << endl;
        }
    } while (day != 666);
    return 0;
}

I also know that if I add a system("pause"); or a _getch(); between the first and second call, it works well, but I dont want the user to make anything after putting his date (and I also dont want to add batch in my C++).
I hope one of you can tell me why and how to solve it, thanks.

PS : I tried to say hello but this text editor wont :(

Body:
The function dateIncrement is declared with the return type int

int dateIncrement(int day, int month, int year) {

So it can return one scalar object of the type.

However in this return statement

return day, month, year;

you are trying to return at once three objects.

Actually this return statement is equivalent to the following

return year;

because there is used the comma operator and its value is the value of the last operand.

Moreover in main you are ignoring the returned value.

dateIncrement(day, month, year);

What you need is to pass the arguments to the function by reference. It means that the function should be declared like

void dateIncrement(int &day, int &month, int &year) {

As the function has the return type void then do not specify any expression in a return statement if such a statement will be present in the function.

Pay attention to that you are determining the leap year incorrectly

anneeBis = (year % 4 == 0 && year % 100 != 0);

And in this statement

feb29 = ((month == 2 && day == 29) && anneeBis);
                ^^^         ^^^

there are typos.


问:
IndexError: index 1 is out of bounds for axis 0 with size 1, with range(n-1) already
I'm trying to find the trapezoidal integration of a bunch of data but it keeps saying

```<code>File "D:/uni work/Sci programming/aps3.py", line 25, in trapz
x2 = x[i+1]

IndexError: index 1 is out of bounds for axis 0 with size 1'
</code>```

I changed range(n) to range(n-1) but I still get the same error.

```<code>import numpy as np
solarfile = open('solar.dat','r',)
x1=[]#wavelength
y1=[]#irradiance
for theline in solarfile:
    num = theline.split()
    x1.append(float(num[0]))
    y1.append(float(num[1]))
x=np.array([x1])
y=np.array([y1])

a = int(input("Please Enter the lower bound: "))
b = int(input("Please enter the upper bound: "))
if (a<np.argmin(x)):
    a =np.argmin(x)
if (b>np.argmax(x)):
    b =np.argmax(x)
n = b - a
def trapz(x,y,a,b):
    traparray=[]
    for i in range(n-1):

        x1 = x[i]
        x2 = x[i+1]
        dx = x2-x1
        y1 = y[i]
        y2 = y[i+1]
        dy = y2-y1
        trap = ((y1*dx)+(0.5*(dy*dx)))
        d = traparray.append(trap)
return (s)
print (trapz(x,y,a,b))
solarfile.close()
</code>```

I keep trying things but they don't work.

答:
You're getting the index error since you're accessing an element in an array which doesn't exist.

Your n value is not defined, or it is also possible that it is using a global value of n, which is greater than the length of the array x.

Change your line on 25 to as below so that it only executes to the length of the array.

for i in range(len(x)-1)

Body:
I'm trying to find the trapezoidal integration of a bunch of data but it keeps saying

File "D:/uni work/Sci programming/aps3.py", line 25, in trapz
x2 = x[i+1]

IndexError: index 1 is out of bounds for axis 0 with size 1'

I changed range(n) to range(n-1) but I still get the same error.

import numpy as np
solarfile = open('solar.dat','r',)
x1=[]#wavelength
y1=[]#irradiance
for theline in solarfile:
    num = theline.split()
    x1.append(float(num[0]))
    y1.append(float(num[1]))
x=np.array([x1])
y=np.array([y1])

a = int(input("Please Enter the lower bound: "))
b = int(input("Please enter the upper bound: "))
if (a<np.argmin(x)):
    a =np.argmin(x)
if (b>np.argmax(x)):
    b =np.argmax(x)
n = b - a
def trapz(x,y,a,b):
    traparray=[]
    for i in range(n-1):

        x1 = x[i]
        x2 = x[i+1]
        dx = x2-x1
        y1 = y[i]
        y2 = y[i+1]
        dy = y2-y1
        trap = ((y1*dx)+(0.5*(dy*dx)))
        d = traparray.append(trap)
return (s)
print (trapz(x,y,a,b))
solarfile.close()

I keep trying things but they don't work.


问:
How to search a nested dictionary and not care about top level key
So I am using lunr.js in my Jekyll application to implement a search feature and the results return correctly. The aim is to then display the list of results in the browser.

Here I get the results, then pass them to a func which handles the DOM manipulation.

var results = idx.search(searchTerm); // Get lunr to perform a search
displaySearchResults(results, window.store);
```

<p>The log of <code>console.log(window.store);</code> is the following:</p>

<pre class="lang-js prettyprint-override"><code>"python-2019-03-23-welcome-to-jekyll-html": Object { title: "test", category: "Python", url: "/python/2019/03/23/welcome-to-jekyll.html" }
</code>```

The first key python-2019-03-23-welcome-to-jekyll-html doesn't matter as that will change depending on the number of posts. How can I get the values of Object{}?

Any advice would be appreciated. I'm fairly new to JS, so if this is badly worded, let me know.

答:
You can use Object.values() to access only the values of the object. Example:

```<code>const myObj = {a: 1, b: 2}
Object.values(myObj)  // => [1, 2]
</code>```

Body:
So I am using lunr.js in my Jekyll application to implement a search feature and the results return correctly. The aim is to then display the list of results in the browser.

Here I get the results, then pass them to a func which handles the DOM manipulation.

var results = idx.search(searchTerm); // Get lunr to perform a search
displaySearchResults(results, window.store);

The log of console.log(window.store); is the following:

"python-2019-03-23-welcome-to-jekyll-html": Object { title: "test", category: "Python", url: "/python/2019/03/23/welcome-to-jekyll.html" }

The first key python-2019-03-23-welcome-to-jekyll-html doesn't matter as that will change depending on the number of posts. How can I get the values of Object{}?

Any advice would be appreciated. I'm fairly new to JS, so if this is badly worded, let me know.

Body:
You can use Object.values() to access only the values of the object. Example:

const myObj = {a: 1, b: 2}
Object.values(myObj)  // => [1, 2]


问:
Set Request Method for PHP Rest Api
I'm building rest APIs in Php and I want to set a request method for each Api from the .htaccess. Since in Php rest Api can accessed whatever the request method is. I used this method

```<code>RewriteCond %{REQUEST_METHOD} GET
RewriteRule /?user/list api/user/list.php [NC,L]
</code>```

but it didn't work it still can be accessed when I send a post request.

答:
Try disabling MultiViews. If MultiViews is enabled then it will completely bypass the mod_rewrite directives and issue an internal subrequest for list.php regardless of the request method.

Your RewriteRule pattern is also also too general - it looks like it would generate a rewrite loop?!

.htaccess is located in the root project.

By that, I assume you mean it's in the directory where /api is a subdirectory?

In which case try the following:

```<code>Options -MultiViews

RewriteEngine On

RewriteCond %{REQUEST_METHOD} =GET
RewriteRule ^api/user/list$ api/user/list.php [L]
</code>```

The = in =GET makes it an exact match string comparison.

You shouldn't need the NC flag, unless you specifically need to allow mixed case requests?

Title: Set Request Method for PHP Rest Api

Body:
I'm building rest APIs in Php and I want to set a request method for each Api from the .htaccess. Since in Php rest Api can accessed whatever the request method is. I used this method

RewriteCond %{REQUEST_METHOD} GET
RewriteRule /?user/list api/user/list.php [NC,L]

but it didn't work it still can be accessed when I send a post request.

Body:
Try disabling MultiViews. If MultiViews is enabled then it will completely bypass the mod_rewrite directives and issue an internal subrequest for list.php regardless of the request method.

Your RewriteRule pattern is also also too general - it looks like it would generate a rewrite loop?!

.htaccess is located in the root project.

By that, I assume you mean it's in the directory where /api is a subdirectory?

In which case try the following:

Options -MultiViews

RewriteEngine On

RewriteCond %{REQUEST_METHOD} =GET
RewriteRule ^api/user/list$ api/user/list.php [L]

The = in =GET makes it an exact match string comparison.

You shouldn't need the NC flag, unless you specifically need to allow mixed case requests?


问:
Nvcc missing when installing cudatoolkit?
I have installed cuda along pytorch with

```<code>conda install pytorch torchvision cudatoolkit=10.0 -c pytorch
</code>```

However, it seems like nvcc was not installed along with it. If I want to use for example nvcc -V, I get the error that nvcc was not found, and that I should install it with sudo apt install nvidia-cuda-toolkit.
Can I do this (I dont want to just try and then find out that it is not working/messes up the whole cuda setup).
And is this a bug or expected behavior?

I am using Ubuntu 18.04 and have cuda 10.2

答:
You can try

```<code>conda install -c conda-forge nvcc_linux-64
</code>```

Currently this should get you 10.2. Nvidia has its own channel nvidia but the latest version there is 10.1.

Body:
I have installed cuda along pytorch with

conda install pytorch torchvision cudatoolkit=10.0 -c pytorch

However, it seems like nvcc was not installed along with it. If I want to use for example nvcc -V, I get the error that nvcc was not found, and that I should install it with sudo apt install nvidia-cuda-toolkit.
Can I do this (I dont want to just try and then find out that it is not working/messes up the whole cuda setup).
And is this a bug or expected behavior?

I am using Ubuntu 18.04 and have cuda 10.2

Body:
You can try

conda install -c conda-forge nvcc_linux-64

Currently this should get you 10.2. Nvidia has its own channel nvidia but the latest version there is 10.1.


问:
How to update GTK3 image using a button to capture a picture from the camera using C++
I posted this on the Pi forum but the only answer I received is that I posted it in the wrong place.

Posting on Pi forum

I managed to create a program that will display some buttons and an Image. Now I would like to update the image when a button is clicked. How do I do that?

Here is what I have so far, it all works but missing code to update the displayed image.  The 3 second delay before camrea.grab is missing from this code but has been add to the code that I am using.

```<code>#include <iostream>
#include <raspicam/raspicam.h>
#include <wiringPi.h>
#include <gtk/gtk.h>

#include <fstream>
#include <vector>
#include <unistd.h>

using namespace std;

void Capture_Image(void){
    //camera setup
    raspicam::RaspiCam camera; //Camera object

    if (!camera.open())
    {
        cerr << "Could not open the camera" << endl;
        //return 1;
    }

    camera.grab();

    std::vector<unsigned char> buf;
    buf.resize(camera.getImageTypeSize(raspicam::RASPICAM_FORMAT_RGB));

    camera.retrieve(buf.data(), raspicam::RASPICAM_FORMAT_RGB);

    std::ofstream outFile("/home/pi/s.jpg", std::ios::binary);
    outFile << "P6\n" << camera.getWidth() << " " << camera.getHeight() << " 255\n";
    outFile.write((char*)buf.data(), buf.size());

    cout << "Image saved to output.ppm" << endl;
}

int main(int argc, char **argv)
{
    wiringPiSetup();
    gtk_init (&argc, &argv);

    //Main Box
    GtkWidget *mainBox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 5);
    gtk_container_add (GTK_CONTAINER (win), mainBox);

    //camera image container
    GtkWidget *cameraBox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 5);
    gtk_container_add (GTK_CONTAINER (mainBox), cameraBox);

    GtkWidget *cameraView = gtk_image_new_from_file("/home/pi/s.jpg");
    gtk_box_pack_start (GTK_BOX (cameraBox), cameraView, TRUE, TRUE, 0);

    //resize image
    GdkPixbuf *pixBuf = gtk_image_get_pixbuf(GTK_IMAGE(cameraView));
    pixBuf = gdk_pixbuf_scale_simple(pixBuf, 300,200,GDK_INTERP_BILINEAR);
    gtk_image_set_from_pixbuf(GTK_IMAGE(cameraView),pixBuf);

    //image capture button
    GtkWidget *imageCapture = gtk_button_new_with_label ("Image Capture");
    g_signal_connect (imageCapture, "clicked", G_CALLBACK (Capture_Image), NULL);
    gtk_box_pack_start (GTK_BOX (cameraBox), imageCapture, TRUE, TRUE, 0);

    //show the new window
    gtk_widget_show_all (win);
    //Start the GTK main loop
    gtk_main ();

    return 0;
}
</code>```

答:
I did a lot of research and found the solution.

I updated my function like this

```<code>void Capture_Image(GtkWidget *widget, gpointer image){
</code>```

And added this code in my function after the image was saved.

```<code>GtkWidget *cameraView = (GtkWidget *) image;
gtk_image_set_from_file(GTK_IMAGE(cameraView),"/home/pi/s.jpg");
//resize image
GdkPixbuf *pixBufUpdate = gtk_image_get_pixbuf(GTK_IMAGE(cameraView));
pixBufUpdate = gdk_pixbuf_scale_simple(pixBufUpdate, 320,240,GDK_INTERP_BILINEAR);
gtk_image_set_from_pixbuf(GTK_IMAGE(cameraView),pixBufUpdate);
</code>```

When I call with the button I used this

```<code>g_signal_connect (imageCapture, "clicked", G_CALLBACK (Capture_Image), cameraView);
</code>```

Body:
I posted this on the Pi forum but the only answer I received is that I posted it in the wrong place.

Posting on Pi forum

I managed to create a program that will display some buttons and an Image. Now I would like to update the image when a button is clicked. How do I do that?

Here is what I have so far, it all works but missing code to update the displayed image.  The 3 second delay before camrea.grab is missing from this code but has been add to the code that I am using.

#include <iostream>
#include <raspicam/raspicam.h>
#include <wiringPi.h>
#include <gtk/gtk.h>

#include <fstream>
#include <vector>
#include <unistd.h>

using namespace std;

void Capture_Image(void){
    //camera setup
    raspicam::RaspiCam camera; //Camera object

    if (!camera.open())
    {
        cerr << "Could not open the camera" << endl;
        //return 1;
    }

    camera.grab();

    std::vector<unsigned char> buf;
    buf.resize(camera.getImageTypeSize(raspicam::RASPICAM_FORMAT_RGB));

    camera.retrieve(buf.data(), raspicam::RASPICAM_FORMAT_RGB);

    std::ofstream outFile("/home/pi/s.jpg", std::ios::binary);
    outFile << "P6\n" << camera.getWidth() << " " << camera.getHeight() << " 255\n";
    outFile.write((char*)buf.data(), buf.size());

    cout << "Image saved to output.ppm" << endl;
}

int main(int argc, char **argv)
{
    wiringPiSetup();
    gtk_init (&argc, &argv);

    //Main Box
    GtkWidget *mainBox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 5);
    gtk_container_add (GTK_CONTAINER (win), mainBox);

    //camera image container
    GtkWidget *cameraBox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 5);
    gtk_container_add (GTK_CONTAINER (mainBox), cameraBox);

    GtkWidget *cameraView = gtk_image_new_from_file("/home/pi/s.jpg");
    gtk_box_pack_start (GTK_BOX (cameraBox), cameraView, TRUE, TRUE, 0);

    //resize image
    GdkPixbuf *pixBuf = gtk_image_get_pixbuf(GTK_IMAGE(cameraView));
    pixBuf = gdk_pixbuf_scale_simple(pixBuf, 300,200,GDK_INTERP_BILINEAR);
    gtk_image_set_from_pixbuf(GTK_IMAGE(cameraView),pixBuf);

    //image capture button
    GtkWidget *imageCapture = gtk_button_new_with_label ("Image Capture");
    g_signal_connect (imageCapture, "clicked", G_CALLBACK (Capture_Image), NULL);
    gtk_box_pack_start (GTK_BOX (cameraBox), imageCapture, TRUE, TRUE, 0);

    //show the new window
    gtk_widget_show_all (win);
    //Start the GTK main loop
    gtk_main ();

    return 0;
}

Body:
I did a lot of research and found the solution.

I updated my function like this

void Capture_Image(GtkWidget *widget, gpointer image){

And added this code in my function after the image was saved.

GtkWidget *cameraView = (GtkWidget *) image;
gtk_image_set_from_file(GTK_IMAGE(cameraView),"/home/pi/s.jpg");
//resize image
GdkPixbuf *pixBufUpdate = gtk_image_get_pixbuf(GTK_IMAGE(cameraView));
pixBufUpdate = gdk_pixbuf_scale_simple(pixBufUpdate, 320,240,GDK_INTERP_BILINEAR);
gtk_image_set_from_pixbuf(GTK_IMAGE(cameraView),pixBufUpdate);

When I call with the button I used this

g_signal_connect (imageCapture, "clicked", G_CALLBACK (Capture_Image), cameraView);


问:
Cloudmade API Turn by Turn - can custom voiced be used?
Anyone with experience using the Cloudmade api for iphone apps? I'm being asked if it's feasible to incorporate custom voices for the turn by turn navigation it offers.

Any advice appreciated!

答:
Basically, you can get the turn-by-turn routing as an XML (see documentation) and feed the instructions to the Text-to-Speech engine (I'm afraid there's nothing out-of-the-box for iPhone, so I'd suggest you give a try to Flite or a similar).

I'm not sure Cloudmade SDK does anything different than that, also incorporating some TTS engine in their SDK. For sure, this is exactly what I did for an Android application myself for turn-by-turn routing.


问:
List the history of branches checked out
git reflog |grep 'checkout: moving'|cut -d\  -f 8 shows me what I am after but I always heard using plumbing for scripting is better than parsing the output of  porcelain commands. What would be the plumbing equivalent here?

答:
You could skip reflog's formatting entirely, just

```<code>cut -f2- .git/logs/HEAD | awk '$1=="checkout:" { print $NF }'
</code>```

but I think nobody's bothered making officially-scriptable interfaces for the reflog, branch names are local, arbitrary and ephemeral already, the reflogs for what's been checked out even more so.

Body:
You could skip reflog's formatting entirely, just

cut -f2- .git/logs/HEAD | awk '$1=="checkout:" { print $NF }'

but I think nobody's bothered making officially-scriptable interfaces for the reflog, branch names are local, arbitrary and ephemeral already, the reflogs for what's been checked out even more so.


问:
Grouping input array by 2 values in order to create stacked bar using amchart
I'm preparing data for dataProvider using amchart to create stacked Column chart in JS like this https://www.amcharts.com/demos-v3/stacked-column-chart-v3/ but using only 2 values (plan and actual) in staked columns, i have the response of my service as its shown below, and i would like grouping data so i have to change input array:

```<code>inputArr = [{Value: 10},
            {Value: 25},
            {Value: 30},
            {Value: 37}
            {Value: 43}];
</code>```

by this

```<code>newArr = [{Value1: 10, Value2: 25},
          {Value1: 30, Value2: 37},
          {Value1: 43, Value2: 0}];
</code>```

if there are odd numbers of elements in array so make Value2 is 0 when transforming.

答:
You could create a function to make this conversion:

let inputArr = [{Value: 10},
            {Value: 25},
            {Value: 30},
            {Value: 37},
            {Value: 43}];

function pairValues(ary)
{
  let newAry = [];
  let obj;

  // Loop the inputted array and pair values
  ary.forEach((subObj)=>
  {
    if(obj)
    {
      obj.Value2 = subObj.Value;
      newAry.push(obj);
      obj = undefined;
    }
    else
    {
      obj = {};
      obj.Value1 = subObj.Value;
    }
  });

  // If the last obj has no pair, set Value2 to zero
  if (obj)
  {
    obj.Value2 = 0;
    newAry.push(obj);
  }
  return newAry;
}
let outputArr = pairValues(inputArr);
console.log(outputArr);```

Body:
I'm preparing data for dataProvider using amchart to create stacked Column chart in JS like this https://www.amcharts.com/demos-v3/stacked-column-chart-v3/ but using only 2 values (plan and actual) in staked columns, i have the response of my service as its shown below, and i would like grouping data so i have to change input array:

inputArr = [{Value: 10},
            {Value: 25},
            {Value: 30},
            {Value: 37}
            {Value: 43}];

by this

newArr = [{Value1: 10, Value2: 25},
          {Value1: 30, Value2: 37},
          {Value1: 43, Value2: 0}];

if there are odd numbers of elements in array so make Value2 is 0 when transforming.


问:
CSS: How to center the snackbar horizontally?
I am using a simple snackbar code from w3schools (https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_snackbar). It works OK but for long message it starts to move off the horizontal center, for example.

```<code><div id="snackbar">Some very very very very very very long text some message..</div>
</code>```

I try to fix it by removing "margin-left" and also "left", and only setting "margin: 0 auto" but it doesn't work.

答:
Remove margin-left: -125px;
and add: transform: translateX(-50%);
from #snackbar selector.

Body:
I am using a simple snackbar code from w3schools (https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_snackbar). It works OK but for long message it starts to move off the horizontal center, for example.

Some very very very very very very long text some message..

I try to fix it by removing "margin-left" and also "left", and only setting "margin: 0 auto" but it doesn't work.


问:
Transfer Twilio voice Autobot to a telephone number
I'm a Twilio newbie so please be gentle.

I'm creating an Autopilot bot to be used via Alexa that in in some circumstances needs to transfer the voice to a telephone number. I'm using my mobile as the destination for testing. I have written a Function to transfer the call which then calls my mobile. All good so far, but as soon as the call is made the Twilio session ends - the call is received and I hear on my mobile "I'm sorry an application error has occurred". I'm guessing I'm missing parameter to connect the voice session to the call. Where have I gone wrong?

Thanks in advance.

Task:

```<code>{
    "actions": [
        {
            "say": "Connecting you"
        },
        {
            "handoff": {
                "method": "POST",
                "channel": "voice",
                "uri": "https://qwerty.twil.io/call-me"
            }
        }
    ]
}
</code>```

Function code:

```<code>exports.handler = function(context, event, callback) {
  // Get an initialized Twilio API client
  const client = context.getTwilioClient();

  // Make a new phone call, using our first function
  // to provide the TwiML for the call
  client.calls.create({
    url: 'https://' + context.DOMAIN_NAME + '/voice',
        to: '+44MyMobileNumber',
        from: '+44MyTwilioNumber'
  }, function(err, result) {
    console.log('New phone call started...');
    console.log(result);

    // End our function
    callback();
  });
};
</code>```

答: The answer was to Handoff the call in Autopilot to a Twiml Bin that makes the call.</p>

Body:
I'm a Twilio newbie so please be gentle.

I'm creating an Autopilot bot to be used via Alexa that in in some circumstances needs to transfer the voice to a telephone number. I'm using my mobile as the destination for testing. I have written a Function to transfer the call which then calls my mobile. All good so far, but as soon as the call is made the Twilio session ends - the call is received and I hear on my mobile "I'm sorry an application error has occurred". I'm guessing I'm missing parameter to connect the voice session to the call. Where have I gone wrong?

Thanks in advance.

Task:

{
    "actions": [
        {
            "say": "Connecting you"
        },
        {
            "handoff": {
                "method": "POST",
                "channel": "voice",
                "uri": "https://qwerty.twil.io/call-me"
            }
        }
    ]
}

Function code:

exports.handler = function(context, event, callback) {
  // Get an initialized Twilio API client
  const client = context.getTwilioClient();

  // Make a new phone call, using our first function
  // to provide the TwiML for the call
  client.calls.create({
    url: 'https://' + context.DOMAIN_NAME + '/voice',
        to: '+44MyMobileNumber',
        from: '+44MyTwilioNumber'
  }, function(err, result) {
    console.log('New phone call started...');
    console.log(result);

    // End our function
    callback();
  });
};


问:
Building an executable using pyinstaller, with windows default executable icon
I just need to build an executable using pyinstaller, with the default windows .exe icon.
Or a way to remove/set default windows icon after compiling.

Thank you.

答:
I don't think you can just use windows default .exe icon, but you can set your own.

Use pyinstaller --onefile --icon=myicon.ico yourapp.py for the command, and have myicon.ico in that directory or specify which directory.


Title: Daily Inventory from Bought/Sold transaction log

Body:
The following SQL queries describe two tables and their contents, a small and simplified part of a big inventory system.

The first is a transaction log listing bought and sold quantities of various items.

CREATE TABLE `Inventar_actions` (
  `PartID` char(8) NOT NULL,
  `DateSeq` smallint(4) unsigned NOT NULL,
  `ActionType` enum('Bought','Sold') NOT NULL,
  `Units` bigint(20) unsigned NOT NULL,
  PRIMARY KEY (`PartID`,`DateSeq`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `test`.`Inventar_actions` (`PartID`, `DateSeq`, `ActionType`, `Units`) VALUES
('0001', '1020', 'Bought', '100'),('0001', '1025', 'Sold', '20'),('0001', '1028', 'Sold', '30'),
('0001', '1031', 'Bought', '100'),('0001', '1035', 'Sold', '50');

The second table is a calendar, listing business days and their sequential numbers from an arbitrary epoch:

CREATE TABLE `BusinessDates` (
  `DateSeq` int(10) unsigned NOT NULL,
  `BusinessDate` date NOT NULL,
  PRIMARY KEY (`DateSeq`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `test`.`BusinessDates` (`DateSeq`, `BusinessDate`) VALUES
('1015', '2020-02-03'),('1016', '2020-02-04'),('1017', '2020-02-05'),('1018', '2020-02-06'),('1019', '2020-02-07'),
('1020', '2020-02-10'),('1021', '2020-02-11'),('1022', '2020-02-12'),('1023', '2020-02-13'),('1024', '2020-02-14'),
('1025', '2020-02-17'),('1026', '2020-02-18'),('1027', '2020-02-19'),('1028', '2020-02-20'),('1029', '2020-02-21'),
('1030', '2020-02-24'),('1031', '2020-02-25'),('1032', '2020-02-26'),('1033', '2020-02-27'),('1034', '2020-02-28'),
('1035', '2020-03-02'),('1036', '2020-03-03'),('1037', '2020-03-04'),('1038', '2020-03-05'),('1039', '2020-03-06')
;

What I need is a daily inventory, one that looks something like this:

| 1020 | 2020-02-10 | 100 | Bought | 100 |
| 1021 | 2020-02-11 |     |        | 100 |
| 1022 | 2020-02-12 |     |        | 100 |
| 1023 | 2020-02-13 |     |        | 100 |
| 1024 | 2020-02-14 |     |        | 100 |
| 1025 | 2020-02-17 |  20 | Sold   |  80 |
| 1026 | 2020-02-18 |     |        |  80 |
| 1027 | 2020-02-19 |     |        |  80 |
| 1028 | 2020-02-20 |  30 | Sold   |  50 |
| 1029 | 2020-02-21 |     |        |  50 |
| 1030 | 2020-02-24 |     |        |  50 |
| 1031 | 2020-02-25 | 100 | Bought | 150 |
| 1032 | 2020-02-26 |     |        | 150 |
| 1033 | 2020-02-27 |     |        | 150 |
| 1034 | 2020-02-28 |     |        | 150 |
| 1035 | 2020-03-02 |  50 | Sold   | 100 |
| 1036 | 2020-03-03 |     |        | 100 |
| 1037 | 2020-03-04 |     |        | 100 |
| 1038 | 2020-03-05 |     |        | 100 |
| 1039 | 2020-03-06 |     |        | 100 |

That is, for each business date what is the balance of each PartID, given parts bought and sold.

I used the following query to line up dates, date-sequence and transactions:

SELECT d.DateSeq, d.BusinessDate, a.`Units`, a.`ActionType`
FROM `BusinessDates` AS d LEFT JOIN
(SELECT DateSeq, ActionType, Units FROM `Inventar_actions` WHERE PartID = '0001') AS a USING (DateSeq)
WHERE d.DateSeq BETWEEN 1020 AND 1039
ORDER BY d.DateSeq;

This produces the first four columns of the desired output.

Unfortunately, I couldn't find a query that will also produce the last column, the balance inventory of parts.

Please note that there are a lot of PartID's and thousands of business days.

Please help...

Body:
This works with mysql 5.x and 8.0

CREATE TABLE `Inventar_actions` (
  `PartID` char(8) NOT NULL,
  `DateSeq` smallint(4) unsigned NOT NULL,
  `ActionType` enum('Bought','Sold') NOT NULL,
  `Units` bigint(20) unsigned NOT NULL,
  PRIMARY KEY (`PartID`,`DateSeq`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `Inventar_actions` (`PartID`, `DateSeq`, `ActionType`, `Units`) VALUES
('0001', '1020', 'Bought', '100'),('0001', '1025', 'Sold', '20'),('0001', '1028', 'Sold', '30'),
('0001', '1031', 'Bought', '100'),('0001', '1035', 'Sold', '50');

✓

✓

CREATE TABLE `BusinessDates` (
  `DateSeq` int(10) unsigned NOT NULL,
  `BusinessDate` date NOT NULL,
  PRIMARY KEY (`DateSeq`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `BusinessDates` (`DateSeq`, `BusinessDate`) VALUES
('1015', '2020-02-03'),('1016', '2020-02-04'),('1017', '2020-02-05'),('1018', '2020-02-06'),('1019', '2020-02-07'),
('1020', '2020-02-10'),('1021', '2020-02-11'),('1022', '2020-02-12'),('1023', '2020-02-13'),('1024', '2020-02-14'),
('1025', '2020-02-17'),('1026', '2020-02-18'),('1027', '2020-02-19'),('1028', '2020-02-20'),('1029', '2020-02-21'),
('1030', '2020-02-24'),('1031', '2020-02-25'),('1032', '2020-02-26'),('1033', '2020-02-27'),('1034', '2020-02-28'),
('1035', '2020-03-02'),('1036', '2020-03-03'),('1037', '2020-03-04'),('1038', '2020-03-05'),('1039', '2020-03-06')
;

✓

✓

SELECT
   d.DateSeq
   , d.BusinessDate
   , a.`Units`
   , a.`ActionType`
      ,
   CASE
     WHEN a.`ActionType` = 'Bought' THEN @inventory := @inventory + a.`Units`
   WHEN a.`ActionType` = 'Sold' THEN @inventory := @inventory - a.`Units`
   ELSE
    @inventory := @inventory
   END inventory
FROM (SELECT * FROM `BusinessDates` ORDER BY  BusinessDate ASC) AS d LEFT JOIN
(SELECT DateSeq, ActionType, Units FROM `Inventar_actions` WHERE PartID = '0001') AS a USING (DateSeq)
,(SELECT @inventory := 0) b
WHERE d.DateSeq BETWEEN 1020 AND 1039
ORDER BY d.DateSeq;

DateSeq | BusinessDate | Units | ActionType | inventory
------: | :----------- | ----: | :--------- | :--------
   1020 | 2020-02-10   |   100 | Bought     | 100
   1021 | 2020-02-11   |  null | null       | 100
   1022 | 2020-02-12   |  null | null       | 100
   1023 | 2020-02-13   |  null | null       | 100
   1024 | 2020-02-14   |  null | null       | 100
   1025 | 2020-02-17   |    20 | Sold       | 80
   1026 | 2020-02-18   |  null | null       | 80
   1027 | 2020-02-19   |  null | null       | 80
   1028 | 2020-02-20   |    30 | Sold       | 50
   1029 | 2020-02-21   |  null | null       | 50
   1030 | 2020-02-24   |  null | null       | 50
   1031 | 2020-02-25   |   100 | Bought     | 150
   1032 | 2020-02-26   |  null | null       | 150
   1033 | 2020-02-27   |  null | null       | 150
   1034 | 2020-02-28   |  null | null       | 150
   1035 | 2020-03-02   |    50 | Sold       | 100
   1036 | 2020-03-03   |  null | null       | 100
   1037 | 2020-03-04   |  null | null       | 100
   1038 | 2020-03-05   |  null | null       | 100
   1039 | 2020-03-06   |  null | null       | 100

db<>fiddle here


问:
Break lines in blade translation files
In my view I have

```<code><p>{{ trans('mission-vision-page.mission-description') }}</p>
</code>```

I've put a block of text in my language file, but I want to maintain the new lines. I've tried:

1.

```<code>return ['mission-description' => 'line 1 <br /> line 2']
</code>```

2.

```<code>return ['mission-description' => 'line 1 \n line 2']
</code>```

3.

```<code>$newLine = '<br />';
return ['mission-description' => 'line 1 ' . $newLine . ' line 2']
</code>```

I know probably there's a better way to accomplish this, but in my en.php file can I add new lines?

答:
Add custom blade directive, in App\Providers\AppServiceProvider.php add:

\Blade::directive('lang2br', function ($expression) {
   return "<?php echo nl2br(app('translator')->getFromJson({$expression})); ?>";
});
```

<p>Then you can use like <code>lang</code> directive:</p>

```@lang2br('something');
```

Title: Break lines in blade translation files

Body:
In my view I have

{{ trans('mission-vision-page.mission-description') }}

I've put a block of text in my language file, but I want to maintain the new lines. I've tried:

1.

return ['mission-description' => 'line 1
 line 2']

2.

return ['mission-description' => 'line 1 \n line 2']

3.

$newLine = '
';
return ['mission-description' => 'line 1 ' . $newLine . ' line 2']

I know probably there's a better way to accomplish this, but in my en.php file can I add new lines?

Body:
Add custom blade directive, in App\Providers\AppServiceProvider.php add:

\Blade::directive('lang2br', function ($expression) {
   return "<?php echo nl2br(app('translator')->getFromJson({$expression})); ?>";
});

Then you can use like lang directive:

@lang2br('something');


问:
Querying Temporal Tables
Is there a way to query temporal tables, so that I can view how the tables changed by day?

I have not worked with temporal tables before, so what I'm doing now is using the for system_time in a bunch of queries by date. I know there has to be a better way.

答:
In the documentation, they refer to columns called ValidFrom and ValidTo (they can be called anything you want, but I'll be using those names in this discussion). On insert, data is inserted into the live table with a ValidFrom of "now" and a ValidTo of some high date (9999-12-31 iirc). For updates, the record in the live table has itsValidFromupdated to "now" but there's also a record inserted into the history table with aValidFromof the previous value and aValidTo` of "now". On deletes, the record from the live table is deleted but the insert into the history table happens as described in the update scenario.

For the inserts, you'll want to query your table with a predicate of where ValidFrom >= '2020-02-14' and ValidFrom < '2020-02-15' and no row exists in the history table (a left join by PK will work here).

For the updates, you'll want to query the history table with a predicate of where ValidTo >= '2020-02-14' and ValidTo < '2020-02-15' and a corresponding record exists in the history table (an inner join by PK will work here)

For any deletes, you'll want to query the history table with a predicate of where ValidTo >= '2020-02-14' and ValidTo < '2020-02-15' and no row exists in the live table (a left join by PK will work here).

Title: Querying Temporal Tables


问:
Polly's CircuitBreakerAsync does not retry if exception occur
I am using Polly library for transient fault handling. For synchronous operations Polly circuit breaker policy works fine but when I created its async version it does not retries the execution. Kindly suggest :

Asynchronous method:

```<code>private async static Task HelloWorld()
    {
        if (DateTime.Now < programStartTime.AddSeconds(10))
        {
            Console.WriteLine("Task Failed.");
            throw new TimeoutException();
        }
        await Task.Delay(TimeSpan.FromSeconds(1));
        Console.WriteLine("Task Completed.");
    }
</code>```

Polly circuit breaker async policy:

```<code>private static void AsyncDemo3(Func<Task> action)
    {
        programStartTime = DateTime.Now;

        AsyncPolicy policy = Policy
            .Handle<TimeoutException>()
            .CircuitBreakerAsync(3, TimeSpan.FromSeconds(2));
        try
        {
            var a = policy.ExecuteAndCaptureAsync(action, true).GetAwaiter().GetResult();
        }
        catch (AggregateException ex)
        {
            Console.WriteLine("Exception: " + ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception: " + ex.Message);
        }
    }
</code>```

Executing the Polly circuit breaker policy :

```<code>AsyncDemo3(HelloWorld);
</code>```

Kindly help the find and resolve the problem.

答:
Recommend creating both policies and combining the same using PolicyWrap as follows.

Policy Creation

```<code> var circuitBreakerPolicy = Policy
        .Handle<TimeoutException>()
        .CircuitBreakerAsync(3, TimeSpan.FromSeconds(2));
 var retryPolicy = Policy.Handle<TimeoutException>().RetryAsync(3);

 // Combined policy: outermost first, innermost last
 var policy = Policy.WrapAsync(retryPolicy, circuitBreakerPolicy);
</code>```

Policy Usage

```<code> await this.policy.ExecuteAsync(async () => await SomeFooMethodAsync(cancellationToken));
</code>```

Body:
I am using Polly library for transient fault handling. For synchronous operations Polly circuit breaker policy works fine but when I created its async version it does not retries the execution. Kindly suggest :

Asynchronous method:

private async static Task HelloWorld()
    {
        if (DateTime.Now < programStartTime.AddSeconds(10))
        {
            Console.WriteLine("Task Failed.");
            throw new TimeoutException();
        }
        await Task.Delay(TimeSpan.FromSeconds(1));
        Console.WriteLine("Task Completed.");
    }

Polly circuit breaker async policy:

private static void AsyncDemo3(Func<Task> action)
    {
        programStartTime = DateTime.Now;

        AsyncPolicy policy = Policy
            .Handle<TimeoutException>()
            .CircuitBreakerAsync(3, TimeSpan.FromSeconds(2));
        try
        {
            var a = policy.ExecuteAndCaptureAsync(action, true).GetAwaiter().GetResult();
        }
        catch (AggregateException ex)
        {
            Console.WriteLine("Exception: " + ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception: " + ex.Message);
        }
    }

Executing the Polly circuit breaker policy :

AsyncDemo3(HelloWorld);

Kindly help the find and resolve the problem.

Body:
Recommend creating both policies and combining the same using PolicyWrap as follows.

Policy Creation

 var circuitBreakerPolicy = Policy
        .Handle<TimeoutException>()
        .CircuitBreakerAsync(3, TimeSpan.FromSeconds(2));
 var retryPolicy = Policy.Handle<TimeoutException>().RetryAsync(3);

 // Combined policy: outermost first, innermost last
 var policy = Policy.WrapAsync(retryPolicy, circuitBreakerPolicy);

Policy Usage

 await this.policy.ExecuteAsync(async () => await SomeFooMethodAsync(cancellationToken));


问:
Efficiently removing duplicates from a list
Good evening. I have an excel file with zip codes and associated information. Those zip codes have a lot of duplicates. I'd like to figure out which zip codes I have by putting them all in a list without duplicates. This code works, but runs very slowly (took over 100 seconds), and was wondering what I could do to improve the efficiency of it.

I know that having to check the whole list for duplicates each time is contributing a lot to the inefficiency, but I'm not sure how to fix that. I also know that going through every row is probably not the best answer, but again I am pretty new and am now stuck.

Thanks in advance.

```<code>import sys
import xlrd

loc = ("locationOfFile")
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)

def findUniqueZips():
    zipsInSheet = []
    for i in range(sheet.nrows):
        if str(sheet.cell(i,0).value) in zipsInSheet:
            pass
        else:
            zipsInSheet.append(str(sheet.cell(i,0).value))
    print(zipsInSheet)

findUniqueZips()
</code>```

答:
I usually just convert it to a set.   Sets are your friend.  They are much faster than lists.  Unless you intentionally need or want duplicates, use sets.

https://docs.python.org/3.7/tutorial/datastructures.html?highlight=intersection#sets

Body:
Good evening. I have an excel file with zip codes and associated information. Those zip codes have a lot of duplicates. I'd like to figure out which zip codes I have by putting them all in a list without duplicates. This code works, but runs very slowly (took over 100 seconds), and was wondering what I could do to improve the efficiency of it.

I know that having to check the whole list for duplicates each time is contributing a lot to the inefficiency, but I'm not sure how to fix that. I also know that going through every row is probably not the best answer, but again I am pretty new and am now stuck.

Thanks in advance.

import sys
import xlrd

loc = ("locationOfFile")
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)

def findUniqueZips():
    zipsInSheet = []
    for i in range(sheet.nrows):
        if str(sheet.cell(i,0).value) in zipsInSheet:
            pass
        else:
            zipsInSheet.append(str(sheet.cell(i,0).value))
    print(zipsInSheet)

findUniqueZips()


问:
Define a quantile group in a dataframe with the data source in another dataframe in R
I have a quantile information from a dataframe in a named vector using the next code:

```<code>library(tidyverse)

quant_mpg <- mtcars %>%
  pull(mpg) %>%
  quantile(probs = seq(0, 1, 0.1))

</code>```

And I want to cut this quantile in a summary dataframe created post:

```<code>grouped_mtcars <- mtcars %>%
  group_by(cyl) %>%
  summarize(mpg = mean(mpg)) %>%
  ungroup() %>%
  mutate(quantile = cut(mpg, quant_mpg, labels = FALSE))

</code>```

Obtaning the next output:

```<code># A tibble: 3 x 3
    cyl   mpg quantile
  <dbl> <dbl>    <int>
1     4  26.7        9
2     6  19.7        6
3     8  15.1        2
</code>```

Is there a way I can make this straightforward for the grouped variable without defining the quant_mpg vector. I need it this way bacause I have several group variables and grouped dataframes and I need to obtain the quantiles without much processing.

答:
We can extract the column from original data</p>

```<code>library(dplyr)
mtcars %>%
   group_by(cyl) %>%
   summarise(mpg = mean(mpg)) %>%
   mutate(quantile = cut(mpg,  quantile(mtcars[['mpg']], #####
            probs = seq(0, 1, 0.1)), labels = FALSE))
# A tibble: 3 x 3
#    cyl   mpg quantile
#  <dbl> <dbl>    <int>
#1     4  26.7        9
#2     6  19.7        6
#3     8  15.1        2
</code>```

Body:
I have a quantile information from a dataframe in a named vector using the next code:

library(tidyverse)

quant_mpg <- mtcars %>%
  pull(mpg) %>%
  quantile(probs = seq(0, 1, 0.1))

And I want to cut this quantile in a summary dataframe created post:

grouped_mtcars <- mtcars %>%
  group_by(cyl) %>%
  summarize(mpg = mean(mpg)) %>%
  ungroup() %>%
  mutate(quantile = cut(mpg, quant_mpg, labels = FALSE))

Obtaning the next output:

# A tibble: 3 x 3
    cyl   mpg quantile
  <dbl> <dbl>    <int>
1     4  26.7        9
2     6  19.7        6
3     8  15.1        2

Is there a way I can make this straightforward for the grouped variable without defining the quant_mpg vector. I need it this way bacause I have several group variables and grouped dataframes and I need to obtain the quantiles without much processing.

Body:
We can extract the column from original data

library(dplyr)
mtcars %>%
   group_by(cyl) %>%
   summarise(mpg = mean(mpg)) %>%
   mutate(quantile = cut(mpg,  quantile(mtcars[['mpg']], #####
            probs = seq(0, 1, 0.1)), labels = FALSE))
# A tibble: 3 x 3
#    cyl   mpg quantile
#  <dbl> <dbl>    <int>
#1     4  26.7        9
#2     6  19.7        6
#3     8  15.1        2


问:
Channel capability V2_0 is required but not supported Fabric V2
I'm getting this error with orderer while launching a Fabric v2 network

```<code>Channel capability V2_0 is required but not supported
</code>```

My configtx.yaml's Capabilities section

```<code>Capabilities:
    Channel: &ChannelCapabilities
        V2_0: true
    Orderer: &OrdererCapabilities
        V2_0: true
    Application: &ApplicationCapabilities
        V2_0: true
</code>```

Generated channel artifacts with configtxgen v2.0.0

```<code> $ configtxgen --version
configtxgen:
 Version: 2.0.0
 Commit SHA: 0432c3e80
 Go version: go1.13.4
 OS/Arch: linux/amd64
</code>```

Using hyperledger/fabric-orderer:latest docker image.

Any suggestion what I might be doing wrong?

答: The latest tag points to the 1.4 image, not the 2.0 image. I can't remember exactly what the discussion around the latest tag was but I don't believe its planned to be updated, ie it's intentional that latest hasn't been changed to point to 2.0

Body:
I'm getting this error with orderer while launching a Fabric v2 network

Channel capability V2_0 is required but not supported

My configtx.yaml's Capabilities section

Capabilities:
    Channel: &ChannelCapabilities
        V2_0: true
    Orderer: &OrdererCapabilities
        V2_0: true
    Application: &ApplicationCapabilities
        V2_0: true

Generated channel artifacts with configtxgen v2.0.0

 $ configtxgen --version
configtxgen:
 Version: 2.0.0
 Commit SHA: 0432c3e80
 Go version: go1.13.4
 OS/Arch: linux/amd64

Using hyperledger/fabric-orderer:latest docker image.

Any suggestion what I might be doing wrong?


问:
List sorting in CMake 3.12
I'd missing something basic in CMake.
This code:

```<code>set(MyList "a" "b" "c")
list(SORT "${MyList}")
</code>```

Runs fine in CMake 3.14, but fails in 3.12 with this error:

```<code>list sub-command SORT requires list to be present.
</code>```

The documentation for list doesn't say anything specific.
Were there some changes done in 3.14 in the are of list handling?
What is the proper way to sort a list in 3.12?

答:
This was a silly mistake.
The CMake 3.14 added different handling of list variables. Now "${MyList}" is acceptable. In the previous versions only MyList must be used.

Title: List sorting in CMake 3.12

Body:
I'd missing something basic in CMake.
This code:

set(MyList "a" "b" "c")
list(SORT "${MyList}")

Runs fine in CMake 3.14, but fails in 3.12 with this error:

list sub-command SORT requires list to be present.

The documentation for list doesn't say anything specific.
Were there some changes done in 3.14 in the are of list handling?
What is the proper way to sort a list in 3.12?


问:
Transparent HTTP tunnel to TCP
I want to open any arbitrary TCP socket on a server, but it's behind a proxy and I can only use a port that is intended for HTTP hosting only. Simply put, what is the most transparent way to wrap such a socket into an HTTP connection? Preferably I would call a *nix program through a shell script in the server that would take care of translating the requests.

I apologize if this was answered before, but I am struggling to find and understand anything.

答:
I ended up going with Chisel, which provides a single binary for both servers and clients, with features like authentication and reverse port forwarding. For instance:

```<code>chisel server
</code>```

will run an HTTP server in $PORT or 8080, and

```<code>chisel client server.com 4567:123
</code>```

connects to server.com and maps the remote port 123 into the local port 4567.

Other solutions are still welcome, particularly if they involve more transparency, frequently preinstalled tools like netcat, and if they also provide support for other protocols like UDP.

Title: Transparent HTTP tunnel to TCP

Body:
I ended up going with Chisel, which provides a single binary for both servers and clients, with features like authentication and reverse port forwarding. For instance:

chisel server

will run an HTTP server in $PORT or 8080, and

chisel client server.com 4567:123

connects to server.com and maps the remote port 123 into the local port 4567.

Other solutions are still welcome, particularly if they involve more transparency, frequently preinstalled tools like netcat, and if they also provide support for other protocols like UDP.


问:
tinyXml how to create xml
HI,

I have the following:

```<code>class pers
{
    public:
      pers();
      std::string name;
      long favourite_number;
      time_t curent_time;
}
</code>```

I would like to create an xml using tinyXml. Here is the xml:

```<code><data>
<name> me </name>
<favourite_number> 1233336555 </favourite_number> //it's a long number
<curent_time> hour:day:month:year </curent_time>
</code>```

And here is the code:

```<code>main()
{
    pers *p = new pers();
    pers->name="me";
    pers->favourite_number=12333336555;

    /**/how too print the curent time ?**
    TiXmlDocument doc;
    TiXmlElement * root;
    root = new TiXmlElement( "data" );
    TiXmlElement * element1 = new TiXmlElement( "name" );
    root->LinkEndChild( element1);
    TiXmlText * text1 = new TiXmlText( pers->name );
    element1->LinkEndChild( text1 );
    TiXmlElement * element2 = new TiXmlElement( "favourite_number" );
    root->LinkEndChild( element2);
    long d=pers->favourite_number;

    std::ostringstream os;
    os << d;
    std::string buf2=os.str();

   TiXmlText * text2 = new TiXmlText( buf2 );
   element2->LinkEndChild( text2 );
</code>```

How to do this if I want to have the current time in the xml?

Isn't there an easier way to do it?

答:
So your question basically has nothing to do with XML, nor TinyXml? Next time you might want to simplify your question and give it an appropriate title. </p>

<p>You can either go via time.h and the functionality provided in there or use something like Boost.Date_Time. Something which was answered here as well. </p>

Title: tinyXml how to create xml

Body:
HI,

I have the following:

class pers
{
    public:
      pers();
      std::string name;
      long favourite_number;
      time_t curent_time;
}

I would like to create an xml using tinyXml. Here is the xml:

<data>
<name> me </name>
<favourite_number> 1233336555 </favourite_number> //it's a long number
<curent_time> hour:day:month:year </curent_time>

And here is the code:

main()
{
    pers *p = new pers();
    pers->name="me";
    pers->favourite_number=12333336555;

    /**/how too print the curent time ?**
    TiXmlDocument doc;
    TiXmlElement * root;
    root = new TiXmlElement( "data" );
    TiXmlElement * element1 = new TiXmlElement( "name" );
    root->LinkEndChild( element1);
    TiXmlText * text1 = new TiXmlText( pers->name );
    element1->LinkEndChild( text1 );
    TiXmlElement * element2 = new TiXmlElement( "favourite_number" );
    root->LinkEndChild( element2);
    long d=pers->favourite_number;

    std::ostringstream os;
    os << d;
    std::string buf2=os.str();

   TiXmlText * text2 = new TiXmlText( buf2 );
   element2->LinkEndChild( text2 );

How to do this if I want to have the current time in the xml?

Isn't there an easier way to do it?

Body:
So your question basically has nothing to do with XML, nor TinyXml? Next time you might want to simplify your question and give it an appropriate title.

You can either go via time.h and the functionality provided in there or use something like Boost.Date_Time. Something which was answered here as well.


问:
check that a word is an isogram with pure javascript
How do i check that a given word is an isogram with pure javascript, using a function. the function must return true or false.

An isogram is a word with a repeated character.

I know this code works, but i need a better solution.

```<code>function isIsogram(word){
    x = false; y = false;
    for(i = 0; i < word.length; i++){
        wordl = word.substring(0,i)
        wordr = word.substring(i)
        x = wordl.includes(word.charAt(i))
        y = wordr.includes(word.charAt(i))
        //console.log(x,wordl,wordr)
    }
    return x&&y
}
isIsogram("thomas");//False
isIsogram("moses"); //True
</code>```

答:
```<code>const isIsogram = (word) => {
    return new Set(word.toLowerCase()).size === word.length
}

console.log(isIsogram('Thor'));//true
console.log(isIsogram('Loki'));//true
console.log(isIsogram('America'));//false
</code>```

Body:
How do i check that a given word is an isogram with pure javascript, using a function. the function must return true or false.

An isogram is a word with a repeated character.

I know this code works, but i need a better solution.

function isIsogram(word){
    x = false; y = false;
    for(i = 0; i < word.length; i++){
        wordl = word.substring(0,i)
        wordr = word.substring(i)
        x = wordl.includes(word.charAt(i))
        y = wordr.includes(word.charAt(i))
        //console.log(x,wordl,wordr)
    }
    return x&&y
}
isIsogram("thomas");//False
isIsogram("moses"); //True


问:
Error with Confluent Schema REST proxy when trying to set an Avro schema
I am trying to update an avro schema using the rest proxy API in Confluent.  I can do a GET with the following, and get a valid response:

http://mykafkahost.com:8081/subjects/avro-schema-for-value/versions/1

But when I try this:
http://mykafkahost.com:8081/subjects/my-avro-schema-for-value/1

using either POST, PUT, or PATCH, I consistently get

{"error_code":404,"message":"HTTP 404 Not Found"}

Also tried
http://mykafkahost.com:8081/subjects/my-avro-schema-for-value/versions/1
but it yields:

{"error_code":405,"message":"HTTP 405 Method Not Allowed"}

I've asked the operations team, and they don't believe specific verbs are enabled/disabled, but it's looking possible to me. If I need to enable the POST, what config file is this done through?

答:
If your intention is to update the schema which is already registered in schema registry then here is the POST call,

```<code>HTTP POST:
URL http://mykafkahost.com:8081/subjects/my-avro-schema-for-value/
Post Body:
    {
          "schema":
             "{
                    \"type\": \"record\",
                    \"name\": \"test\",
                    \"fields\":
                      [
                        {
                          \"type\": \"string\",
                          \"name\": \"field1\"
                        },
                        {
                          \"type\": \"int\",
                          \"name\": \"field2\"
                        }
                      ]
                  }"
        }

Response:
HTTP/1.1 200 OK
{"id":2}
</code>```

On success of POST request, there will be a new version of the schema for the topic, but you can't update the existing version, you can only delete the version.

Hope this answers.

Body:
If your intention is to update the schema which is already registered in schema registry then here is the POST call,

HTTP POST:
URL http://mykafkahost.com:8081/subjects/my-avro-schema-for-value/
Post Body:
    {
          "schema":
             "{
                    \"type\": \"record\",
                    \"name\": \"test\",
                    \"fields\":
                      [
                        {
                          \"type\": \"string\",
                          \"name\": \"field1\"
                        },
                        {
                          \"type\": \"int\",
                          \"name\": \"field2\"
                        }
                      ]
                  }"
        }

Response:
HTTP/1.1 200 OK
{"id":2}

On success of POST request, there will be a new version of the schema for the topic, but you can't update the existing version, you can only delete the version.

Hope this answers.