问:
Invoking a kafka consumer based on some condition
Suppose if there is a class A which is consuming data from kafka consumer C1 and based on the data from consumer C1, I need to start consuming from consumer C2.

Is there a way to do it?

答:
Here's one way:

@SpringBootApplication
public class So62160012Application {

    public static void main(String[] args) {
        SpringApplication.run(So62160012Application.class, args);
    }

    @Autowired
    private KafkaListenerEndpointRegistry registry;

    @Autowired
    private KafkaTemplate<String, String> template;

    @KafkaListener(id = "so62160012-1", topics = "so62160012-1")
    public void listen1(String in) {
        System.out.println("one: " + in);
        template.send("so62160012-2", in);
        if (in.contains("startC2")) {
            this.registry.getListenerContainer("so62160012-2").start();
        }
    }

    @KafkaListener(id = "so62160012-2", topics = "so62160012-2", autoStartup = "false")
    public void listen2(String in) {
        System.out.println("two: " + in);
    }

    @Bean
    public NewTopic topic1() {
        return TopicBuilder.name("so62160012-1").partitions(1).replicas(1).build();
    }

    @Bean
    public NewTopic topic2() {
        return TopicBuilder.name("so62160012-2").partitions(1).replicas(1).build();
    }

    @Bean
    public ApplicationRunner runner() {
        return args -> {
            IntStream.range(0, 10)
                    .map(i -> {
                        try {
                            Thread.sleep(2000);
                        }
                        catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                        }
                        return i;
                    })
                    .forEach(i -> this.template.send("so62160012-1",
                            "foo" + i + (i == 5 ? "startC2" : "")));
        };
    }

}
```

Hopefully self-explanatory.

Body:
Here's one way:

@SpringBootApplication
public class So62160012Application {

    public static void main(String[] args) {
        SpringApplication.run(So62160012Application.class, args);
    }

    @Autowired
    private KafkaListenerEndpointRegistry registry;

    @Autowired
    private KafkaTemplate<String, String> template;

    @KafkaListener(id = "so62160012-1", topics = "so62160012-1")
    public void listen1(String in) {
        System.out.println("one: " + in);
        template.send("so62160012-2", in);
        if (in.contains("startC2")) {
            this.registry.getListenerContainer("so62160012-2").start();
        }
    }

    @KafkaListener(id = "so62160012-2", topics = "so62160012-2", autoStartup = "false")
    public void listen2(String in) {
        System.out.println("two: " + in);
    }

    @Bean
    public NewTopic topic1() {
        return TopicBuilder.name("so62160012-1").partitions(1).replicas(1).build();
    }

    @Bean
    public NewTopic topic2() {
        return TopicBuilder.name("so62160012-2").partitions(1).replicas(1).build();
    }

    @Bean
    public ApplicationRunner runner() {
        return args -> {
            IntStream.range(0, 10)
                    .map(i -> {
                        try {
                            Thread.sleep(2000);
                        }
                        catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                        }
                        return i;
                    })
                    .forEach(i -> this.template.send("so62160012-1",
                            "foo" + i + (i == 5 ? "startC2" : "")));
        };
    }

}

Hopefully self-explanatory.


来源: stackexchange

问:
Python While loop not iterating variable only print commands
Background context - I'm making a peculiar clock that will display the time via WS2812B pixels and learning as I go!

I have a dictionary that will contain the commands being sent to the pixels as below

```<code>hourvalues = {1: "Hour One",
              2: "Hour Two"}
</code>```

etc etc up to 24
And the main document contains the loop:

```<code>while True:
    print(hourvalues[hour])
    sleep(1)
</code>```

This works wonderfully for now with print (as a test) and I get a word every second. However, if I change the dictionary to

```<code>hourvalues = {1: print("Hour One"),
              2: Print("Hour Two")}
</code>```

and the body to

```<code>while True:
    hourvalues[hour]
    sleep(1)
</code>```

in order to represent the final thing where it will be sending a command, not printing a line, I get just a single word, and that's it.

What am I doing wrong?

This is my first post, be gentle! Thanks all

答:
You have to put the function as dict value, not its return value, as you are doing in your second piece of code.

So, it could look like:

```<code>def hour_one():
    print('Hour one')

def hour_two():
    print('Hour two')

hourvalues = {1: hour_one,  # no (), you don't want to call it
              2: hour_two}  # while creating the dict !

for hour in [1, 2]:
    hourvalues[hour]()  # call it now
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Background context - I'm making a peculiar clock that will display the time via WS2812B pixels and learning as I go!

I have a dictionary that will contain the commands being sent to the pixels as below

hourvalues = {1: "Hour One",
              2: "Hour Two"}

etc etc up to 24
And the main document contains the loop:

while True:
    print(hourvalues[hour])
    sleep(1)

This works wonderfully for now with print (as a test) and I get a word every second. However, if I change the dictionary to

hourvalues = {1: print("Hour One"),
              2: Print("Hour Two")}

and the body to

while True:
    hourvalues[hour]
    sleep(1)

in order to represent the final thing where it will be sending a command, not printing a line, I get just a single word, and that's it.

What am I doing wrong?

This is my first post, be gentle! Thanks all

Body:
You have to put the function as dict value, not its return value, as you are doing in your second piece of code.

So, it could look like:

def hour_one():
    print('Hour one')

def hour_two():
    print('Hour two')

hourvalues = {1: hour_one,  # no (), you don't want to call it
              2: hour_two}  # while creating the dict !

for hour in [1, 2]:
    hourvalues[hour]()  # call it now


问:
What is the most efficient way to call a function on a 2D ndarray of coordinates?
I have a ndarray of size (M, N, 3). It holds M x N points, each of which is identified by its x, y, and z coordinates. I also have a function 'foo'. 'foo' takes in a point as a ndarray of size (, 3). Is there a faster way to call 'foo' on each of the M x N points in my array than to use two nested for loops?

So far, this is what I have tried. My array is the variable 'sample_array'.

```<code>num_rows = sample_array.shape[0]
num_columns = sample_array.shape[1]
solution = np.zeros((num_rows, num_columns))

for row in range(num_rows):
   for column in range(num_columns):
      point = sample_array[row, column]
      solution[row, column] = foo(point)
</code>```

I found this answer, which describes using these two solutions:

```<code>np.vectorize(foo)
np.array(map(foo, sample_array))
</code>```

However, I am not sure how to specify that I don't want the function mapped to every one of the M x N x 3 floats. Instead, I would like it to map the function to be called on each of the M x N (, 3) ndarrays.

Thank you!

答:
Ideally, the function foo you're calling will accept arrays as input. In general, it's good style for any function to accept all arrays as long as the first dimension is as expected. For example, the function

import numpy

def length(x):
    return numpy.sqrt(x[0] ** 2 + x[1] ** 2 + x[2] ** 2)
```

computes the length of a vector, but also accepts arrays of shape (3, ...) (it doesn't even matter how many dimensions follow) and does the right thing.

This design has the following advantages:

The code works for scalars and arrays.

It works for arrays of arbitrary dimensionality.

Working in the first dimension is faster (with C-contiguous ordering).

It often leads to clean code.

Body:
I have a ndarray of size (M, N, 3). It holds M x N points, each of which is identified by its x, y, and z coordinates. I also have a function 'foo'. 'foo' takes in a point as a ndarray of size (, 3). Is there a faster way to call 'foo' on each of the M x N points in my array than to use two nested for loops?

So far, this is what I have tried. My array is the variable 'sample_array'.

num_rows = sample_array.shape[0]
num_columns = sample_array.shape[1]
solution = np.zeros((num_rows, num_columns))

for row in range(num_rows):
   for column in range(num_columns):
      point = sample_array[row, column]
      solution[row, column] = foo(point)

I found this answer, which describes using these two solutions:

np.vectorize(foo)
np.array(map(foo, sample_array))

However, I am not sure how to specify that I don't want the function mapped to every one of the M x N x 3 floats. Instead, I would like it to map the function to be called on each of the M x N (, 3) ndarrays.

Thank you!

Body:
Ideally, the function foo you're calling will accept arrays as input. In general, it's good style for any function to accept all arrays as long as the first dimension is as expected. For example, the function

import numpy

def length(x):
    return numpy.sqrt(x[0] ** 2 + x[1] ** 2 + x[2] ** 2)

computes the length of a vector, but also accepts arrays of shape (3, ...) (it doesn't even matter how many dimensions follow) and does the right thing.

This design has the following advantages:

The code works for scalars and arrays.

It works for arrays of arbitrary dimensionality.

Working in the first dimension is faster (with C-contiguous ordering).

It often leads to clean code.


问:
compare two text files then update the specific values based on the matching first column. (python)
I have two files. File1 needs to grab values from file2 only if they have the same ID number. I only want to grab the LATITUDE and LONGITUDE values from file2. I need to update these values. I am not sure why the code below is not showing the output I want.

```<code>File1.txt

#ID CAT CHN LC SC LATITUDE LONGITUDE
20022 CX 21 --   4  32.739000  -114.635700
01711 CX 21 --   3  32.779700  -115.567500
08433 CX 21 --   2  31.919930  -123.321000

File2.txt

20022,32.45,-114.88
01192,32.839,-115.487
01711,32.88,-115.45
01218,32.717,-115.637

output
#ID CAT CHN LC SC LATITUDE LONGITUDE
20022 CX 21 --   4  32.45  -114.88
01711 CX 21 --   3  32.88  -115.45
08433 CX 21 --   2  31.919930  -123.321000
</code>```

The code I have so far.

```<code>file1_data = []

file1_headers = []

with open("File1.txt") as file1:
    for line in file1:
        file1_data.append(line.strip().split("\n"))
    file1_headers = file1_data[0]
    del file1_data[0]

file2_data = []

with open("File2.txt") as file2:
    for line in file2:
        file2_data.append(line.strip().split("\n"))

file2_ids = [x[0] for x in file2_data]

final_data = [file1_headers] + file1_data

for i in range(1, len(final_data)):
    if final_data[i][0] in file2_ids:
        match = [x for x in file2_data if x[0] == final_data[i][0]]
        final_data[i] = [match[0] + [final_data[i][3]]]

with open("output.txt", "w") as output:
    output.writelines("\n".join(["\n".join(x) for x in final_data]))
</code>```

答:
line.strip().split doesn't do what you think it does. You can see how to use it below. I also recommend using a dictionary in cases like this where you have a clear key and values for efficiency. I split the original file by spaces to maintain structure when joining later, and removed some redundant intermediate variables as well.

In general, I would recommend against relying so heavily on format, since an extra space could ruin everything. Consider creating a class for the objects described by each line for more modularity.

```<code>

with open("File1.txt") as file1:
    output_data = [(line.strip().split(' ')) for line in file1]

with open("File2.txt") as file2:
    file2_data = [line.strip().split(",") for line in file2]

# save the latitude and longitude.
file2_data = {x[0]: (x[1], x[2]) for x in file2_data}

# replace the output in the original data
for i in range(1, len(output_data)):
    id = output_data[i][0]
    if id in file2_data:
        output_data[i][8] = file2_data[id][0]
        output_data[i][10] = file2_data[id][1]

with open("output.txt", "w") as output:
    output.writelines("\n".join([" ".join(i) for i in output_data]))
</code>```

This produces the output:

```<code>#ID CAT CHN LC SC LATITUDE LONGITUDE
20022 CX 21 --   4  32.45  -114.88
01711 CX 21 --   3  32.88  -115.45
08433 CX 21 --   2  31.919930  -123.321000
</code>```

Body:
I have two files. File1 needs to grab values from file2 only if they have the same ID number. I only want to grab the LATITUDE and LONGITUDE values from file2. I need to update these values. I am not sure why the code below is not showing the output I want.

File1.txt

#ID CAT CHN LC SC LATITUDE LONGITUDE
20022 CX 21 --   4  32.739000  -114.635700
01711 CX 21 --   3  32.779700  -115.567500
08433 CX 21 --   2  31.919930  -123.321000

File2.txt

20022,32.45,-114.88
01192,32.839,-115.487
01711,32.88,-115.45
01218,32.717,-115.637

output
#ID CAT CHN LC SC LATITUDE LONGITUDE
20022 CX 21 --   4  32.45  -114.88
01711 CX 21 --   3  32.88  -115.45
08433 CX 21 --   2  31.919930  -123.321000

The code I have so far.

file1_data = []

file1_headers = []

with open("File1.txt") as file1:
    for line in file1:
        file1_data.append(line.strip().split("\n"))
    file1_headers = file1_data[0]
    del file1_data[0]

file2_data = []

with open("File2.txt") as file2:
    for line in file2:
        file2_data.append(line.strip().split("\n"))

file2_ids = [x[0] for x in file2_data]

final_data = [file1_headers] + file1_data

for i in range(1, len(final_data)):
    if final_data[i][0] in file2_ids:
        match = [x for x in file2_data if x[0] == final_data[i][0]]
        final_data[i] = [match[0] + [final_data[i][3]]]

with open("output.txt", "w") as output:
    output.writelines("\n".join(["\n".join(x) for x in final_data]))

Body:
line.strip().split doesn't do what you think it does. You can see how to use it below. I also recommend using a dictionary in cases like this where you have a clear key and values for efficiency. I split the original file by spaces to maintain structure when joining later, and removed some redundant intermediate variables as well.

In general, I would recommend against relying so heavily on format, since an extra space could ruin everything. Consider creating a class for the objects described by each line for more modularity.

with open("File1.txt") as file1:
    output_data = [(line.strip().split(' ')) for line in file1]

with open("File2.txt") as file2:
    file2_data = [line.strip().split(",") for line in file2]

# save the latitude and longitude.
file2_data = {x[0]: (x[1], x[2]) for x in file2_data}

# replace the output in the original data
for i in range(1, len(output_data)):
    id = output_data[i][0]
    if id in file2_data:
        output_data[i][8] = file2_data[id][0]
        output_data[i][10] = file2_data[id][1]

with open("output.txt", "w") as output:
    output.writelines("\n".join([" ".join(i) for i in output_data]))

This produces the output:

#ID CAT CHN LC SC LATITUDE LONGITUDE
20022 CX 21 --   4  32.45  -114.88
01711 CX 21 --   3  32.88  -115.45
08433 CX 21 --   2  31.919930  -123.321000


问:
Data not Saved in file xml
I have this code in ASP.NET MVC: I want to save the data from datareader in xml file I used this code shown below but I have in the file just two lines:

```<code><?xml version="1.0" encoding="utf-8"?>
<Centre_Commercial />
</code>```

My code in the controller:

```<code>XDocument document = new XDocument(new XDeclaration("1.0", "utf-8", null));
XElement nodecentre = new XElement("Centre_Commercial");
document.Add(nodecentre);

while (dr.Read())
{
    nodecentre.Add(new XElement("Num_Centre", Convert.ToInt32(dr[0].ToString())));
    nodecentre.Add(new XElement("Num_Centre", dr[1].ToString()));
    nodecentre.Add(new XElement("Num_Centre", Convert.ToDateTime(dr[2].ToString()).Date));
    nodecentre.Add(new XElement("Num_Centre", int.Parse(dr[3].ToString())));
    nodecentre.Add(new XElement("Num_Centre", int.Parse(dr[4].ToString())));
    nodecentre.Add(new XElement("Num_Centre", Convert.ToDateTime(dr[5].ToString())));
    nodecentre.Add(new XElement("Num_Centre", dr[6].ToString()));
    nodecentre.Add(new XElement("Num_Centre", dr[7].ToString()));
    nodecentre.Add(new XElement("Num_Centre", int.Parse(dr[8].ToString())));

    document.Save(Server.MapPath(@"~/App_Data/test.Xml"));
}

con.Close();
</code>```

Thanks in advance

答:
You need to move .Save(...) method call out of the loop.

c#

```<code>}
con.Close();
document.Save(Server.MapPath(@"~/App_Data/test.Xml"));
</code>```

SQL

Very possible that you need to add SET NOCOUNT ON; as a first line in the stored procedure.

```<code>create procedure spBudget
(
    @budget1 int,
    @budget2 int
) as
begin
    SET NOCOUNT ON;
    select * from Centre_Commercial where budget between @b and @b;
end
</code>```

Title: Data not Saved in file xml

Body:
I have this code in ASP.NET MVC: I want to save the data from datareader in xml file I used this code shown below but I have in the file just two lines:

<?xml version="1.0" encoding="utf-8"?>
<Centre_Commercial />

My code in the controller:

XDocument document = new XDocument(new XDeclaration("1.0", "utf-8", null));
XElement nodecentre = new XElement("Centre_Commercial");
document.Add(nodecentre);

while (dr.Read())
{
    nodecentre.Add(new XElement("Num_Centre", Convert.ToInt32(dr[0].ToString())));
    nodecentre.Add(new XElement("Num_Centre", dr[1].ToString()));
    nodecentre.Add(new XElement("Num_Centre", Convert.ToDateTime(dr[2].ToString()).Date));
    nodecentre.Add(new XElement("Num_Centre", int.Parse(dr[3].ToString())));
    nodecentre.Add(new XElement("Num_Centre", int.Parse(dr[4].ToString())));
    nodecentre.Add(new XElement("Num_Centre", Convert.ToDateTime(dr[5].ToString())));
    nodecentre.Add(new XElement("Num_Centre", dr[6].ToString()));
    nodecentre.Add(new XElement("Num_Centre", dr[7].ToString()));
    nodecentre.Add(new XElement("Num_Centre", int.Parse(dr[8].ToString())));

    document.Save(Server.MapPath(@"~/App_Data/test.Xml"));
}

con.Close();

Thanks in advance

Body:
You need to move .Save(...) method call out of the loop.

c#

}
con.Close();
document.Save(Server.MapPath(@"~/App_Data/test.Xml"));

SQL

Very possible that you need to add SET NOCOUNT ON; as a first line in the stored procedure.

create procedure spBudget
(
    @budget1 int,
    @budget2 int
) as
begin
    SET NOCOUNT ON;
    select * from Centre_Commercial where budget between @b and @b;
end


问:
JavaScript audio analyze phonetics
I'm able to analyze audio data using the AudioContext API in JavaScript and draw the waveform to a canvas.

The question is, after loading the audio data, I have about a 1024-long Uint8Array data points representing the wavelength (per frame), how do I guess what sounds this is making (from a choice of the phonetics mentioned here, namely:

Ⓐ

lisa A

Closed mouth for the “P”, “B”, and “M” sounds. This is almost identical to the Ⓧ shape, but there is ever-so-slight pressure between the lips.

Ⓑ

lisa B

Slightly open mouth with clenched teeth. This mouth shape is used for most consonants (“K”, “S”, “T”, etc.). It’s also used for some vowels such as the “EE” sound in bee.

Ⓒ

lisa C

Open mouth. This mouth shape is used for vowels like “EH” as in men and “AE” as in bat. It’s also used for some consonants, depending on context.

This shape is also used as an in-between when animating from Ⓐ or Ⓑ to Ⓓ. So make sure the animations ⒶⒸⒹ and ⒷⒸⒹ look smooth!

Ⓓ

lisa D

Wide open mouth. This mouth shapes is used for vowels like “AA” as in father.

Ⓔ

lisa E

Slightly rounded mouth. This mouth shape is used for vowels like “AO” as in off and “ER” as in bird.

This shape is also used as an in-between when animating from Ⓒ or Ⓓ to Ⓕ. Make sure the mouth isn’t wider open than for Ⓒ. Both ⒸⒺⒻ and ⒹⒺⒻ should result in smooth animation.

Ⓕ

lisa F

Puckered lips. This mouth shape is used for “UW” as in you, “OW” as in show, and “W” as in way.

Ⓖ

lisa G

Upper teeth touching the lower lip for “F” as in for and “V” as in very.

This extended mouth shape is optional. If your art style is detailed enough, it greatly improves the overall look of the animation. If you decide not to use it, you can specify so using the extendedShapes option.

Ⓗ

lisa H

This shape is used for long “L” sounds, with the tongue raised behind the upper teeth. The mouth should be at least far open as in Ⓒ, but not quite as far as in Ⓓ.

This extended mouth shape is optional. Depending on your art style and the angle of the head, the tongue may not be visible at all. In this case, there is no point in drawing this extra shape. If you decide not to use it, you can specify so using the extendedShapes option.

Ⓧ

lisa X

Idle position. This mouth shape is used for pauses in speech. This should be the same mouth drawing you use when your character is walking around without talking. It is almost identical to Ⓐ, but with slightly less pressure between the lips: For Ⓧ, the lips should be closed but relaxed.

This extended mouth shape is optional. Whether there should be any visible difference between the rest position Ⓧ and the closed talking mouth Ⓐ depends on your art style and personal taste. If you decide not to use it, you can specify so using the extendedShapes option.

)?

I know there are many machine learning options like Meyda and Tensorflow and other machine learning methodss, but I want an algorithm to detech the above phonetics in real time. It doesn't have to be 100% accurate, just slightly better than randomly picking certain values for the mouths... At this point, anything better than random would be fine.

I'm aware audio recognition can be done with PocketSphinx.js, and this is used in rhubarb lipsink for its calculations, but all I'm looking for is a very simple algorithm, given a 1024 data-array of a wavelength per frame, of how to get the phonetics, again, it doesn't have to be 100% accurate, but it has to be realtime, and better than random.

Basically, the problem with pocketsphinx is that it's purpose is to get speech-to-word recognition, so it has a lot of extra code meant to translate the sounds to the exact words it has compiled in the dictionaries, but I don't need that I only need to extract the sounds themselves, without converting them to some dictionary, so theoretically there shouldn't be as much overheard.

I just want a simple algorithm that can take the already acquired data from the AudioContext, to just guess, relatively, what sound, in the above-mentioned list, is being made
Again, to be very clear:

I am not looking for a PocketSphinx solution, nor any other "ready to go" library, all I want is a mathematical formula for each one of the unique sounds mentioned above, that can be adapted to any programming language

答:
I'm not sure why this is tagged tensorflow if you don't want a TensorFlow answer. If all you want is something better than random, you are almost certainly better off using a package like PocketSphinx and breaking the returned words down into their phonetics. What you're asking for is quite difficult: see threads discussing why here and here.

However, if you are absolutely attached to finding an algorithm for this...

Searching around, most items I came across used machine learning except for a few: this paper from 2008, this one from 1993, which was expanded into a full Ph.D dissertation, and this MIT research paper from 1997. Here is a sample of the algorithm the authors used in the last one, just for the /R/ sound:

The paper says they implemented their algorithm in C++, but unfortunately no code is included.

Bottom line, I would recommend sticking with PocketSphinx unless this is part of your own Ph.D research!

UPDATE:

Adding more detail here upon request. Pocketsphinx explains, if you scroll all the way down to section 8 in their readme, that they use a machine learning platform called Sphinxtrain, which is also available in French and Chinese. But at the top of the Sphinxtrain page, there is a link to their "new library" called Vosk.

Vosk supports 9 languages and is small enough to fit on a Raspberry Pi, so it may be closer to what you're looking for. It, in turn, uses an open source C++ speech recognition toolkit called Kaldi, which also uses machine learning.

Arduinos are significantly more limited than Raspberry Pis, as I'm sure you know, so you may seriously want to reach out to the authors of the MIT paper if you are going in that direction. The authors used a 200 MHz Pentium Pro processor with 32 MB of RAM, and that's about the power level of the best Arduinos: the Arduino Yun 2 includes a 400 MHz Linux microprocessor with 64 MB of RAM.

Hopefully that gives you enough to chew on. Good luck!

Title: JavaScript audio analyze phonetics


问:
How do I express today's date in DD/MM/YYYY format using RegEx?
I'm working with a bespoke application that uses RegEx to validate information. I am creating a function that validates against another field like so:

```<code><validationrule key="MandatoryIfToday" type="VRMandatoryFieldIfFieldMatchesRegex" triggerField="PolicyDate" triggerRegEx="**today's date**" mandatoryField="MakeMeMandatory" errorcode="ER_MANDATORY" />
</code>```

To achieve this I simply need to know how to express today's date in RegEx format, however I can only find a way of expressing the format DD/MM/YYYY, is it possible to validate today's date dynamically using RegEx?

答:
It's not possible since regex has no concept of time.

What might work instead is to get today's date as a string in DD/MM/YYYY format, then match the input against it. Or you could parse the input as DD/MM/YYYY then match it against today's date.

Body:
I'm working with a bespoke application that uses RegEx to validate information. I am creating a function that validates against another field like so:

<validationrule key="MandatoryIfToday" type="VRMandatoryFieldIfFieldMatchesRegex" triggerField="PolicyDate" triggerRegEx="**today's date**" mandatoryField="MakeMeMandatory" errorcode="ER_MANDATORY" />

To achieve this I simply need to know how to express today's date in RegEx format, however I can only find a way of expressing the format DD/MM/YYYY, is it possible to validate today's date dynamically using RegEx?


问:
add checkbox to qtreewidgetitem
i want to add a check box to my qtreewigetitem, i tried this code to setflag, then i add item is selectable for sake of maybe this will solve my problem but nothing happened, would you please help me how can i add check box to my item?
thank you in advance

```<code>m_eventList->addTopLevelItem(new QTreeWidgetItem);
       QTreeWidgetItem *item = m_eventList->topLevelItem(m_eventList->topLevelItemCount()-1)

    item->setFlags(item->flags() | Qt::ItemIsUserCheckable |Qt::ItemIsSelectable);
</code>```

答:
Qt::ItemIsUserCheckable and Qt::ItemIsSelectable are default setting for QTreeWidget.

item->setCheckState(column, Qt::Unchecked) is Okay.

https://doc.qt.io/qt-5/qtreewidgetitem.html#flags

ContentLicense: CC BY-SA 3.0

Title: add checkbox to qtreewidgetitem

Body:
i want to add a check box to my qtreewigetitem, i tried this code to setflag, then i add item is selectable for sake of maybe this will solve my problem but nothing happened, would you please help me how can i add check box to my item?
thank you in advance

m_eventList->addTopLevelItem(new QTreeWidgetItem);
       QTreeWidgetItem *item = m_eventList->topLevelItem(m_eventList->topLevelItemCount()-1)

    item->setFlags(item->flags() | Qt::ItemIsUserCheckable |Qt::ItemIsSelectable);


问:
Errors in sorting a dictionary
This is my code to find and print values of students with the second-lowest score in the given data

```<code>room =dict()
for _ in range(int(input())):
    name = input()
    score = float(input())
    room.update({name:score})

lowest= min(room.values())
second_lowest = None
for k,v in sorted(room.items(),reverse=True):
    if v == lowest: continue
    elif second_lowest is None:
        second_lowest = v
    elif v < second_lowest:
        second_lowest = v
    if second_lowest==v and second_lowest is not lowest:
        print('name',k)
</code>```

When given a specific set of inputs it returns more than two second_lowest key, for example, for the below input it returns harsh harry and berry where it shouldn't have returned harsh. But this problem disappears if I create a separate (key, value) loop with the same

```<code>sorted(room.items(),reverse=True)
</code>```

Sample Input:

```<code>5
Harry
37.21
Berry
37.21
Tina
37.2
Akriti
41
Harsh
39
</code>```

Sample Output:

```<code>name Harsh
name Harry
name Berry
</code>```

答:
How about this?  Sort the set (i.e. all the unique values) of scores, and then find the second lowest.  Return the names of students with that score:</p>

```<code>def return_lowest(scores_dict, n_most=2):
    unique_scores = sorted(list(set(scores_dict.values())))
    score_lowest = unique_scores[n_most-1]
    output = [name for name in scores_dict if scores_dict[name] == score_lowest]
    return output

In[1]: return_lowest({'Bill':100,'Sally':95,'Fred':75,'Gina':75,'Frank':65})
Out[1]:
['Fred', 'Gina']
</code>```

Title: Errors in sorting a dictionary

Body:
This is my code to find and print values of students with the second-lowest score in the given data

room =dict()
for _ in range(int(input())):
    name = input()
    score = float(input())
    room.update({name:score})

lowest= min(room.values())
second_lowest = None
for k,v in sorted(room.items(),reverse=True):
    if v == lowest: continue
    elif second_lowest is None:
        second_lowest = v
    elif v < second_lowest:
        second_lowest = v
    if second_lowest==v and second_lowest is not lowest:
        print('name',k)

When given a specific set of inputs it returns more than two second_lowest key, for example, for the below input it returns harsh harry and berry where it shouldn't have returned harsh. But this problem disappears if I create a separate (key, value) loop with the same

sorted(room.items(),reverse=True)

Sample Input:

5
Harry
37.21
Berry
37.21
Tina
37.2
Akriti
41
Harsh
39

Sample Output:

name Harsh
name Harry
name Berry

Body:
How about this?  Sort the set (i.e. all the unique values) of scores, and then find the second lowest.  Return the names of students with that score:

def return_lowest(scores_dict, n_most=2):
    unique_scores = sorted(list(set(scores_dict.values())))
    score_lowest = unique_scores[n_most-1]
    output = [name for name in scores_dict if scores_dict[name] == score_lowest]
    return output

In[1]: return_lowest({'Bill':100,'Sally':95,'Fred':75,'Gina':75,'Frank':65})
Out[1]:
['Fred', 'Gina']


问:
error TS2420: Class 'NgRedux<RootState>' incorrectly implements interface 'ObservableStore<RootState>'
When I am going to compile or build angular application on linux (ubuntu) I am getting this issue:

For Compilation: ng serve

For building:   ng build --base-href=/dist/

Error:

ERROR in
  node_modules/@angular-redux/store/lib/src/components/ng-redux.d.ts(10,31): error TS2420: Class 'NgRedux' incorrectly implements
  interface 'ObservableStore'.   Property
  '[Symbol.observable]' is missing in type 'NgRedux' but
  required in type 'ObservableStore'.

These above bash commands working well in my windows environment with same application, when I tried to run or build on Ubuntu it give me this error. This look like redux issue I have downgraded redux version
But it did’t worked for me, I have also tried each and every combination but this issue is not resolved on Ubuntu.

Environment on Linux(Ubuntu) Machine

Node Version: v8.10.0

NPM Version: 3.5.2

Ng version: 7.0.3

Environment on Windows Machine

Node Version: v8.11.3

NPM Version: 5.6.0

Ng version: 7.0.3

答:
I had a similar issue, and the following combination worked for me:

angular cli v9.1.6, redux v4.0.1, angular-redux/store V9

so maybe this?

npm install --save redux@4.0.1

npm install --save @angular-redux/store@^9


问:
SQL DB2 : How to JOIN dynamicaly 2 tables using "running total calculations"
I am learning SQL on a server: IBM V7R1M0, DB2.

I am trying to build a SQL report.
After seeking a similar example several days, I launch this bottle in the ocean of knowledge...

Context:
The stores request goods from the warehouse.
Those goods are pick on pallets.
Those pallets will be put on staging lane before to load them in a truck.

Rule1: We want only pallet(s) from one store on a staging lane (We don't want to mix the pallets from different stores)

Rule2: A store will occupy staging lanes which are nearby.

Rule3: Staging lanes are ordered by there ID (with gaps)

Table 1:

```<code>|-----|-----|-----------------|
| ID  |store|pallet_estimation|
|-----|-----|-----------------|
| 1   | A   | 35              |
| 2   | C   |  2              |
| 3   | B   | 30              |
|-----|-----|-----------------|

SELECT * FROM (
    VALUES (1, 'A', 35), (2, 'C', 2), (3, 'B', 30)
          ) T1(ID, store, pallet_estimation)
</code>```

Table 2 :

```<code>|---------------|---------------|
|ID_staging_lane|pallet_capacity|
|---------------|---------------|
| 201           | 10            |
| 202           | 10            |
| 204           | 30            |
| 205           | 40            |
| 208           | 30            |
| 210           | 30            |
|---------------|---------------|

SELECT * FROM(
  VALUES (201, 10), (202, 10), (204, 30), (205, 40), (208, 30), (210, 30)
     ) T2(ID_staging_lane, pallet_capacity)
</code>```

Expected result:

```<code>|-----------|--------|--------------------|---------------|------------------|
|T1_sequence|T1_store|T1_pallet_estimation|T2_staging_lane|T2_pallet_capacity|
|-----------|--------|--------------------|---------------|------------------|
| 1         | A      | 35                 | 201           | 10               |
| 1         | A      | 35                 | 202           | 10               |
| 1         | A      | 35                 | 204           | 30               |
| 2         | C      |  2                 | 205           | 40               |
| 3         | B      | 30                 | 208           | 30               |
|-----------|--------|--------------------|---------------|------------------|
</code>```

Thanks you, Charles, for you time.
I'll try to improve my demand.

If needed, I want to split/divide the pallet_estimation on several staging lanes, following the sequence

Example:

```<code>For store A which has 35 pallets,
I want to use staging lane 201 then it remains 35 - 10 = 25 ,
then I want to use staging lane 202 then it remains 25 - 10 = 15,
then I want to use staging lane 204 then it remains 15 - 30 = -15

then I want to continue with the store C on the next staging lane 205 then it remains 2 - 40 = -38

then I want to continue with the store B on the next staging lane 208 then it remains 30 - 30 = 0
</code>```

How would you start to build that ?
 - with window function ? SUM() OVER()
 - with recursive SQL ? DECLARE FETCH
 - is it possible to build a dynamic JOIN in SQL ?
 - other idea ?

Thanks in advance,

Renaud

答:
First of all, v7r1 is very old...10 years to be exact...

Secondly, I don't understand what you're trying to join on...I see nothing that would explain why store A ended up with 3 rows in your results.

Thirdly, there's no such thing as a "dynamic join", in any RDBMS.  You can have a dyanmic statement, which could include a join.  Or you can have a static statement, which also could include a join.  For Db2 on the IBM i, it only matters if your incorporating the statement in an RPG/COLBOL program or an SQL stored procedure/function.

Now having said all that, let me introduce you to Common Table Expressions (CTE).  Basicaly the same as a Nested Table Expression (NTE) but IMO easier to follow and CTEs also can have a performance benefit over NTE on the i.

```<code>with T1 as (
  SELECT * FROM (
    VALUES (1, 'A', 35), (2, 'C', 2), (3, 'B', 30)
          ) T1(ID, store, pallet_estimation)
), T2 as (
SELECT * FROM(
  VALUES (201, 10), (202, 10), (204, 30), (205, 40), (208, 30), (210, 30)
     ) T2(ID_staging_lane, pallet_capacity)
), fitment as (
select T1.*, T2.*, row_number() OVER(partition by ID_STAGING_LANE) as rowNbr
from T1 join T2 on pallet_estimation <= pallet_capacity
)
select * from fitment where rowNbr = 1;
</code>```

The with T1 as (<select statement>) is the common table expression; as is T2 and fitment.  The with keyword is only used for the First CTE.

The fitment CTE joins T1 and T2 based upon which estimate fits in the lane description, assigning a row_number to each possibility.  The final select takes the first fit for each lane.

The nice thing about CTE's is you can easily build them and see the results as you go along.  At any point you can add select * from MYCTE and see what you have so far.

Note that as shown, a CTE can reference another CTE.  (fitment reference both T1 and T2)

EDIT

The functions your need to use, to look forward or backwards in the result set are named LAG() and LEAD().  They are part of the OLAP functionality built into Db2 for i.  Unfortunately for you, they were added at 7.3.

You will need to roll your own version using a user defined function (UDF) that makes use what's known as the scatchpad to save data between the calls to the function for each row.

I found an very old article Scribble on SQL's Scratchpad showing how to the scratch pad in RPG.  You can also use it inside an SQL defined UDF.

Do a bit a googling to see if you can get started.  If you run into issues, create a new question here.  (or check out the Midrange mailing lists

Body:
I am learning SQL on a server: IBM V7R1M0, DB2.

I am trying to build a SQL report.
After seeking a similar example several days, I launch this bottle in the ocean of knowledge...

Context:
The stores request goods from the warehouse.
Those goods are pick on pallets.
Those pallets will be put on staging lane before to load them in a truck.

Rule1: We want only pallet(s) from one store on a staging lane (We don't want to mix the pallets from different stores)

Rule2: A store will occupy staging lanes which are nearby.

Rule3: Staging lanes are ordered by there ID (with gaps)

Table 1:

|-----|-----|-----------------|
| ID  |store|pallet_estimation|
|-----|-----|-----------------|
| 1   | A   | 35              |
| 2   | C   |  2              |
| 3   | B   | 30              |
|-----|-----|-----------------|

SELECT * FROM (
    VALUES (1, 'A', 35), (2, 'C', 2), (3, 'B', 30)
          ) T1(ID, store, pallet_estimation)

Table 2 :

|---------------|---------------|
|ID_staging_lane|pallet_capacity|
|---------------|---------------|
| 201           | 10            |
| 202           | 10            |
| 204           | 30            |
| 205           | 40            |
| 208           | 30            |
| 210           | 30            |
|---------------|---------------|

SELECT * FROM(
  VALUES (201, 10), (202, 10), (204, 30), (205, 40), (208, 30), (210, 30)
     ) T2(ID_staging_lane, pallet_capacity)

Expected result:

|-----------|--------|--------------------|---------------|------------------|
|T1_sequence|T1_store|T1_pallet_estimation|T2_staging_lane|T2_pallet_capacity|
|-----------|--------|--------------------|---------------|------------------|
| 1         | A      | 35                 | 201           | 10               |
| 1         | A      | 35                 | 202           | 10               |
| 1         | A      | 35                 | 204           | 30               |
| 2         | C      |  2                 | 205           | 40               |
| 3         | B      | 30                 | 208           | 30               |
|-----------|--------|--------------------|---------------|------------------|

Thanks you, Charles, for you time.
I'll try to improve my demand.

If needed, I want to split/divide the pallet_estimation on several staging lanes, following the sequence

Example:

For store A which has 35 pallets,
I want to use staging lane 201 then it remains 35 - 10 = 25 ,
then I want to use staging lane 202 then it remains 25 - 10 = 15,
then I want to use staging lane 204 then it remains 15 - 30 = -15

then I want to continue with the store C on the next staging lane 205 then it remains 2 - 40 = -38

then I want to continue with the store B on the next staging lane 208 then it remains 30 - 30 = 0

How would you start to build that ?
 - with window function ? SUM() OVER()
 - with recursive SQL ? DECLARE FETCH
 - is it possible to build a dynamic JOIN in SQL ?
 - other idea ?

Thanks in advance,

Renaud

Body:
First of all, v7r1 is very old...10 years to be exact...

Secondly, I don't understand what you're trying to join on...I see nothing that would explain why store A ended up with 3 rows in your results.

Thirdly, there's no such thing as a "dynamic join", in any RDBMS.  You can have a dyanmic statement, which could include a join.  Or you can have a static statement, which also could include a join.  For Db2 on the IBM i, it only matters if your incorporating the statement in an RPG/COLBOL program or an SQL stored procedure/function.

Now having said all that, let me introduce you to Common Table Expressions (CTE).  Basicaly the same as a Nested Table Expression (NTE) but IMO easier to follow and CTEs also can have a performance benefit over NTE on the i.

with T1 as (
  SELECT * FROM (
    VALUES (1, 'A', 35), (2, 'C', 2), (3, 'B', 30)
          ) T1(ID, store, pallet_estimation)
), T2 as (
SELECT * FROM(
  VALUES (201, 10), (202, 10), (204, 30), (205, 40), (208, 30), (210, 30)
     ) T2(ID_staging_lane, pallet_capacity)
), fitment as (
select T1.*, T2.*, row_number() OVER(partition by ID_STAGING_LANE) as rowNbr
from T1 join T2 on pallet_estimation <= pallet_capacity
)
select * from fitment where rowNbr = 1;

The with T1 as (<select statement>) is the common table expression; as is T2 and fitment.  The with keyword is only used for the First CTE.

The fitment CTE joins T1 and T2 based upon which estimate fits in the lane description, assigning a row_number to each possibility.  The final select takes the first fit for each lane.

The nice thing about CTE's is you can easily build them and see the results as you go along.  At any point you can add select * from MYCTE and see what you have so far.

Note that as shown, a CTE can reference another CTE.  (fitment reference both T1 and T2)

EDIT

The functions your need to use, to look forward or backwards in the result set are named LAG() and LEAD().  They are part of the OLAP functionality built into Db2 for i.  Unfortunately for you, they were added at 7.3.

You will need to roll your own version using a user defined function (UDF) that makes use what's known as the scatchpad to save data between the calls to the function for each row.

I found an very old article Scribble on SQL's Scratchpad showing how to the scratch pad in RPG.  You can also use it inside an SQL defined UDF.

Do a bit a googling to see if you can get started.  If you run into issues, create a new question here.  (or check out the Midrange mailing lists


答:
```<code>second_lowest = sorted(list(set(room.values())))[1]
names = [x for x in room if room[x]==second_lowest]
for name in names:
    print(f"name {name}")
</code>```

Explanation

[x for x in room] loops over the keys of the room dict.

set(room.values()) will make the scores unique.

sorted(list(set(room.values())))[1] will give you the second lowest score.

When put together in a list comprehension will give you the second lowest names.

Title: Errors in sorting a dictionary

Body:
second_lowest = sorted(list(set(room.values())))[1]
names = [x for x in room if room[x]==second_lowest]
for name in names:
    print(f"name {name}")

Explanation

[x for x in room] loops over the keys of the room dict.

set(room.values()) will make the scores unique.

sorted(list(set(room.values())))[1] will give you the second lowest score.

When put together in a list comprehension will give you the second lowest names.


答:
you can try np.apply_along_axis(function, axis=2, arr=your_input_array) which will slice the array along the 3rd axis and apply the function to each slice, i.e. point.

Find the doc here np.apply_along_axis

Title: What is the most efficient way to call a function on a 2D ndarray of coordinates?


问:
Creating Application for other enterprise to SSO and list directory users?
I am trying to create a web application. This app is a B2B PAS model.
One of the features of the app is, an organization using GSuite, can onboard our system and then all its users can log in to our software using their org's google ids. However, in the application, one user can assign task to another user in org. So our application should be able to list all users of the org too.

How can both these features be achieved?

I have tried the SAML approach, by creating a custom app from Gsuite admin console. However, can SAML be extended to also list users from the organizations which the SAML app belongs to? (Basically trying to use the Google Cloud Directory API)

What other alternative approaches should I look for if pure SAML doesn't work out?

P.S tech stack I'm using is Nest JS for backend and Angular for frontend

答:
If I am understanding properly you are looking for the way to populate all users/ID from  organization to your  SAML App. Single sign-on (SSO) allows users to sign in to enterprise cloud applications using their managed Google account credentials, more details here in set up your own custom SAML application. It is also possible to Set up SSO using 3rd party IdPs.

However, Google supports several industry standard protocols like OAuth 2.0, OpenID Connect 1.0 and SAML 2.0 for handling authentication, authorization, and single sign-on. You can take a look at authenticating corporate users in a hybrid environment for more details.


问:
fxml getController() returns null
I am newbie in JavaFX. Can anyone help me?

Here is my code

```<code>Stage stage = new Stage();

FXMLLoader loader = new FXMLLoader();
Parent root = (Parent) loader.load(getClass().getResource("FXMLMain.fxml").openStream());
FXMLMainController mainController = loader.getController();
mainController.setStage(stage);
stage.setScene(new Scene(root));
stage.show();

((Node) (event.getSource())).getScene().getWindow().hide();
</code>```

loader.getController() returns null

```<code>java.lang.NullPointerException
    at library.management.system.FXMLDocumentController.loginButtonAction(FXMLDocumentController.java:69)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
    at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1763)
    at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1651)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
    at javafx.event.Event.fireEvent(Event.java:204)
    at javafx.scene.Node.fireEvent(Node.java:8175)
    at javafx.scene.control.Button.fire(Button.java:185)
    at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
    at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:204)
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3746)
    at javafx.scene.Scene$MouseHandler.access$1800(Scene.java:3471)
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1695)
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2486)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:314)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:243)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:345)
    at com.sun.glass.ui.View.handleMouseEvent(View.java:526)
    at com.sun.glass.ui.View.notifyMouse(View.java:898)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.access$300(WinApplication.java:39)
    at com.sun.glass.ui.win.WinApplication$4$1.run(WinApplication.java:112)
    at java.lang.Thread.run(Thread.java:744)
</code>```

答:
I know my answer is late, but I will put to benefit anyone who will fall on this page after.

short answer:

change this:

```<code>FXMLLoader loader = new FXMLLoader();
Parent root = (Parent) loader.load(getClass().getResource("FXMLMain.fxml").openStream());
FXMLMainController mainController = loader.getController();
</code>```

to that:

```<code>FXMLLoader loader = new FXMLLoader(getClass().getResource("FXMLMain.fxml"));
Parent root = loader.load();
FXMLMainController mainController = loader.getController();
</code>```

Explaination:

The problem is that you are invoking the load() method (which is a static method) using an instance variable instead of the FXMLLoader class.
It is understandable that you need to use the instance so that you can invoke the getController() method. In this case, You should pass the URL (using getClass().getResource()) to the constructor of the FXMLLoader while you are creating your instance, then you can get the Parent root just by using the load() method.
Your order of method calls is correct so just as a reminder for other, remember that you need to call the load() method first before getController() or else it will return null

I ran into this problem before and this is how I solved it.

Title: fxml getController() returns null

Body:
I am newbie in JavaFX. Can anyone help me?

Here is my code

Stage stage = new Stage();

FXMLLoader loader = new FXMLLoader();
Parent root = (Parent) loader.load(getClass().getResource("FXMLMain.fxml").openStream());
FXMLMainController mainController = loader.getController();
mainController.setStage(stage);
stage.setScene(new Scene(root));
stage.show();

((Node) (event.getSource())).getScene().getWindow().hide();

loader.getController() returns null

java.lang.NullPointerException
    at library.management.system.FXMLDocumentController.loginButtonAction(FXMLDocumentController.java:69)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
    at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1763)
    at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1651)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
    at javafx.event.Event.fireEvent(Event.java:204)
    at javafx.scene.Node.fireEvent(Node.java:8175)
    at javafx.scene.control.Button.fire(Button.java:185)
    at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
    at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:204)
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3746)
    at javafx.scene.Scene$MouseHandler.access$1800(Scene.java:3471)
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1695)
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2486)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:314)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:243)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:345)
    at com.sun.glass.ui.View.handleMouseEvent(View.java:526)
    at com.sun.glass.ui.View.notifyMouse(View.java:898)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.access$300(WinApplication.java:39)
    at com.sun.glass.ui.win.WinApplication$4$1.run(WinApplication.java:112)
    at java.lang.Thread.run(Thread.java:744)

Body:
I know my answer is late, but I will put to benefit anyone who will fall on this page after.

short answer:

change this:

FXMLLoader loader = new FXMLLoader();
Parent root = (Parent) loader.load(getClass().getResource("FXMLMain.fxml").openStream());
FXMLMainController mainController = loader.getController();

to that:

FXMLLoader loader = new FXMLLoader(getClass().getResource("FXMLMain.fxml"));
Parent root = loader.load();
FXMLMainController mainController = loader.getController();

Explaination:

The problem is that you are invoking the load() method (which is a static method) using an instance variable instead of the FXMLLoader class.
It is understandable that you need to use the instance so that you can invoke the getController() method. In this case, You should pass the URL (using getClass().getResource()) to the constructor of the FXMLLoader while you are creating your instance, then you can get the Parent root just by using the load() method.
Your order of method calls is correct so just as a reminder for other, remember that you need to call the load() method first before getController() or else it will return null

I ran into this problem before and this is how I solved it.


问:
Regex to find/replace text of varying length
We are using a third-party proprietery software in our project. Between two major releases, the vendor decided to restrict access to one of the methods and provided an alternate method name with a different signature. Example as shown below

```<code>Object obj;

Old way: Method_A(obj);

New way: obj.Method_B();
</code>```

Is it possible to use regex with linux sed to do a find/replace?

Eg:

Method_A( abc ); ==> abc .Method_B();

Method_A( m ); ==> m .Method_B();

Method_A( xyz123 ); ==> xyz123 .Method_B();

This is what I have tried so far:

```<code>grep -R "Method_A(" . | sed -i 's/Method_A(^.{1,50}$/_____.Method_B(/g"
</code>```

No matter what I try to specify for _____, I am not able to achieve the desired result.

答:
You may use the following POSIX BRE sed regex:

```<code>sed 's/Method_A( \(.*\) );/\1.Method_B();/g'
</code>```

If you need to apply your 1 to 50 chars in between ( and ); use

```<code>sed 's/Method_A( \(.\{1,50\}\) );/\1.Method_B();/g'
</code>```

Details

Method_A(  - matches Method_A(  substring

\(.*\) - Capturing group 1 (referenced to with the \1 backreference in the replacement pattern part): any 0 or more chars, as many as possible

 ); - a  ); substring

See an online sed demo:

```<code>sed 's/Method_A( \(.*\) );/\1.Method_B();/g' <<< 'Method_A( abc );' # ==> abc.Method_B();
sed 's/Method_A( \(.*\) );/\1.Method_B();/g' <<< 'Method_A( m );' # ==> m.Method_B();
sed 's/Method_A( \(.*\) );/\1.Method_B();/g' <<< 'Method_A( xyz123 );' # ==> xyz123.Method_B();
</code>```

Body:
We are using a third-party proprietery software in our project. Between two major releases, the vendor decided to restrict access to one of the methods and provided an alternate method name with a different signature. Example as shown below

Object obj;

Old way: Method_A(obj);

New way: obj.Method_B();

Is it possible to use regex with linux sed to do a find/replace?

Eg:

Method_A( abc ); ==> abc .Method_B();

Method_A( m ); ==> m .Method_B();

Method_A( xyz123 ); ==> xyz123 .Method_B();

This is what I have tried so far:

grep -R "Method_A(" . | sed -i 's/Method_A(^.{1,50}$/_____.Method_B(/g"

No matter what I try to specify for _____, I am not able to achieve the desired result.

Body:
You may use the following POSIX BRE sed regex:

sed 's/Method_A( \(.*\) );/\1.Method_B();/g'

If you need to apply your 1 to 50 chars in between ( and ); use

sed 's/Method_A( \(.\{1,50\}\) );/\1.Method_B();/g'

Details

Method_A(  - matches Method_A(  substring

\(.*\) - Capturing group 1 (referenced to with the \1 backreference in the replacement pattern part): any 0 or more chars, as many as possible

 ); - a  ); substring

See an online sed demo:

sed 's/Method_A( \(.*\) );/\1.Method_B();/g' <<< 'Method_A( abc );' # ==> abc.Method_B();
sed 's/Method_A( \(.*\) );/\1.Method_B();/g' <<< 'Method_A( m );' # ==> m.Method_B();
sed 's/Method_A( \(.*\) );/\1.Method_B();/g' <<< 'Method_A( xyz123 );' # ==> xyz123.Method_B();


问:
cannot get folder from src/main/resources Java project Maven
I try to loop over all files in a certain folder in my resources (I added this folder myself in eclipse by doing new->folder). Whatever I try it keeps giving a null exception on the line where I try to get the folder. As I need to loop over its content getting it as a stream or something won't work.
I tried many approaches, but for example these two gave me the error:

```<code>File folder = new File(Thread.currentThread().getContextClassLoader().getResource("schematics").getPath());
</code>```

This wrapped inside a try catch did also not work:

```<code>File folder = new File(getClass().getClassLoader().getResource("schematics").toURI());
</code>```

My file structure (class where I try to access the schematics is HeavenStructureManager's initialiser):

EDIT
This project is a minecraft plugin, bundled to a jar by maven and run by the spigotmc minecraft jar. Their api provides a function getResource() but that gives a InputStream. As I would like to dynamically get all files inside a folder that does not work for me.
I unpacked my jar file to check where the schematic is, and it looked like this:

答:
Try using an absolute path:

```<code>getClass().getClassLoader().getResource("/schematics")
</code>```

When you use the getResource method, getResource will try to find the resource relative to the class package. Therefore, when you use the path ("schematics"), in reality, you are referring to the file at the location [resources]/com/ericdebouwer/heaven/schematics. By using a leading / getResource treats it as an absolute path.

Body:
I try to loop over all files in a certain folder in my resources (I added this folder myself in eclipse by doing new->folder). Whatever I try it keeps giving a null exception on the line where I try to get the folder. As I need to loop over its content getting it as a stream or something won't work.
I tried many approaches, but for example these two gave me the error:

File folder = new File(Thread.currentThread().getContextClassLoader().getResource("schematics").getPath());

This wrapped inside a try catch did also not work:

File folder = new File(getClass().getClassLoader().getResource("schematics").toURI());

My file structure (class where I try to access the schematics is HeavenStructureManager's initialiser):

EDIT
This project is a minecraft plugin, bundled to a jar by maven and run by the spigotmc minecraft jar. Their api provides a function getResource() but that gives a InputStream. As I would like to dynamically get all files inside a folder that does not work for me.
I unpacked my jar file to check where the schematic is, and it looked like this:

Body:
Try using an absolute path:

getClass().getClassLoader().getResource("/schematics")

When you use the getResource method, getResource will try to find the resource relative to the class package. Therefore, when you use the path ("schematics"), in reality, you are referring to the file at the location [resources]/com/ericdebouwer/heaven/schematics. By using a leading / getResource treats it as an absolute path.


问:
Why does fatal error “LNK1104: cannot open file 'C:\Program.obj'” occur when I compile a C++ project in Visual Studio? (2)
This is really a follow up to the original question with this title but I am too noob to be allowed to comment there (can you merge this in as a comment Mike ?)

I just spent around a day trying to work out why I was getting this problem when I cut and pasted the command line verbatim from VS 2010 into a batch file and tried to run it.

I put the full path to link.exe in an env var in the batch file called "link" and ran the command as:

"%link%" /VERBOSE ... yada yada yada

and got the error “LNK1104: cannot open file 'C:\Program.obj'”.

This is because %link% is used by VS 2010 link.exe as additional input for linking.

As my %link% var was the program FQN "C:\Program Files\Micro$ Visual Studio 10.0..." (i.e. contains spaces), the linker tried to include "C:\Program" (as the first space delimited string), and added a suffix of ".obj" because it assumed that is what I meant.

It then tried to include this spurious file as an input, failed to find it, and fell over.

Being more of a gcc man myself, this behaviour was unexpected to say the least.

The trivial solution was to use a different name for my command variable - eg %lcmd%

答: Windows quoting can be a royal pain because rather than being handled by the shell, it's handled by individual programs. You may need to include appropriate quotes in the definition of %link% itself.</p>


问:
ggbiplot worked previously with prcomp, now will not
ggbiplot used to work with no problems using prcomp but now does not.  All I receive is the following error code:

Error in plot_label(p = p, data = plot.data, label = label, label.label = label.label,  :
    Unsupported class: prcomp

I have installed ggbiplot using dependencies=TRUE and everything else other posts about similar issues have done but yet I still get this message.

Any help is appreciated.

```<code>mypca <- prcomp(mydata, center=TRUE, scale.=TRUE)
ggbiplot(mypca, center=TRUE, scale.=TRUE)
</code>```

Error in plot_label(p = p, data = plot.data, label = label, label.label = label.label,  :
    Unsupported class: prcomp

答:
Try,</p>

```<code>ggbiplot::ggbiplot(mypca)
</code>```

Body:
ggbiplot used to work with no problems using prcomp but now does not.  All I receive is the following error code:

Error in plot_label(p = p, data = plot.data, label = label, label.label = label.label,  :
    Unsupported class: prcomp

I have installed ggbiplot using dependencies=TRUE and everything else other posts about similar issues have done but yet I still get this message.

Any help is appreciated.

mypca <- prcomp(mydata, center=TRUE, scale.=TRUE)
ggbiplot(mypca, center=TRUE, scale.=TRUE)

Error in plot_label(p = p, data = plot.data, label = label, label.label = label.label,  :
    Unsupported class: prcomp

Body:
Try,

ggbiplot::ggbiplot(mypca)


问:
Setting data returned by useQuery as state
I have been using client.query to get data from my database and setting states using useState.

Here's an example:

```<code>const [videos, setVideos] = useState([]);

client.query({ query: GET_VIDEOS })
 .then(response => {
        setVideos(response.data.videos);
})
</code>```

However, this does not load 100% of the time. Usually, it doesn't load when I load the app for the first time in a while. I typically have to reboot in these situations.

This issue makes me want to look into useQuery instead of client.query.

However, the examples in the documentation only show how we can use useQuery to make direct changes in the components.

Example:

```<code>function Dogs({ onDogSelected }) {
  const { loading, error, data } = useQuery(GET_DOGS);

  if (loading) return 'Loading...';
  if (error) return `Error! ${error.message}`;

  return (
    <select name="dog" onChange={onDogSelected}>
      {data.dogs.map(dog => (
        <option key={dog.id} value={dog.breed}>
          {dog.breed}
        </option>
      ))}
    </select>
  );
}
</code>```

However, I don't want to make changes to the components right now. I would much rather query the data and then set the queried data as a state, using useState.

How would I best accomplish this? One idea that I had was to create a component that returns null but queries the data. It would look something like this:

```<code>function Videos() {
  const { loading, error, data } = useQuery(GET_VIDEOS);

  if (loading) return 'Loading...';
  if (error) return `Error! ${error.message}`;

  setVideos(data);

  return null;
}
</code>```

I was curious to hear what are best practices for such situations.

答:
react-apollo's useQuery has an onCompleted as one of its options, so you can use it like

```<code>const { loading, error } = useQuery(GET_VIDEOS, {
  onCompleted: (data) => setVideos(data)
});
</code>```

Body:
I have been using client.query to get data from my database and setting states using useState.

Here's an example:

const [videos, setVideos] = useState([]);

client.query({ query: GET_VIDEOS })
 .then(response => {
        setVideos(response.data.videos);
})

However, this does not load 100% of the time. Usually, it doesn't load when I load the app for the first time in a while. I typically have to reboot in these situations.

This issue makes me want to look into useQuery instead of client.query.

However, the examples in the documentation only show how we can use useQuery to make direct changes in the components.

Example:

function Dogs({ onDogSelected }) {
  const { loading, error, data } = useQuery(GET_DOGS);

  if (loading) return 'Loading...';
  if (error) return `Error! ${error.message}`;

  return (
    <select name="dog" onChange={onDogSelected}>
      {data.dogs.map(dog => (
        <option key={dog.id} value={dog.breed}>
          {dog.breed}
        </option>
      ))}
    </select>
  );
}

However, I don't want to make changes to the components right now. I would much rather query the data and then set the queried data as a state, using useState.

How would I best accomplish this? One idea that I had was to create a component that returns null but queries the data. It would look something like this:

function Videos() {
  const { loading, error, data } = useQuery(GET_VIDEOS);

  if (loading) return 'Loading...';
  if (error) return `Error! ${error.message}`;

  setVideos(data);

  return null;
}

I was curious to hear what are best practices for such situations.

Body:
react-apollo's useQuery has an onCompleted as one of its options, so you can use it like

const { loading, error } = useQuery(GET_VIDEOS, {
  onCompleted: (data) => setVideos(data)
});


问:
Submitting reCAPTCHA v2 with selenium and python - no form submit button
So I recently signed up with anti-captcha and have been testing with the https://github.com/ad-m/python-anticaptcha/blob/master/examples/recaptcha_selenium.py script.

I cannot get past a reCAPTCHA that has no submit button (hidden or visible) nor a clear way to submit for verification. I've used the anti-captcha firefox plugin, so I know it can be passed. But I am stuck at the point of doing this manually myself.

I thought this was going to be a helpful answer, but it doesn't go into depth. I am able to get the job.get_solution_response() token and enter it into the required textfield, but I cannot submit the "form."

Does anyone have success with this? I am also looking to do this in a headless version of the browser. Would a solution be different based on headless vs non-headless?

BTW, realtor(dot)com is the website I am having trouble with. If I am not aloud to post this site, please let me know so I can remove it.

答:
I went back into the source code of the site and found they are using a function as a callback for verification...

I saw that they are using a function called solvedCaptcha and injecting a variable name payload. So here is how I solved it:

NOTE: Make sure the driver is currently on the reCAPTCHA page.

```<code>driver.execute_async_script("var payload = '<enter the job.get_solution_response() here>'; solvedCaptcha(payload);")
</code>```

This async script then calls the page's verification and it reloads the blocked window.

NOTE: This CAPTCHA did not have a submit button and was not placed in a form. So using .submit() on an item within the driver would not work.

Body:
I went back into the source code of the site and found they are using a function as a callback for verification...

I saw that they are using a function called solvedCaptcha and injecting a variable name payload. So here is how I solved it:

NOTE: Make sure the driver is currently on the reCAPTCHA page.

driver.execute_async_script("var payload = '<enter the job.get_solution_response() here>'; solvedCaptcha(payload);")

This async script then calls the page's verification and it reloads the blocked window.

NOTE: This CAPTCHA did not have a submit button and was not placed in a form. So using .submit() on an item within the driver would not work.


问:
ORM Support for Handling Deadlocks
Do you know of any ORM tool that offers deadlock recovery? I know deadlocks are a bad thing but sometimes any system will suffer from it given the right amount of load. In Sql Server, the deadlock message says "Rerun the transaction" so I would suspect that rerunning a deadlock statement is a desirable feature on ORM's.</p>

答:
I had a quick look (no doubt you have too) and couldn't find anything suggesting that hibernate at least offers this. This is probably because ORMs consider this outside of the scope of the problem they are trying to solve.

If you are having issues with deadlocks certainly follow some of the suggestions posted here to try and resolve them. After that you just need to make sure all your database access code gets wrapped with something which can detect a deadlock and retry the transaction.

ContentLicense: CC BY-SA 2.5

Title: ORM Support for Handling Deadlocks


问:
Does flash play .avi or .mpg4 ? If yes, how?
How to load and play .avi or .mpg4 in Flash? Is that possible ?

-> This class can play .flv and also .mp4 .. but for .avi it shows error "Error #2044: Unhandled NetStatusEvent:. level=error, code=NetStream.Play.StreamNotFound"

```<code>package src {
    import flash.display.Sprite;
    import flash.media.Video;
    import flash.net.NetConnection;
    import flash.net.NetStream;
    import flash.events.Event;
    import flash.events.MouseEvent;

        public class vplayer extends Sprite{
            public var vid:Video = new Video(1920,1080);
            private var nc:NetConnection = new NetConnection();
            public var ns:NetStream;
            public var listener:Object = new Object();
            private var _duration:Number = 0;

            public function vplayer():void{
                addChild(vid);
                nc.connect(null);
                ns = new NetStream(nc);
                vid.attachNetStream(ns);
                listener.onMetaData = metaDataHandler;
                ns.client = listener;
                //customClient.onCuePoint = cuePointHandler;
            }
            public function playVideo00(vv:String):void{

                ns.play(vv);
            }
            public function stopVideo00():void{
                ns.close();
            }
            /*public function cuePointHandler(infoObject:Object):void {
                trace("cuePoint");
            }*/
            public function metaDataHandler(infoObject:Object):void {
                _duration = infoObject["duration"];
                trace (" Time:  " + infoObject["duration"]);
            }
            public function get duration00():Number {
                return _duration;
            }
        }
}
</code>```

.. any help ?

答:
File extension actually doesn't mean that much.  AVI, QuickTime, etc are container formats and the audio and video stream formats (ie, codecs) inside them can vary.  With some, the container format can vary, too.

The Flash Video article on Wikipedia summarizes things fairly well as far as what is playable in what version of Flash Player.

As far as playing video, you can either make your own player using FLVPlayback or use a common player like FlowPlayer.

Body:
How to load and play .avi or .mpg4 in Flash? Is that possible ?

-> This class can play .flv and also .mp4 .. but for .avi it shows error "Error #2044: Unhandled NetStatusEvent:. level=error, code=NetStream.Play.StreamNotFound"

package src {
    import flash.display.Sprite;
    import flash.media.Video;
    import flash.net.NetConnection;
    import flash.net.NetStream;
    import flash.events.Event;
    import flash.events.MouseEvent;

        public class vplayer extends Sprite{
            public var vid:Video = new Video(1920,1080);
            private var nc:NetConnection = new NetConnection();
            public var ns:NetStream;
            public var listener:Object = new Object();
            private var _duration:Number = 0;

            public function vplayer():void{
                addChild(vid);
                nc.connect(null);
                ns = new NetStream(nc);
                vid.attachNetStream(ns);
                listener.onMetaData = metaDataHandler;
                ns.client = listener;
                //customClient.onCuePoint = cuePointHandler;
            }
            public function playVideo00(vv:String):void{

                ns.play(vv);
            }
            public function stopVideo00():void{
                ns.close();
            }
            /*public function cuePointHandler(infoObject:Object):void {
                trace("cuePoint");
            }*/
            public function metaDataHandler(infoObject:Object):void {
                _duration = infoObject["duration"];
                trace (" Time:  " + infoObject["duration"]);
            }
            public function get duration00():Number {
                return _duration;
            }
        }
}

.. any help ?


问:
How do I access a git branch with a ':' in the name?
In recent months I have two PRs come at me with the branch names being 'foo:bar'. Whenever I do a git fetch --all, that branch is nowhere to be found. How can I get this branch to be on my local machine?

答:
That is an illegal branch name. You should look on github (or wherever these pull requests occurred) to see what happened here.

Note, however, that if you are managing pull requests correctly, it might be normal not to be able to find that branch because, if you're like me, you always delete that branch right after the merge anyway.


问:
How to create table or named array in R when I already have the cell values?
Given a dataframe such as:

df = data.frame(
  Bread=rep(c("White", "Wheat", "Rye"), each=4),
  Meat=rep(c("Ham", "Roast Beef", "Turkey", "Pastrami"), times=3),
  Price=rnorm(12)
)
df
#>    Bread       Meat      Price
#> 1  White        Ham  0.6428015
#> 2  White Roast Beef -0.4382468
#> 3  White     Turkey -0.9383151
#> 4  White   Pastrami  1.6069649
#> 5  Wheat        Ham -0.9898017
#> 6  Wheat Roast Beef  0.4567167
#> 7  Wheat     Turkey  0.9479741
#> 8  Wheat   Pastrami -0.5721409
#> 9    Rye        Ham  0.1234204
#> 10   Rye Roast Beef -1.1446393
#> 11   Rye     Turkey -2.8622073
#> 12   Rye   Pastrami -1.1646482
```

<p><sup>Created on 2020-06-02 by the reprex package (v0.3.0)</sup></p>

<p>I would like to make a table such as this but filled with the values.</p>

<pre class="lang-r prettyprint-override"><code>+-------+-----+--------+------------+----------+
|       | Ham | Turkey | Roast Beef | Pastrami |
+-------+-----+--------+------------+----------+
| White |     |        |            |          |
+-------+-----+--------+------------+----------+
| Wheat |     |        |            |          |
+-------+-----+--------+------------+----------+
| Rye   |     |        |            |          |
+-------+-----+--------+------------+----------+
</code>```

Afterwards, I'd like to add dimnames such as "Bread Type" and "Meat Selection."

I tried using spread, but I can't figure out how to turn the final dataframe into a table object.

tidyr::spread(df, Bread, Price)
#>         Meat        Rye      Wheat      White
#> 1        Ham  1.4325955  0.2399214 -1.3911592
#> 2   Pastrami  0.3127256  0.1133108  0.1940318
#> 3 Roast Beef -1.6286526  0.8210128 -0.4017497
#> 4     Turkey -0.8071035 -0.2611048 -0.9201723
```

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

答:
We can use pivot_wider with column_to_rownames from tibble

```<code>library(dplyr)
library(tibble)
library(tidyr)
df %>%
       pivot_wider(names_from = Meat, values_from = Price) %>%
       column_to_rownames('Bread') %>%
       as.matrix
#             Ham Roast Beef     Turkey    Pastrami
#White  0.3881185  0.2906277 -0.2855983  0.07601472
#Wheat -0.5602986  0.4471884  0.9085011 -0.50505960
#Rye   -0.3010040 -0.7260360 -1.1800770  0.25307471
</code>```

Or with acast

```<code>library(reshape2)
acast(df, Bread ~ Meat)
</code>```

Or with xtabs from base R

```<code>out <- xtabs(Price ~ Bread + Meat, df)
names(dimnames(out)) <- c("Bread Type", "Meat Selection")
out
#          Meat Selection
#Bread Type         Ham    Pastrami  Roast Beef      Turkey
#     Rye   -0.30100401  0.25307471 -0.72603598 -1.18007703
#     Wheat -0.56029860 -0.50505960  0.44718837  0.90850113
#     White  0.38811847  0.07601472  0.29062767 -0.28559829
</code>```

Body:
Given a dataframe such as:

df = data.frame(
  Bread=rep(c("White", "Wheat", "Rye"), each=4),
  Meat=rep(c("Ham", "Roast Beef", "Turkey", "Pastrami"), times=3),
  Price=rnorm(12)
)
df
#>    Bread       Meat      Price
#> 1  White        Ham  0.6428015
#> 2  White Roast Beef -0.4382468
#> 3  White     Turkey -0.9383151
#> 4  White   Pastrami  1.6069649
#> 5  Wheat        Ham -0.9898017
#> 6  Wheat Roast Beef  0.4567167
#> 7  Wheat     Turkey  0.9479741
#> 8  Wheat   Pastrami -0.5721409
#> 9    Rye        Ham  0.1234204
#> 10   Rye Roast Beef -1.1446393
#> 11   Rye     Turkey -2.8622073
#> 12   Rye   Pastrami -1.1646482

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

I would like to make a table such as this but filled with the values.

+-------+-----+--------+------------+----------+
|       | Ham | Turkey | Roast Beef | Pastrami |
+-------+-----+--------+------------+----------+
| White |     |        |            |          |
+-------+-----+--------+------------+----------+
| Wheat |     |        |            |          |
+-------+-----+--------+------------+----------+
| Rye   |     |        |            |          |
+-------+-----+--------+------------+----------+

Afterwards, I'd like to add dimnames such as "Bread Type" and "Meat Selection."

I tried using spread, but I can't figure out how to turn the final dataframe into a table object.

tidyr::spread(df, Bread, Price)
#>         Meat        Rye      Wheat      White
#> 1        Ham  1.4325955  0.2399214 -1.3911592
#> 2   Pastrami  0.3127256  0.1133108  0.1940318
#> 3 Roast Beef -1.6286526  0.8210128 -0.4017497
#> 4     Turkey -0.8071035 -0.2611048 -0.9201723

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

Body:
We can use pivot_wider with column_to_rownames from tibble

library(dplyr)
library(tibble)
library(tidyr)
df %>%
       pivot_wider(names_from = Meat, values_from = Price) %>%
       column_to_rownames('Bread') %>%
       as.matrix
#             Ham Roast Beef     Turkey    Pastrami
#White  0.3881185  0.2906277 -0.2855983  0.07601472
#Wheat -0.5602986  0.4471884  0.9085011 -0.50505960
#Rye   -0.3010040 -0.7260360 -1.1800770  0.25307471

Or with acast

library(reshape2)
acast(df, Bread ~ Meat)

Or with xtabs from base R

out <- xtabs(Price ~ Bread + Meat, df)
names(dimnames(out)) <- c("Bread Type", "Meat Selection")
out
#          Meat Selection
#Bread Type         Ham    Pastrami  Roast Beef      Turkey
#     Rye   -0.30100401  0.25307471 -0.72603598 -1.18007703
#     Wheat -0.56029860 -0.50505960  0.44718837  0.90850113
#     White  0.38811847  0.07601472  0.29062767 -0.28559829


问:
VBA count emails module!
This is a follow-up question of one which I posted yesterday. I feel I am getting quite close to creating a module in VBA that will count the number of e-mails sent on a particular day of the week. For the moment the day chosen is Monday.

However, the code is not yet working, and Outlook refuses to see the particular module.

I am sure there are a couple of errors in it. If someone could point these out, I would greatly appreciate it.

I also think that such code could be useful for others for future reference as the code for this kind of module does not seem to be readily available on the internet (I've looked!) and yet forms a type of search parameter that many will find useful!

```<code>Sub Count2(Optional dteDate As Date)
  Dim objOutlook As Object, objnSpace As Object, objFolder As Object
  Dim EmailCount As Integer
  Set objOutlook = CreateObject("Outlook.Application")
  Set objnSpace = objOutlook.GetNamespace("MAPI")

  On Error Resume Next

  Set objFolder = objnSpace.Folders("My Personal Emails").Folders("spam")
  If Err.Number <> 0 Then
    Err.Clear
    MsgBox "No such folder."
    Exit Sub
  End If

  Select Case Weekday(dteDate)
    Case vbMonday
      dteDate = Date
    End Select

  For Each MapiItem In MapiFolderInbox.Messages
    If MapiItem.TimeReceived = Date Then
      Count = Count + 1
      Next MapiItem
    End If

  EmailCount = objFolder.Items.Count
  Set objFolder = Nothing
  Set objnSpace = Nothing
  Set objOutlook = Nothing

  MsgBox "Number of emails in the folder: " _
    & EmailCount, , "Number of spam messages sent on a Monday: " & Count
End Sub
</code>```

答:
Outlook only sees the module when the parameters are left empty... as opposed to containing (Optional dteDate As Date).

Other than that, following the suggestion by Johan, the Module runs, but only ever has Count = 1. That is, that the result of emails received on a Monday is always 1 regardless of the input.

I also tried adbanginwar's suggestion, but in this case a compile error of 'Expected: Then or GoTo' is displayed.

Title: VBA count emails module!

Body:
This is a follow-up question of one which I posted yesterday. I feel I am getting quite close to creating a module in VBA that will count the number of e-mails sent on a particular day of the week. For the moment the day chosen is Monday.

However, the code is not yet working, and Outlook refuses to see the particular module.

I am sure there are a couple of errors in it. If someone could point these out, I would greatly appreciate it.

I also think that such code could be useful for others for future reference as the code for this kind of module does not seem to be readily available on the internet (I've looked!) and yet forms a type of search parameter that many will find useful!

Sub Count2(Optional dteDate As Date)
  Dim objOutlook As Object, objnSpace As Object, objFolder As Object
  Dim EmailCount As Integer
  Set objOutlook = CreateObject("Outlook.Application")
  Set objnSpace = objOutlook.GetNamespace("MAPI")

  On Error Resume Next

  Set objFolder = objnSpace.Folders("My Personal Emails").Folders("spam")
  If Err.Number <> 0 Then
    Err.Clear
    MsgBox "No such folder."
    Exit Sub
  End If

  Select Case Weekday(dteDate)
    Case vbMonday
      dteDate = Date
    End Select

  For Each MapiItem In MapiFolderInbox.Messages
    If MapiItem.TimeReceived = Date Then
      Count = Count + 1
      Next MapiItem
    End If

  EmailCount = objFolder.Items.Count
  Set objFolder = Nothing
  Set objnSpace = Nothing
  Set objOutlook = Nothing

  MsgBox "Number of emails in the folder: " _
    & EmailCount, , "Number of spam messages sent on a Monday: " & Count
End Sub


问:
PHP calculation returns NAN
I'm trying to perform some calculation on Data retrieved from database ,
but evertime I run this code I get  NAN as output.

```<code>function calculateNPS()
    {
        $queryTotal = "SELECT count(*) as total FROM message";
        $resullTotal = mysqli_query($link ,$queryTotal);

        $queryYes= "SELECT count(visit) as  yes FROM message WHERE visit='Yes'";
        $resultYes = mysqli_query($link ,$queryYes);

         $queryNo = "SELECT *count(visit) as no FROM message WHERE visit='No'";
        $resultNo = mysqli_query($link ,$queryNo);

        $yescount = mysqli_fetch_assoc($resultTotal);
        $nocount=mysqli_fetch_assoc($resultNo);
        $totalcount=mysqli_fetch_assoc($resultYes);

        $nps = ((float)($yescount['yes'])/(float)($totalcount['total'])*100)-((float)($nocount['no'])/(float)($totalcount['total'])*100);
        echo $nps;

}
</code>```

答:
Some numeric operations can result in a value represented by the constant NAN. This result represents an undefined or unrepresentable value in floating-point calculations. So it seems you have some problems with the values in the $nps calculation.

I would suggest that you try outputting/inspecting all the params, like $yescount or $yescount['yes'] to make sure you have valid data to start with. Then break your expression into shorter operations until you find the issue.

For instance, mysqli_fetch_assoc returns an associative array that corresponds to the fetched row or NULL if there are no more rows.

Also, in your queries you use $link but I can't see where it's coming from.

Title: PHP calculation returns NAN

Body:
I'm trying to perform some calculation on Data retrieved from database ,
but evertime I run this code I get  NAN as output.

function calculateNPS()
    {
        $queryTotal = "SELECT count(*) as total FROM message";
        $resullTotal = mysqli_query($link ,$queryTotal);

        $queryYes= "SELECT count(visit) as  yes FROM message WHERE visit='Yes'";
        $resultYes = mysqli_query($link ,$queryYes);

         $queryNo = "SELECT *count(visit) as no FROM message WHERE visit='No'";
        $resultNo = mysqli_query($link ,$queryNo);

        $yescount = mysqli_fetch_assoc($resultTotal);
        $nocount=mysqli_fetch_assoc($resultNo);
        $totalcount=mysqli_fetch_assoc($resultYes);

        $nps = ((float)($yescount['yes'])/(float)($totalcount['total'])*100)-((float)($nocount['no'])/(float)($totalcount['total'])*100);
        echo $nps;

}


问:
Docker: could not read CA certificate
I installed Docker on Windows 10 Pro and I can't get it to work.

When I try to run hello-world I get

```<code>could not read CA certificate
</code>```

It's looking for the certificates in the machine/machines/default . However that folder didn't exist.

I created a machine called "default" (which created the above mentioned folder) but that didn't help.

Before that I created another machine called "dev" which seems to have certificates, but that doesn't seem to be helping either.

Also there are certificate files in machine/machines - I don't know if I should somehow point Docker to look in that folder (instead of machine/machines/default) ?

I'm pretty new to Docker so I might be missing something. However I've been at this all day, read the Docker documentation, tried plenty of solutions and similar answers but nothing seems to be working.

答:
Environment variables hanging around from previously (long) removed Docker Toolbox installation caused this problem with Docker Desktop (which was started ok after HyperV. Removed them all, remove these environmental variables

DOCKER_TLS_VERIFY

DOCKER_CERT_PATH

DOCKER_HOST

DOCKER_TOOLBOX_INSTALL_PATH

, restart terminal, all working great now

Title: Docker: could not read CA certificate

Body:
I installed Docker on Windows 10 Pro and I can't get it to work.

When I try to run hello-world I get

could not read CA certificate

It's looking for the certificates in the machine/machines/default . However that folder didn't exist.

I created a machine called "default" (which created the above mentioned folder) but that didn't help.

Before that I created another machine called "dev" which seems to have certificates, but that doesn't seem to be helping either.

Also there are certificate files in machine/machines - I don't know if I should somehow point Docker to look in that folder (instead of machine/machines/default) ?

I'm pretty new to Docker so I might be missing something. However I've been at this all day, read the Docker documentation, tried plenty of solutions and similar answers but nothing seems to be working.


问:
How do I get the x64 Native Tools Developer Command Prompt for Visual Studio Community 2019?
I have a 64 bit Windows 10 and have installed the 2019 community edition Visual Studio. When I do a search for "x64" in Windows there is only an x86 developer command prompt and a PowerShell prompt.

What do I do to get the x64 developer command prompt for visual studio 2019?

答:
In my case it is named x64 Native Tools Command Prompt for VS 2019 and I can find it by the following sequence:

Press Windows key.

Release Windows key.

Type x64.

The following screen appears:

You can also find shortcuts for VS 2019 Command Prompts (x86/x64, Native/Cross) here:

```<code>C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Visual Studio 2019\Visual Studio Tools\VC
</code>```

If nothing is found here, then check whether VS 2019 is correctly installed.

Body:
In my case it is named x64 Native Tools Command Prompt for VS 2019 and I can find it by the following sequence:

Press Windows key.

Release Windows key.

Type x64.

The following screen appears:

You can also find shortcuts for VS 2019 Command Prompts (x86/x64, Native/Cross) here:

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Visual Studio 2019\Visual Studio Tools\VC

If nothing is found here, then check whether VS 2019 is correctly installed.


问:
node_modules - running the local copy instead of the global one
I have a node package that installed globally. With my current env set up, there are some conflicting issues but I was able to find a solution but I would like to change the bundled.js file for that library.

Instead, what I would like to do is install that package to the local project's directory and make the changes there only. However, when I try to do this, it seems like when I run the node module, it references the globally installed version of that package?

Is there a way where I can specify, when I run the package, to run off the local copy rather than the global one? Or am I going to have to delete the global one?

答: Just remove the global node_modules folder: C:\Users\username\node_modules