问:
How to acces to the B,G,R of an image with opencv in Python?
I would like to access to all R,G,B channels of my image, I wrote some code but it gives me just the R,G,B of one pixel even if I did an append...

I'm a beginner with Python so can you help me please?

Here's the code :

```<code>#coding: utf8
import numpy as np
import cv2
from imageio import imread

imgcolor = imread("/home/PATH/bougieHaut3.jpg")
rows,cols,rgb = imgcolor.shape
for i in range(rows):
    for j in range (cols):
        blue = imgcolor[i,j,0]
        B=[]
        B.append(blue)
        green = imgcolor[i,j,1]
        G=[]
        G.append(green)
        red = imgcolor[i,j,2]
        R=[]
        R.append(red)
print(B,G,R)
</code>```

Thank you so much for your help :) !

答:
You can define the invariant functions like:
import PIL
import math

```<code>def invariant_r(img):
  c1 = np.zeros((img_height, img_weight))
  for i in range(0, img_height):
    for j in range(0, img_weight):
      b = img[i,j,0]
      g = img[i,j,1]
      r = img[i,j,2]
      x = (r/max(g,b))
      c1[i][j]= math.atan(x)
  return c1

def invariant_g(img):
  c1 = np.zeros((img_height, img_weight))
  for i in range(0, img_height):
    for j in range(0, img_weight):
      b = img[i,j,0]
      g = img[i,j,1]
      r = img[i,j,2]
      x = (g/max(r,b))
      c1[i][j]= math.atan(x)
  return c1

def invariant_b(img):
  c1 = np.zeros((img_height, img_weight))
  for i in range(0, img_height):
    for j in range(0, img_weight):
      b = img[i,j,0]
      g = img[i,j,1]
      r = img[i,j,2]
      x = (b/max(r,g))
      c1[i][j]= math.atan(x)
  return c1
</code>```

And call them like:

```<code> r_img = invariant_r(img)
  g_img = invariant_g(img)
  b_img = invariant_b(img)
</code>```

After merging these values in an array, you have color invariant array.

Body:
I would like to access to all R,G,B channels of my image, I wrote some code but it gives me just the R,G,B of one pixel even if I did an append...

I'm a beginner with Python so can you help me please?

Here's the code :

#coding: utf8
import numpy as np
import cv2
from imageio import imread

imgcolor = imread("/home/PATH/bougieHaut3.jpg")
rows,cols,rgb = imgcolor.shape
for i in range(rows):
    for j in range (cols):
        blue = imgcolor[i,j,0]
        B=[]
        B.append(blue)
        green = imgcolor[i,j,1]
        G=[]
        G.append(green)
        red = imgcolor[i,j,2]
        R=[]
        R.append(red)
print(B,G,R)

Thank you so much for your help :) !

Body:
You can define the invariant functions like:
import PIL
import math

def invariant_r(img):
  c1 = np.zeros((img_height, img_weight))
  for i in range(0, img_height):
    for j in range(0, img_weight):
      b = img[i,j,0]
      g = img[i,j,1]
      r = img[i,j,2]
      x = (r/max(g,b))
      c1[i][j]= math.atan(x)
  return c1

def invariant_g(img):
  c1 = np.zeros((img_height, img_weight))
  for i in range(0, img_height):
    for j in range(0, img_weight):
      b = img[i,j,0]
      g = img[i,j,1]
      r = img[i,j,2]
      x = (g/max(r,b))
      c1[i][j]= math.atan(x)
  return c1

def invariant_b(img):
  c1 = np.zeros((img_height, img_weight))
  for i in range(0, img_height):
    for j in range(0, img_weight):
      b = img[i,j,0]
      g = img[i,j,1]
      r = img[i,j,2]
      x = (b/max(r,g))
      c1[i][j]= math.atan(x)
  return c1

And call them like:

 r_img = invariant_r(img)
  g_img = invariant_g(img)
  b_img = invariant_b(img)

After merging these values in an array, you have color invariant array.


来源: stackexchange

问:
Adam Optimizer is apparently not converging
I am trying to write a neural network in rust + arrayfire, and while gradient descent works, ADAM does not.

```<code>fn back_propagate(
    &mut self,
    signals: &Vec<Array<f32>>,
    labels: &Array<u8>,
    learning_rate_alpha: f64,
    batch_size: i32,
) {
    let mut output = signals.last().unwrap();
    let mut error = output - labels;

    for layer_index in (0..self.num_layers - 1).rev() {
        let signal = Self::add_bias(&signals[layer_index]);
        let deriv = self.layer_activations[layer_index].apply_deriv(output);

        let delta = &(deriv * error).T();

        let matmul = matmul(&delta, &signal, MatProp::NONE, MatProp::NONE);
        let gradient_t = (matmul / batch_size).T();

        match self.optimizer {
            Optimizer::GradientDescent => {
                let weight_update = learning_rate_alpha * gradient_t;
                self.weights[layer_index] -= weight_update;
            }
            Optimizer::Adam => {
                let exponents = constant(2f32, gradient_t.dims());

                self.first_moment_vectors[layer_index] = (&self.beta1[layer_index]
                    * &self.first_moment_vectors[layer_index])
                    + (&self.one_minus_beta1[layer_index] * &gradient_t);

                self.second_moment_vectors[layer_index] = (&self.beta2[layer_index]
                    * &self.second_moment_vectors[layer_index])
                    + (&self.one_minus_beta2[layer_index]
                        * arrayfire::pow(&gradient_t, &exponents, true));

                let corrected_first_moment_vector = &self.first_moment_vectors[layer_index]
                    / &self.one_minus_beta1[layer_index];

                let corrected_second_moment_vector = &self.second_moment_vectors[layer_index]
                    / &self.one_minus_beta2[layer_index];

                let denominator = sqrt(&corrected_second_moment_vector) + 1e-8;
                let weight_update =
                    learning_rate_alpha * (corrected_first_moment_vector / denominator);

                self.weights[layer_index] -= weight_update;
            }
        }

        output = &signals[layer_index];

        let err = matmulTT(
            &delta,
            &self.weights[layer_index],
            MatProp::NONE,
            MatProp::NONE,
        );

        error = index(&err, &[seq!(), seq!(1, output.dims()[1] as i32, 1)]);
    }
}
</code>```

I've stored beta1, beta2, 1-beta1, 1-beta2 in constant arrays for every layer just to avoid having to recompute them. It appears to have made no difference.

GradientDescent converges with a learning rate alpha=2.0, however with Adam, if i use alpha>~0.02, the network appears to get locked in. Funnily enough, if I remove all the hidden layers, it does work. Which tells me something, but I'm not sure what it is.

答: I figured it out, for anyone else, my alpha=0.01 is still too high, once I reduced it to 0.001, it converged very quickly</p>

ContentLicense: CC BY-SA 4.0

Body:
I am trying to write a neural network in rust + arrayfire, and while gradient descent works, ADAM does not.

fn back_propagate(
    &mut self,
    signals: &Vec<Array<f32>>,
    labels: &Array<u8>,
    learning_rate_alpha: f64,
    batch_size: i32,
) {
    let mut output = signals.last().unwrap();
    let mut error = output - labels;

    for layer_index in (0..self.num_layers - 1).rev() {
        let signal = Self::add_bias(&signals[layer_index]);
        let deriv = self.layer_activations[layer_index].apply_deriv(output);

        let delta = &(deriv * error).T();

        let matmul = matmul(&delta, &signal, MatProp::NONE, MatProp::NONE);
        let gradient_t = (matmul / batch_size).T();

        match self.optimizer {
            Optimizer::GradientDescent => {
                let weight_update = learning_rate_alpha * gradient_t;
                self.weights[layer_index] -= weight_update;
            }
            Optimizer::Adam => {
                let exponents = constant(2f32, gradient_t.dims());

                self.first_moment_vectors[layer_index] = (&self.beta1[layer_index]
                    * &self.first_moment_vectors[layer_index])
                    + (&self.one_minus_beta1[layer_index] * &gradient_t);

                self.second_moment_vectors[layer_index] = (&self.beta2[layer_index]
                    * &self.second_moment_vectors[layer_index])
                    + (&self.one_minus_beta2[layer_index]
                        * arrayfire::pow(&gradient_t, &exponents, true));

                let corrected_first_moment_vector = &self.first_moment_vectors[layer_index]
                    / &self.one_minus_beta1[layer_index];

                let corrected_second_moment_vector = &self.second_moment_vectors[layer_index]
                    / &self.one_minus_beta2[layer_index];

                let denominator = sqrt(&corrected_second_moment_vector) + 1e-8;
                let weight_update =
                    learning_rate_alpha * (corrected_first_moment_vector / denominator);

                self.weights[layer_index] -= weight_update;
            }
        }

        output = &signals[layer_index];

        let err = matmulTT(
            &delta,
            &self.weights[layer_index],
            MatProp::NONE,
            MatProp::NONE,
        );

        error = index(&err, &[seq!(), seq!(1, output.dims()[1] as i32, 1)]);
    }
}

I've stored beta1, beta2, 1-beta1, 1-beta2 in constant arrays for every layer just to avoid having to recompute them. It appears to have made no difference.

GradientDescent converges with a learning rate alpha=2.0, however with Adam, if i use alpha>~0.02, the network appears to get locked in. Funnily enough, if I remove all the hidden layers, it does work. Which tells me something, but I'm not sure what it is.


问:
Blazor WASM Load Data before Render Page
I would like to load some Data before I Render my Blazor Application because in depndency to the loaded data I would like to render my app (layout, navbar ...)

Now I want to use the OnInitialised method instead of OnInitialisedAsync and with no async and await keywords.

But now I had a problem to convert the data which I get back from my API.

```<code>protected override void OnInitialized()
    {
        try
        {   Console.WriteLine("Test1Mainasync");
            LoadCategories();
        }
        catch (Exception e)
        {

            jsRuntime.ToastrError(e.Message);
        }
    }

    private void LoadCategories()
    {

        IEnumerable<CategorieDTO> CategoriesInit1  = new List<CategorieDTO>();
        CategoriesInit1  =  categorieService.GetAllCategories();

        SD.Categories = CategoriesInit1.ToList();
        //foreach(var categorie in CategoriesInit){
        //    SD.Categories.Append(categorie);
        //}

        Console.WriteLine("Test1Main");

    }
</code>```

Has someone an idea why this converting issues happen?

答:
I think you have this method:

```<code>public async Task<IEnumerable<CategorieDTO>> GetAllCategories()
</code>```

and you should call it this way:

```<code>private async Task LoadCategories()
{
    IEnumerable<CategorieDTO> CategoriesInit1  = new List<CategorieDTO>();
    CategoriesInit1  = await  categorieService.GetAllCategories();

</code>```

and:

```<code>protected override async Task OnInitializedAsync()
{
    try
    {   Console.WriteLine("Test1Mainasync");
        await LoadCategories();
    }
</code>```

Body:
I would like to load some Data before I Render my Blazor Application because in depndency to the loaded data I would like to render my app (layout, navbar ...)

Now I want to use the OnInitialised method instead of OnInitialisedAsync and with no async and await keywords.

But now I had a problem to convert the data which I get back from my API.

protected override void OnInitialized()
    {
        try
        {   Console.WriteLine("Test1Mainasync");
            LoadCategories();
        }
        catch (Exception e)
        {

            jsRuntime.ToastrError(e.Message);
        }
    }

    private void LoadCategories()
    {

        IEnumerable<CategorieDTO> CategoriesInit1  = new List<CategorieDTO>();
        CategoriesInit1  =  categorieService.GetAllCategories();

        SD.Categories = CategoriesInit1.ToList();
        //foreach(var categorie in CategoriesInit){
        //    SD.Categories.Append(categorie);
        //}

        Console.WriteLine("Test1Main");

    }

Has someone an idea why this converting issues happen?

Body:
I think you have this method:

public async Task<IEnumerable<CategorieDTO>> GetAllCategories()

and you should call it this way:

private async Task LoadCategories()
{
    IEnumerable<CategorieDTO> CategoriesInit1  = new List<CategorieDTO>();
    CategoriesInit1  = await  categorieService.GetAllCategories();

and:

protected override async Task OnInitializedAsync()
{
    try
    {   Console.WriteLine("Test1Mainasync");
        await LoadCategories();
    }


问:
Run / Open VSCode from Mac Terminal
I'd like to run / open Visual Studio Code from the Mac OSX Terminal by running this command code ..  I found instructions here:

https://code.visualstudio.com/Docs/setup

Apparently I need to include this in my .bashrc file, so I did, but to no avail.

```<code>code () {
    if [[ $# = 0 ]]
    then
        open -a "Visual Studio Code"
    else
        [[ $1 = /* ]] && F="$1" || F="$PWD/${1#./}"
        open -a "Visual Studio Code" --args "$F"
    fi
}
</code>```

I edited the .bashrc file here:

~/.bashrc which points to /Users/username/.bashrc

Which .bashrc should I be editing?

答:
For macOS 12.0 and above:

Open profile in Notepad

open ~/.zshrc
```
<ol start="2">
<li>Create an alias for <code>code</code>, Paste below:</li>
</ol>
<pre class="lang-sh prettyprint-override"><code>alias code='open -a "Visual Studio Code"' # open file or folder in VSCode e.g. code ~/.zshrc
</code>```

Now you can open the current folder e.g. code . or any other file/folder by providing its path.

Profit

PS: You can add as many aliases as needed to open a file/folder with different editors. Just mention the editor's name in the alias. For example, open file/folder with sublime text:

alias subl='open -a "Sublime Text"' # open file or folder in sublime e.g. subl ~/.zshrc
```

And use it like subl .

ContentLicense: CC BY-SA 3.0

Title: Run / Open VSCode from Mac Terminal

Body:
I'd like to run / open Visual Studio Code from the Mac OSX Terminal by running this command code ..  I found instructions here:

https://code.visualstudio.com/Docs/setup

Apparently I need to include this in my .bashrc file, so I did, but to no avail.

code () {
    if [[ $# = 0 ]]
    then
        open -a "Visual Studio Code"
    else
        [[ $1 = /* ]] && F="$1" || F="$PWD/${1#./}"
        open -a "Visual Studio Code" --args "$F"
    fi
}

I edited the .bashrc file here:

~/.bashrc which points to /Users/username/.bashrc

Which .bashrc should I be editing?

Body:
For macOS 12.0 and above:

Open profile in Notepad

open ~/.zshrc

Create an alias for code, Paste below:

alias code='open -a "Visual Studio Code"' # open file or folder in VSCode e.g. code ~/.zshrc

Now you can open the current folder e.g. code . or any other file/folder by providing its path.

Profit

PS: You can add as many aliases as needed to open a file/folder with different editors. Just mention the editor's name in the alias. For example, open file/folder with sublime text:

alias subl='open -a "Sublime Text"' # open file or folder in sublime e.g. subl ~/.zshrc

And use it like subl .


问:
Cannot run NPM Commands
I've been using NPM on my machine (Windows 10), but recently ran into an issue. I currently have Node.js installed and get the following error while running any npm command.

Question: What is causing this error and whats the best way to resolve it.

Command:

```<code>$ npm install
</code>```

Output/Error:

```<code>bash: /c/Program Files/nodejs/npm: /bin/sh^M: bad interpreter: No such file or directory
</code>```

答: It happened to me just now and all I had to do was exiting my wsl2 session and login in again.</p>

Title: Cannot run NPM Commands

Body:
I've been using NPM on my machine (Windows 10), but recently ran into an issue. I currently have Node.js installed and get the following error while running any npm command.

Question: What is causing this error and whats the best way to resolve it.

Command:

$ npm install

Output/Error:

bash: /c/Program Files/nodejs/npm: /bin/sh^M: bad interpreter: No such file or directory


问:
in ipython how do I accept and use an autocomplete suggestion?
I'm using Python 3.8.9 with IPython 8.0.1 on macOS. When I type anything whatsoever, it displays a predicted suggestion based on past commands. Cool.

However, how do I actually accept that suggestion? I tried the obvious: tab, which does not accept the suggestion, but rather opens up a menu with different suggestions, while the original suggestion is still there (see screenshot).

I also tried space, and return, but both of those act as if the suggestion was never made. How the heck do I actually use the ipython autosuggestion? Or is tab supposed to work and something is wrong with my ipython build or something?

答: pressing the right arrow key on my keyboard was the only thing that worked. Kind of non-obvious.</p>


问:
How to get sorted dictionary from another one instead of a list
I have Dict ={'Deblai': [100, 1], 'Blocage': [10, 4], 'Beton de propreté': [50, 2]} dictionary and want to sort it based on the second element of the value which is a list.

I tried OrderedDict = sorted(Dict.items(), key=lambda x: x[1][1]) but it returns an ordered list instead of a dictionary.

This is what I expect :

```<code>OrderedDict = {('Deblai', [100, 1]), ('Beton de propreté', [50, 2]), ('Blocage', [10, 4])}
</code>```

How I can get a dictionary instead of list ?

答:
You can do it using dictionary comprehension like this:

```<code>unsorted_dct ={'Deblai': [100, 1], 'Blocage': [10, 4], 'Beton de propreté': [50, 2]}
sorted_dct = {k: v for k, v in sorted(unsorted_dct.items(), key=lambda item: item[1][1])}
print(sorted_dct)
</code>```

output:

```<code>{'Deblai': [100, 1], 'Beton de propreté': [50, 2], 'Blocage': [10, 4]}
</code>```

Body:
I have Dict ={'Deblai': [100, 1], 'Blocage': [10, 4], 'Beton de propreté': [50, 2]} dictionary and want to sort it based on the second element of the value which is a list.

I tried OrderedDict = sorted(Dict.items(), key=lambda x: x[1][1]) but it returns an ordered list instead of a dictionary.

This is what I expect :

OrderedDict = {('Deblai', [100, 1]), ('Beton de propreté', [50, 2]), ('Blocage', [10, 4])}

How I can get a dictionary instead of list ?

Body:
You can do it using dictionary comprehension like this:

unsorted_dct ={'Deblai': [100, 1], 'Blocage': [10, 4], 'Beton de propreté': [50, 2]}
sorted_dct = {k: v for k, v in sorted(unsorted_dct.items(), key=lambda item: item[1][1])}
print(sorted_dct)

output:

{'Deblai': [100, 1], 'Beton de propreté': [50, 2], 'Blocage': [10, 4]}


问:
How do I get codec_data from gstreamer's x264enc plugin?
I have custom code for an  RTMP server, and trying to add a gstreamer pipeline to transcode the incoming video and supply those to RTMP playback clients.  I have the following pipeline so far:

```<code>appsrc name=input !
    decodebin !
    videoscale ! video/x-raw,width=800,height=600 !
    x264enc speed-preset=veryfast name=encoder !
    appsink name=output
</code>```

In order for my appsink's h264 samples to be utilized I need to generate a sequence header packet with the codec data.  However, I can't find the codec data.

The caps for the x264enc step is:

"video/x-h264, stream-format=(string)byte-stream, alignment=(string)au, level=(string)3.2, profile=(string)high, width=(int)800, height=(int)600, pixel-aspect-ratio=(fraction)4/3, framerate=(fraction)60/1, interlace-mode=(string)progressive, colorimetry=(string)bt709, chroma-site=(string)mpeg2"

There's no codec_data caps there, which is how I passed it to appsrc so my h264 packets could be read.  How else do I get the codec data from gstream?

答: I was able to extract the codec_data by passing the x264enc output into h264parse.

Body:
I have custom code for an  RTMP server, and trying to add a gstreamer pipeline to transcode the incoming video and supply those to RTMP playback clients.  I have the following pipeline so far:

appsrc name=input !
    decodebin !
    videoscale ! video/x-raw,width=800,height=600 !
    x264enc speed-preset=veryfast name=encoder !
    appsink name=output

In order for my appsink's h264 samples to be utilized I need to generate a sequence header packet with the codec data.  However, I can't find the codec data.

The caps for the x264enc step is:

"video/x-h264, stream-format=(string)byte-stream, alignment=(string)au, level=(string)3.2, profile=(string)high, width=(int)800, height=(int)600, pixel-aspect-ratio=(fraction)4/3, framerate=(fraction)60/1, interlace-mode=(string)progressive, colorimetry=(string)bt709, chroma-site=(string)mpeg2"

There's no codec_data caps there, which is how I passed it to appsrc so my h264 packets could be read.  How else do I get the codec data from gstream?


问:
Python automatically converts the numerator and denominator of some fractions into big numbers. Why?
Here is an example:

```<code>x = frac(1,3)
x
Out[138]: Fraction(1, 3)
y = frac(5/39)
y
Out[140]: Fraction(288692283805801, 2251799813685248)
print(x+y)
3117876665102651/6755399441055744
x+y
Out[142]: Fraction(3117876665102651, 6755399441055744)
</code>```

Why is 5/39 automatically converted to 288692283805801/2251799813685248?
Using Python 3.7.8

答:
5/39 is a floating point number, that's not representable as 5/39 exactly. The fraction with large numerator and denominator is the rational that exactly represents the floating point number that approximates 5/39.

Try fractions.Fraction(5, 39) instead.

A similar example is given in the docs for the fractions module, with Fraction(1.1) not returning Fraction(11, 10) as one might naively expect. https://docs.python.org/3/library/fractions.html

Body:
Here is an example:

x = frac(1,3)
x
Out[138]: Fraction(1, 3)
y = frac(5/39)
y
Out[140]: Fraction(288692283805801, 2251799813685248)
print(x+y)
3117876665102651/6755399441055744
x+y
Out[142]: Fraction(3117876665102651, 6755399441055744)

Why is 5/39 automatically converted to 288692283805801/2251799813685248?
Using Python 3.7.8


问:
How to show RSS as pop-up?
On my website users can post comments on a document. Now I want to send an RSS feed to the webmasters when a comment is posted. I want the webmaster to be notified by a small pop-up in the right corner of the page. So this is what's happening:

User adds comment

system checks if webmaster is logged in

if webmaster is logged in; show pop-up in right corner with the title of the comment in it.

How to accomplish this?

答:
Unless you're using a comet style service to push notifictaions to the webmaster's browser, you're going to need to make a page that polls for new notifications at a pre-defined interval. You can then make an AJAX call to the service and parse the response on to a web page that only the webmaster has access to.

If you're interested in comet (services that can push data to the connected client), you can get a start at Wikipedia:

Comet (programming)

OwnerDisplayName: Martijn

Title: How to show RSS as pop-up?

OwnerDisplayName: Justin Niessner

ContentLicense: CC BY-SA 2.5


问:
Round up from .5 in a %
Ceiling rounds up no matter if you get .1, .3, .5, .7. or whatever the value is for the decimal.

I need to know how to only round up if you have .5.  So for example [number].5 round up.

Anyone know how to do this?

答:
```<code>Math.Round(number, MidpointRounding.AwayFromZero);
</code>```

Details and comparison with the default can be seen on the System.MidpointRounding page.

Title: Round up from .5 in a %

Body:
Math.Round(number, MidpointRounding.AwayFromZero);

Details and comparison with the default can be seen on the System.MidpointRounding page.


问:
How to restrict user from selecting past time in Flutter
For example if it's 16:00 then selecting 15:59 or some earlier time from the same day shouldn't be allowed.</p>

答:
This CustomTimerPicker provide hour and minute on callback, and we can provide initial TimeOfDay else it will use TimeOfDay.now().

Run on dartPad.

class CustomTimerPicker extends StatefulWidget {
  late final TimeOfDay intiTime;

  final Function(int selectedHour, int selectedMinute) onChanged;
  CustomTimerPicker({
    Key? key,
    required this.onChanged,
    TimeOfDay? intiTimeOfDay,
  }) : super(key: key) {
    intiTime = intiTimeOfDay ?? TimeOfDay.now();
  }

  @override
  State<CustomTimerPicker> createState() => _CustomTimerPickerState();
}

class _CustomTimerPickerState extends State<CustomTimerPicker> {
  late int selectedHour;
  late int selectedMinutes;

  @override
  void initState() {
    super.initState();
    selectedHour = widget.intiTime.hour;
    selectedMinutes = widget.intiTime.minute;
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        // hour picker
        SizedBox(
          width: kToolbarHeight,
          child: CupertinoPicker(
            // backgroundColor: Colors.cyanAccent, //bg Color
            itemExtent: 50,
            onSelectedItemChanged: (v) {
              setState(() {
                selectedHour = v + widget.intiTime.hour;
              });
              widget.onChanged(
                selectedHour,
                selectedMinutes,
              );
            },
            children: List.generate(
              24 - widget.intiTime.hour,
              (index) => Center(
                child: Text(
                  "${index + widget.intiTime.hour}",
                  textAlign: TextAlign.center,
                ),
              ),
            ),
          ),
        ),

        //minute Picker
        SizedBox(
          width: kToolbarHeight,
          child: CupertinoPicker(
            itemExtent: 50,
            onSelectedItemChanged: (v) {
              setState(() {
                selectedMinutes = v + widget.intiTime.minute;
              });
              widget.onChanged(
                selectedHour,
                selectedMinutes,
              );
            },
            children: List.generate(
              60 - widget.intiTime.minute,
              (index) => Center(
                child: Text(
                  "${index + widget.intiTime.minute}",
                  textAlign: TextAlign.center,
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }
}
```
<p>And use this widget providing height</p>
<pre class="lang-dart prettyprint-override"><code>SizedBox(
  height: 200,
  child: CustomTimerPicker(
    // intiTimeOfDay: TimeOfDay(hour: 3, minute: 4),
    onChanged: (selectedHour, selectedMinute) {
      setState(() {
        h = selectedHour;
        m = selectedMinute;
      });
      debugPrint("H: $selectedHour minute: $selectedMinute");
    },
  ),
),
</code>```

Body:
This CustomTimerPicker provide hour and minute on callback, and we can provide initial TimeOfDay else it will use TimeOfDay.now().

Run on dartPad.

class CustomTimerPicker extends StatefulWidget {
  late final TimeOfDay intiTime;

  final Function(int selectedHour, int selectedMinute) onChanged;
  CustomTimerPicker({
    Key? key,
    required this.onChanged,
    TimeOfDay? intiTimeOfDay,
  }) : super(key: key) {
    intiTime = intiTimeOfDay ?? TimeOfDay.now();
  }

  @override
  State<CustomTimerPicker> createState() => _CustomTimerPickerState();
}

class _CustomTimerPickerState extends State<CustomTimerPicker> {
  late int selectedHour;
  late int selectedMinutes;

  @override
  void initState() {
    super.initState();
    selectedHour = widget.intiTime.hour;
    selectedMinutes = widget.intiTime.minute;
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        // hour picker
        SizedBox(
          width: kToolbarHeight,
          child: CupertinoPicker(
            // backgroundColor: Colors.cyanAccent, //bg Color
            itemExtent: 50,
            onSelectedItemChanged: (v) {
              setState(() {
                selectedHour = v + widget.intiTime.hour;
              });
              widget.onChanged(
                selectedHour,
                selectedMinutes,
              );
            },
            children: List.generate(
              24 - widget.intiTime.hour,
              (index) => Center(
                child: Text(
                  "${index + widget.intiTime.hour}",
                  textAlign: TextAlign.center,
                ),
              ),
            ),
          ),
        ),

        //minute Picker
        SizedBox(
          width: kToolbarHeight,
          child: CupertinoPicker(
            itemExtent: 50,
            onSelectedItemChanged: (v) {
              setState(() {
                selectedMinutes = v + widget.intiTime.minute;
              });
              widget.onChanged(
                selectedHour,
                selectedMinutes,
              );
            },
            children: List.generate(
              60 - widget.intiTime.minute,
              (index) => Center(
                child: Text(
                  "${index + widget.intiTime.minute}",
                  textAlign: TextAlign.center,
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }
}

And use this widget providing height

SizedBox(
  height: 200,
  child: CustomTimerPicker(
    // intiTimeOfDay: TimeOfDay(hour: 3, minute: 4),
    onChanged: (selectedHour, selectedMinute) {
      setState(() {
        h = selectedHour;
        m = selectedMinute;
      });
      debugPrint("H: $selectedHour minute: $selectedMinute");
    },
  ),
),


问:
Python: while followed by elif
I thought else if and elif are logically identical.

But when I try elif after while, I get a syntax error.

However, else is OK after while, as shown here (see comments A & B):

```<code>MENU_COMMANDS = {
'goal': 'the objective of the game is .... ',
'close': 'exit menu',
'menu': 'show all menu commands',
'quit': 'quit game' }

GAME_KEYBOARD = {
'1': 1,
'2': 2 }

def turn1():
key = input("Player 1, make your move")  # == 'goal'

while key in MENU_COMMANDS:
    menu(key)
    key = input("after exiting the menu, make your move")
else:  # why not 'elif' ?    COMMENT A
    if key not in GAME_KEYBOARD:
        print("invalid move")
        return False

# elif key not in GAME_KEYBOARD:  # why won't this work? :(    COMMENT B
#     print("invalid move")
#     return False
</code>```

Is this the only way to execute this logic, or is there a better one?

Thank you!

答:
elif: ... is equivalent to else: if: ... in the context of an if block, but the else in a while block has an entirely different meaning from the else in an if block, so the two aren't interchangeable even though they're represented by the same keyword.

The else in this code block is unnecessary anyway:

```<code>while key in MENU_COMMANDS:
    menu(key)
    key = input("after exiting the menu, make your move")
else:  # why not 'elif' ?    COMMENT A
    if key not in GAME_KEYBOARD:
        print("invalid move")
        return False
</code>```

Since you never break your while, there's no circumstance under which you'd end the loop and not enter the else.  Hence you can just remove the else and it should behave the same:

```<code>while key in MENU_COMMANDS:
    menu(key)
    key = input("after exiting the menu, make your move")

if key not in GAME_KEYBOARD:
    print("invalid move")
    return False
</code>```

Title: Python: while followed by elif

Body:
I thought else if and elif are logically identical.

But when I try elif after while, I get a syntax error.

However, else is OK after while, as shown here (see comments A & B):

MENU_COMMANDS = {
'goal': 'the objective of the game is .... ',
'close': 'exit menu',
'menu': 'show all menu commands',
'quit': 'quit game' }

GAME_KEYBOARD = {
'1': 1,
'2': 2 }

def turn1():
key = input("Player 1, make your move")  # == 'goal'

while key in MENU_COMMANDS:
    menu(key)
    key = input("after exiting the menu, make your move")
else:  # why not 'elif' ?    COMMENT A
    if key not in GAME_KEYBOARD:
        print("invalid move")
        return False

# elif key not in GAME_KEYBOARD:  # why won't this work? :(    COMMENT B
#     print("invalid move")
#     return False

Is this the only way to execute this logic, or is there a better one?

Thank you!

Body:
elif: ... is equivalent to else: if: ... in the context of an if block, but the else in a while block has an entirely different meaning from the else in an if block, so the two aren't interchangeable even though they're represented by the same keyword.

The else in this code block is unnecessary anyway:

while key in MENU_COMMANDS:
    menu(key)
    key = input("after exiting the menu, make your move")
else:  # why not 'elif' ?    COMMENT A
    if key not in GAME_KEYBOARD:
        print("invalid move")
        return False

Since you never break your while, there's no circumstance under which you'd end the loop and not enter the else.  Hence you can just remove the else and it should behave the same:

while key in MENU_COMMANDS:
    menu(key)
    key = input("after exiting the menu, make your move")

if key not in GAME_KEYBOARD:
    print("invalid move")
    return False


问:
Iterating over an array of class objects VS a class object containing arrays
I want to create a program for multi-agent simulation and I am thinking about whether I should use NumPy or numba to accelerate the calculation. Basically, I would need a class to store the state of agents and I would have over a 1000 instances of this classes. In each time step, I will perform different calculation for all instances. There are two approaches that I am thinking of:

Numpy vectorization:

Having 1 class with multiple NumPy arrays for storing states of all agents. Hence, I will only have 1 class instance at all times during the simulation. With this approach, I can simply use NumPy vectorization to perform calculations. However, this will make running functions for specific agents difficult and I would need an extra class to store the index of each agent.

```<code>Class agent:
   def __init__(self):
      self.A = np.zeros(1000)
      self.B = np.zeros(1000)
   def timestep(self):
      return self.A + self.B
</code>```

Numba jitclass:

Using the numba jitclass decorator to compile the code. With this approach, I can apply more standard OOP formatted code as one class instance represent one agent. However, I am not sure about the performance of looping through multiple jitclass instance (say 1000 and more).

```<code>@jitclass
class agent:
   def __init__(self):
      self.A = 0
      self.B = 0
   def timestep(self):
      return self.A + self.B
</code>```

I would like to know which would be a faster approach.

答:
This problem is known as the "AoS VS SoA" where AoS means array of structures and SoA means structure of arrays. You can find some information about this here. SoA is less user-friendly than AoS but it is generally much more efficient. This is especially true when your code can benefit from using SIMD instructions. When you deal with many big array (eg. >=8 big arrays) or when you perform many scalar random memory accesses, then neither AoS nor SoA are efficient. In this case, the best solution is to use arrays of structure of small arrays (AoSoA) so to better use CPU caches while still being able benefit from SIMD. However, AoSoA is tedious as is complexity significantly the code for non trivial algorithms. Note that the number of fields that are accessed also matter in the choice of the best solution (eg. if only one field is frequently read, then SoA is perfect).

OOP is generally rather bad when it comes to performance partially because of this. Another reason is the frequent use of virtual calls and polymorphism while it is not always needed. OOP codes tends to cause a lot of cache misses and optimizing a large code that massively use OOP is often a mess (which sometimes results in rewriting a big part of the target software or the code being left very slow). To address this problem, data oriented design can be used. This approach has been successfully used to drastically speed up large code bases from video games (eg. Unity) to web browser renderers (eg. Chrome) and even relational databases. In high-performance computing (HPC), OOP is often barely used. Object-oriented design is quite related to the use of SoA rather than AoS so to better use cache and benefit from SIMD. For more information, please read this related post.

To conclude, I advise you to use the first code (SoA) in your case (since you only have two arrays and they are not so huge).

Body:
I want to create a program for multi-agent simulation and I am thinking about whether I should use NumPy or numba to accelerate the calculation. Basically, I would need a class to store the state of agents and I would have over a 1000 instances of this classes. In each time step, I will perform different calculation for all instances. There are two approaches that I am thinking of:

Numpy vectorization:

Having 1 class with multiple NumPy arrays for storing states of all agents. Hence, I will only have 1 class instance at all times during the simulation. With this approach, I can simply use NumPy vectorization to perform calculations. However, this will make running functions for specific agents difficult and I would need an extra class to store the index of each agent.

Class agent:
   def __init__(self):
      self.A = np.zeros(1000)
      self.B = np.zeros(1000)
   def timestep(self):
      return self.A + self.B

Numba jitclass:

Using the numba jitclass decorator to compile the code. With this approach, I can apply more standard OOP formatted code as one class instance represent one agent. However, I am not sure about the performance of looping through multiple jitclass instance (say 1000 and more).

@jitclass
class agent:
   def __init__(self):
      self.A = 0
      self.B = 0
   def timestep(self):
      return self.A + self.B

I would like to know which would be a faster approach.


问:
Flatten XML array to a single row in Snowflake
I have thousands of XML files which each have an array of key/value pairs. Like this:

<extras>
  <extra>
    <key>key_name_1</key>
    <value>value_1</value>
  </extra>
  <extra>
    <key>key_name_2</key>
    <value>value_2</value>
  </extra>
</extras>
```
<p>I need to be able to create a query that produces a single-row response for each XML file containing each of those values in a separated column named by the key. With MySQL, I was able to use extractvalue with XPath ('extras/extra[key="key_name_1"/value') for this, but with Snowflake I am not able to find a solution for this.</p>
<p>I have tried lateral flatten and then picking up the value from THIS array, but I haven't succeeded. It is probably something simple, but I am not able to find the solution.</p>
<h1>---Update---</h1>
<p>I could always use something like this:</p>
```XMLGET(XMLGET("xml_data", 'extras'):"$"[0], 'value'):"$"
```
<p>Unfortunately, all keys aren't always available making this useless.</p>
<p>Can it be that I have to do a UDF for this?</p>
<h1>--- Update 2 ---</h1>
<p>Got it working following way:</p>
<pre class="lang-sql prettyprint-override"><code>WITH Extra_1 AS (
    SELECT
        "id" as "id",
        XMLGET(extra.value, 'value'):"$" AS "value"
    FROM table,
        LATERAL FLATTEN(XMLGET("xml_data", 'extras'):"$") extra
    WHERE XMLGET(extra.value, 'key'):"$" = 'key_name_1'
),
WITH Extra_2 AS (
    SELECT
        "id" AS "id",
        XMLGET(extra.value, 'value'):"$" AS "value"
    FROM table,
        LATERAL FLATTEN(XMLGET("xml_data", 'extras'):"$") extra
    WHERE XMLGET(extra.value, 'key'):"$" = 'key_name_2'
)
SELECT
    "id",
    Extra_1."value" AS "key_name_1",
    Extra_2."value" AS "key_name_2",
FROM table
    JOIN Extra_1 ON Extra_1."id" = table."id";
    JOIN Extra_2 ON Extra_2."id" = table."id";
</code>```

Hopefully, someone has a simpler way to do this.

This is how easily it can be done in MySQL:

SELECT
    id,
    extractvalue( xml_data,'/extras/extra[key="key_name_1"]/value') AS key_name_1,
    extractvalue( xml_data,'/extras/extra[key="key_name_2"]/value') AS key_name_2
FROM table;
```

答:
Using FLATTEN and XMLGET:

```<code>CREATE OR REPLACE TABLE t
AS
SELECT 1 AS id, PARSE_XML('<extras>
  <extra>
    <key>key_name_1</key>
    <value>value_1</value>
  </extra>
  <extra>
    <key>key_name_2</key>
    <value>value_2</value>
  </extra>
</extras>') AS col_xml
UNION ALL
SELECT 2 AS id, PARSE_XML('<extras>
  <extra>
    <key>key_name_3</key>
    <value>value_3</value>
  </extra>
  <extra>
    <key>key_name_4</key>
    <value>value_4</value>
  </extra>
 <extra>
    <key>key_name_5</key>
    <value>value_5</value>
  </extra>
</extras>') AS col;
</code>```

Query:

```<code>SELECT id,
    XMLGET(s.VALUE,  'key'):"$"::STRING AS k
   ,XMLGET(s.VALUE,  'value'):"$"::STRING AS val
FROM t
,LATERAL FLATTEN(INPUT => t.col_xml:"$") s
WHERE GET(s.value, '@')::STRING='extra';
</code>```

Output:

Single row:

```<code>SELECT id
    ,GET(XMLGET(t.col_xml,  'extra', 0), '$')[0]:"$"::STRING AS key1
    ,GET(XMLGET(t.col_xml,  'extra', 0), '$')[1]:"$"::STRING AS value1
    ,GET(XMLGET(t.col_xml,  'extra', 1), '$')[0]:"$"::STRING AS key2
    ,GET(XMLGET(t.col_xml,  'extra', 1), '$')[1]:"$"::STRING AS value2
    ,GET(XMLGET(t.col_xml,  'extra', 2), '$')[0]:"$"::STRING AS key2
    ,GET(XMLGET(t.col_xml,  'extra', 2), '$')[1]:"$"::STRING AS value2
FROM t;
</code>```

Body:
I have thousands of XML files which each have an array of key/value pairs. Like this:

<extras>
  <extra>
    <key>key_name_1</key>
    <value>value_1</value>
  </extra>
  <extra>
    <key>key_name_2</key>
    <value>value_2</value>
  </extra>
</extras>

I need to be able to create a query that produces a single-row response for each XML file containing each of those values in a separated column named by the key. With MySQL, I was able to use extractvalue with XPath ('extras/extra[key="key_name_1"/value') for this, but with Snowflake I am not able to find a solution for this.

I have tried lateral flatten and then picking up the value from THIS array, but I haven't succeeded. It is probably something simple, but I am not able to find the solution.

---Update---

I could always use something like this:

XMLGET(XMLGET("xml_data", 'extras'):"$"[0], 'value'):"$"

Unfortunately, all keys aren't always available making this useless.

Can it be that I have to do a UDF for this?

--- Update 2 ---

Got it working following way:

WITH Extra_1 AS (
    SELECT
        "id" as "id",
        XMLGET(extra.value, 'value'):"$" AS "value"
    FROM table,
        LATERAL FLATTEN(XMLGET("xml_data", 'extras'):"$") extra
    WHERE XMLGET(extra.value, 'key'):"$" = 'key_name_1'
),
WITH Extra_2 AS (
    SELECT
        "id" AS "id",
        XMLGET(extra.value, 'value'):"$" AS "value"
    FROM table,
        LATERAL FLATTEN(XMLGET("xml_data", 'extras'):"$") extra
    WHERE XMLGET(extra.value, 'key'):"$" = 'key_name_2'
)
SELECT
    "id",
    Extra_1."value" AS "key_name_1",
    Extra_2."value" AS "key_name_2",
FROM table
    JOIN Extra_1 ON Extra_1."id" = table."id";
    JOIN Extra_2 ON Extra_2."id" = table."id";

Hopefully, someone has a simpler way to do this.

This is how easily it can be done in MySQL:

SELECT
    id,
    extractvalue( xml_data,'/extras/extra[key="key_name_1"]/value') AS key_name_1,
    extractvalue( xml_data,'/extras/extra[key="key_name_2"]/value') AS key_name_2
FROM table;

Body:
Using FLATTEN and XMLGET:

CREATE OR REPLACE TABLE t
AS
SELECT 1 AS id, PARSE_XML('<extras>
  <extra>
    <key>key_name_1</key>
    <value>value_1</value>
  </extra>
  <extra>
    <key>key_name_2</key>
    <value>value_2</value>
  </extra>
</extras>') AS col_xml
UNION ALL
SELECT 2 AS id, PARSE_XML('<extras>
  <extra>
    <key>key_name_3</key>
    <value>value_3</value>
  </extra>
  <extra>
    <key>key_name_4</key>
    <value>value_4</value>
  </extra>
 <extra>
    <key>key_name_5</key>
    <value>value_5</value>
  </extra>
</extras>') AS col;

Query:

SELECT id,
    XMLGET(s.VALUE,  'key'):"$"::STRING AS k
   ,XMLGET(s.VALUE,  'value'):"$"::STRING AS val
FROM t
,LATERAL FLATTEN(INPUT => t.col_xml:"$") s
WHERE GET(s.value, '@')::STRING='extra';

Output:

Single row:

SELECT id
    ,GET(XMLGET(t.col_xml,  'extra', 0), '$')[0]:"$"::STRING AS key1
    ,GET(XMLGET(t.col_xml,  'extra', 0), '$')[1]:"$"::STRING AS value1
    ,GET(XMLGET(t.col_xml,  'extra', 1), '$')[0]:"$"::STRING AS key2
    ,GET(XMLGET(t.col_xml,  'extra', 1), '$')[1]:"$"::STRING AS value2
    ,GET(XMLGET(t.col_xml,  'extra', 2), '$')[0]:"$"::STRING AS key2
    ,GET(XMLGET(t.col_xml,  'extra', 2), '$')[1]:"$"::STRING AS value2
FROM t;


问:
Change custom theme Material-UI
I am using Material-UI for a React project. However, I'm not sure as to how to apply a theme globally.

Here I have tried for individual components

import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';
import CardCommon from '../../common/card/CardCommon';

import purple from '@material-ui/core/colors/purple';
import Button from '@material-ui/core/Button';

import { Link } from 'react-router-dom';
//const primary = red[500]; // #F44336
import { Paths } from '../../../Routes';

const theme = createMuiTheme({
    palette: {
        primary: { main: purple[500] }, // Purple and green play nicely together.
        secondary: { main: '#11cb5f' }, // This is just green.A700 as hex.
    },
});
```

So how can I change the primary and secondary colors globally?

答:
In Material UI Version 5.4, the imports should be from from '@mui/material/styles';

```<code>import { ThemeProvider, createTheme } from '@mui/material/styles';
</code>```

Doc: https://mui.com/customization/theming/#api

Title: Change custom theme Material-UI

Body:
I am using Material-UI for a React project. However, I'm not sure as to how to apply a theme globally.

Here I have tried for individual components

import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';
import CardCommon from '../../common/card/CardCommon';

import purple from '@material-ui/core/colors/purple';
import Button from '@material-ui/core/Button';

import { Link } from 'react-router-dom';
//const primary = red[500]; // #F44336
import { Paths } from '../../../Routes';

const theme = createMuiTheme({
    palette: {
        primary: { main: purple[500] }, // Purple and green play nicely together.
        secondary: { main: '#11cb5f' }, // This is just green.A700 as hex.
    },
});

So how can I change the primary and secondary colors globally?

Body:
In Material UI Version 5.4, the imports should be from from '@mui/material/styles';

import { ThemeProvider, createTheme } from '@mui/material/styles';

Doc: https://mui.com/customization/theming/#api


问:
In Java, why does an assignment in parentheses not occur before the rest of the expression is evaluated?
Consider

```<code>int a = 20;
a = a + (a = 5); // a == 25, why not 10?
</code>```

Don't parentheses trump all precedence rules?  Are some variables on the RHS prepopulated before evaluation of certain expressions?

答:
You asked why and the latest JLS provides a clearer explanation of what is happening in JLS 17:

In particular, the presence or absence of parentheses around an
expression does not affect whether a variable is definitely assigned,
definitely assigned when true, definitely assigned when false,
definitely unassigned, definitely unassigned when true, or definitely
unassigned when false.

In effect they are saying that parentheses do not prompt assignment, which explains why assignment occurs left-to-right, unlike  evaluation, which occurs in innermost-to-outermost order.

But that still does not answer why.

It's not because of compatibility with Java's predecessor, at least not in its present form, because the behavior does not match C:

Java 17:

```<code>  int j = 3, k = 4, l = 5, m = 6, n = 7;

  System.out.println(((j = 3) + j) + j);       // 3 + 3 + 3   = 9
  System.out.println(k + (k + (k = 3)));       // 4 + 4 + 3   = 11
  System.out.println(l + ((l = 3) + l));       // 5 + 3 + 3   = 11
  System.out.println((m + (m += 3)) + m);      // 6 + 9 + 9   = 24
  System.out.println(n + (n += n / 2) + ++n);  // 7 + 11 + 12 = 28
</code>```

GCC 7.5.0:

```<code>  printf("%d\n",((j = 3) + j) + j);       // 3 + 3 + 3 = 9
  printf("%d\n",k + (k + (k = 3)));       // 3 + 3 + 3 = 9
  printf("%d\n",l + ((l = 3) + l));       // 3 + 3 + 3 = 9
  printf("%d\n",(m + (m += 3)) + m);      // 9 + 9 + 9 = 27
  printf("%d\n",n + (n += n / 2) + ++n);  // 10 + 10 + 11 = 31
</code>```

This leaves us with the explanation used elsewhere for Java awkwardness: upgradeability.   Java happened to do it this way at the time it was written; changing it to work in alignment with C would potentially break existing code.  I'd be curious to know of any discussion that  might have taken place when the initial design was decided.

Body:
Consider

int a = 20;
a = a + (a = 5); // a == 25, why not 10?

Don't parentheses trump all precedence rules?  Are some variables on the RHS prepopulated before evaluation of certain expressions?

Body:
You asked why and the latest JLS provides a clearer explanation of what is happening in JLS 17:

In particular, the presence or absence of parentheses around an
expression does not affect whether a variable is definitely assigned,
definitely assigned when true, definitely assigned when false,
definitely unassigned, definitely unassigned when true, or definitely
unassigned when false.

In effect they are saying that parentheses do not prompt assignment, which explains why assignment occurs left-to-right, unlike  evaluation, which occurs in innermost-to-outermost order.

But that still does not answer why.

It's not because of compatibility with Java's predecessor, at least not in its present form, because the behavior does not match C:

Java 17:

  int j = 3, k = 4, l = 5, m = 6, n = 7;

  System.out.println(((j = 3) + j) + j);       // 3 + 3 + 3   = 9
  System.out.println(k + (k + (k = 3)));       // 4 + 4 + 3   = 11
  System.out.println(l + ((l = 3) + l));       // 5 + 3 + 3   = 11
  System.out.println((m + (m += 3)) + m);      // 6 + 9 + 9   = 24
  System.out.println(n + (n += n / 2) + ++n);  // 7 + 11 + 12 = 28

GCC 7.5.0:

  printf("%d\n",((j = 3) + j) + j);       // 3 + 3 + 3 = 9
  printf("%d\n",k + (k + (k = 3)));       // 3 + 3 + 3 = 9
  printf("%d\n",l + ((l = 3) + l));       // 3 + 3 + 3 = 9
  printf("%d\n",(m + (m += 3)) + m);      // 9 + 9 + 9 = 27
  printf("%d\n",n + (n += n / 2) + ++n);  // 10 + 10 + 11 = 31

This leaves us with the explanation used elsewhere for Java awkwardness: upgradeability.   Java happened to do it this way at the time it was written; changing it to work in alignment with C would potentially break existing code.  I'd be curious to know of any discussion that  might have taken place when the initial design was decided.


问:
Remove strings begining with 'AUTO_INCREMENT=' in 2 files
I am trying to create a ruby script that loads 2 .sql files and removes all strings that begin with 'AUTO_INCREMENT='
There are multiple occurrences of this in my .sql files and all I want is them to be removed from both files.
Thanks for any help or input as I am new to ruby and decided to give it a try.</p>

答:
You should read up on IO, String, Array for more details on methods you can use.

Here's how you might read, modify, and save the contents of one file:

```<code># Opens a file for reading.
file = File.open("file1.txt")

# Reads all the contents into the string 'contents'.
contents = file.read
file.close

# Splits contents into an array of strings, one for each line.
lines = contents.split("\n")

# Delete any lines that start with AUTO_INCREMENT=
lines.reject! { |line| line =~ /^AUTO_INCREMENT=/ }

# Join the lines together into one string again.
new_contents = lines.join("\n")

# Open file for writing.
file = File.open("file1.txt", "w")

# Save new contents.
file.write(new_contents)
file.close
</code>```

Body:
You should read up on IO, String, Array for more details on methods you can use.

Here's how you might read, modify, and save the contents of one file:

# Opens a file for reading.
file = File.open("file1.txt")

# Reads all the contents into the string 'contents'.
contents = file.read
file.close

# Splits contents into an array of strings, one for each line.
lines = contents.split("\n")

# Delete any lines that start with AUTO_INCREMENT=
lines.reject! { |line| line =~ /^AUTO_INCREMENT=/ }

# Join the lines together into one string again.
new_contents = lines.join("\n")

# Open file for writing.
file = File.open("file1.txt", "w")

# Save new contents.
file.write(new_contents)
file.close


问:
How does Apache Cassandra perform on a single read of millions of records?
Much has been written about how Cassandra's redundancy provides good performance for thousands of incoming requests from different locations, but I haven't found anything on the throughput of a single big request.  That's what this question is about.

I am assessing Apache Cassandra's potential as a database solution to the following problem:

The client would be a single-server application with exclusive access to the Cassandra database, co-located in the same datacentre.  The Cassandra instance might be a few nodes, but likely not more than 5.

When a certain feature runs on the application (triggered occasionally by a human) it will populate Cassandra with up to 5M records representing short arrays of float data, as well as delete such records.  The records will not be updated and we never need to access individual elements of an array.  The arrays can be of different lengths, but will typically have around 100 elements, and each row might represent 0-20 arrays.

For example:

```<code>id   array1                  array2
123  [1.0, 2.5, ..., 10.8]   [0.0, 0.5, ..., 1.0]
</code>```

Bonus question: Should I use a list of doubles to represent this, or should I serialize the arrays to Json?

At some point the user requests a report and the server should read all 5M records, interpret the arrays, do some aggregation, and plot some data on the screen.  Might the read operation take <1s, <10s, <100s?  How can I estimate the throughput in this case, assuming it is the bottleneck?

答:
Let me start with your second use case, As your data is distributed across the nodes if you have a broad range query without having a narrowed down partition, Cassandra is going to perform slow.

Cassandra is well suitable for Querying and suitable for searching if
you know the partition key.

Even you are having a 5M records, Assuming this gets scattered around
5 different nodes, For your reporting use case Cassandra has to go
through all the nodes and aggregate it. Eventually it gets timed out.

This specific use case is not viable in Cassandra but if you can

aggregate in your service and make multiple calls to partition and

bucket. it is going to perform super fast.

Generally, the accessing pattern matters, Read wins. The data can be
formatted in any form but reading it wisely is matters to Cassandra.
So answered your second part. Thank you.

Body:
Much has been written about how Cassandra's redundancy provides good performance for thousands of incoming requests from different locations, but I haven't found anything on the throughput of a single big request.  That's what this question is about.

I am assessing Apache Cassandra's potential as a database solution to the following problem:

The client would be a single-server application with exclusive access to the Cassandra database, co-located in the same datacentre.  The Cassandra instance might be a few nodes, but likely not more than 5.

When a certain feature runs on the application (triggered occasionally by a human) it will populate Cassandra with up to 5M records representing short arrays of float data, as well as delete such records.  The records will not be updated and we never need to access individual elements of an array.  The arrays can be of different lengths, but will typically have around 100 elements, and each row might represent 0-20 arrays.

For example:

id   array1                  array2
123  [1.0, 2.5, ..., 10.8]   [0.0, 0.5, ..., 1.0]

Bonus question: Should I use a list of doubles to represent this, or should I serialize the arrays to Json?

At some point the user requests a report and the server should read all 5M records, interpret the arrays, do some aggregation, and plot some data on the screen.  Might the read operation take <1s, <10s, <100s?  How can I estimate the throughput in this case, assuming it is the bottleneck?


问:
WPF RadioButton groups in Xaml
In the WPF app we are building, we have 3 groups of RadioButtons in individual StackPanels side by side. We are trying to program the following behavior. When tabbing through the form, we don't want to tab through each of the radiobuttons (standard behavior), instead we would like to tab to the "first" radiobutton in each group and have the ability to arrow up/down to the other radiobuttons (list) in each group once we tab to the group. We have set the IsTabStop=False for the radiobuttons below each of the first radiobutton in the list. This gives us the desired behavior for tabbing through each group, but this does not allow for the ability to arrow up/down the list. The arrow up/down behavior only works if the IsTabStop=True. We also tried setting the GroupName attribute of the radiobutton, but the behavior is the same as described above. In the old win forms, there was a radiobutton list control that had this behavior and we are just trying to recreate it. Does anyone have any idea as to how to recreate this behavior? Thanks in advance for your help...!</p>

答:
I think the KeyboardNavigation attached properties will do the trick.

I mocked up a quick WPF example in XAML (sorry for the length), using ItemsControls to group the RadioButton elements:

```<code><Window
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"
  x:Class="Experiment.MainWindow"
  x:Name="Window"
  Title="MainWindow"
  Width="640" Height="480">

  <Grid x:Name="LayoutRoot">
    <Grid HorizontalAlignment="Left" Height="100" VerticalAlignment="Top" Width="100" Margin="91,139,0,0">
      <ItemsControl KeyboardNavigation.IsTabStop="False" KeyboardNavigation.TabNavigation="Once" KeyboardNavigation.DirectionalNavigation="Contained">
        <RadioButton Content="Alpha" KeyboardNavigation.TabIndex="2"/>
        <RadioButton Content="Delta" KeyboardNavigation.TabIndex="2"/>
        <RadioButton Content="Gamma" IsChecked="True" KeyboardNavigation.TabIndex="1"/>
        <RadioButton Content="Beta" KeyboardNavigation.TabIndex="2"/>
      </ItemsControl>
    </Grid>
    <Grid HorizontalAlignment="Left" Height="100" VerticalAlignment="Top" Width="100" Margin="244,139,0,0">
      <ItemsControl KeyboardNavigation.IsTabStop="False" KeyboardNavigation.TabNavigation="Once" KeyboardNavigation.DirectionalNavigation="Contained">
        <RadioButton x:Name="First" Content="Eenee" KeyboardNavigation.TabIndex="2"/>
        <RadioButton x:Name="Second" Content="Meenee" IsChecked="True" KeyboardNavigation.TabIndex="1"/>
        <RadioButton x:Name="Third" Content="Mynee" KeyboardNavigation.TabIndex="2"/>
        <RadioButton x:Name="Fourth" Content="Moe" KeyboardNavigation.TabIndex="2"/>
      </ItemsControl>
    </Grid>
    <Grid HorizontalAlignment="Left" Height="100" VerticalAlignment="Top" Width="100" Margin="391,139,0,0">
      <ItemsControl KeyboardNavigation.IsTabStop="False" KeyboardNavigation.TabNavigation="Once" KeyboardNavigation.DirectionalNavigation="Contained">
        <RadioButton Content="Extralarge" KeyboardNavigation.TabIndex="2"/>
        <RadioButton Content="Large" KeyboardNavigation.TabIndex="2"/>
        <RadioButton Content="Medium" KeyboardNavigation.TabIndex="2"/>
        <RadioButton Content="Small" IsChecked="True" KeyboardNavigation.TabIndex="1"/>
      </ItemsControl>
    </Grid>
  </Grid>
</Window>
</code>```

OwnerDisplayName: Scott

Title: WPF RadioButton groups in Xaml

Body:
I think the KeyboardNavigation attached properties will do the trick.

I mocked up a quick WPF example in XAML (sorry for the length), using ItemsControls to group the RadioButton elements:

<Window
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"
  x:Class="Experiment.MainWindow"
  x:Name="Window"
  Title="MainWindow"
  Width="640" Height="480">

  <Grid x:Name="LayoutRoot">
    <Grid HorizontalAlignment="Left" Height="100" VerticalAlignment="Top" Width="100" Margin="91,139,0,0">
      <ItemsControl KeyboardNavigation.IsTabStop="False" KeyboardNavigation.TabNavigation="Once" KeyboardNavigation.DirectionalNavigation="Contained">
        <RadioButton Content="Alpha" KeyboardNavigation.TabIndex="2"/>
        <RadioButton Content="Delta" KeyboardNavigation.TabIndex="2"/>
        <RadioButton Content="Gamma" IsChecked="True" KeyboardNavigation.TabIndex="1"/>
        <RadioButton Content="Beta" KeyboardNavigation.TabIndex="2"/>
      </ItemsControl>
    </Grid>
    <Grid HorizontalAlignment="Left" Height="100" VerticalAlignment="Top" Width="100" Margin="244,139,0,0">
      <ItemsControl KeyboardNavigation.IsTabStop="False" KeyboardNavigation.TabNavigation="Once" KeyboardNavigation.DirectionalNavigation="Contained">
        <RadioButton x:Name="First" Content="Eenee" KeyboardNavigation.TabIndex="2"/>
        <RadioButton x:Name="Second" Content="Meenee" IsChecked="True" KeyboardNavigation.TabIndex="1"/>
        <RadioButton x:Name="Third" Content="Mynee" KeyboardNavigation.TabIndex="2"/>
        <RadioButton x:Name="Fourth" Content="Moe" KeyboardNavigation.TabIndex="2"/>
      </ItemsControl>
    </Grid>
    <Grid HorizontalAlignment="Left" Height="100" VerticalAlignment="Top" Width="100" Margin="391,139,0,0">
      <ItemsControl KeyboardNavigation.IsTabStop="False" KeyboardNavigation.TabNavigation="Once" KeyboardNavigation.DirectionalNavigation="Contained">
        <RadioButton Content="Extralarge" KeyboardNavigation.TabIndex="2"/>
        <RadioButton Content="Large" KeyboardNavigation.TabIndex="2"/>
        <RadioButton Content="Medium" KeyboardNavigation.TabIndex="2"/>
        <RadioButton Content="Small" IsChecked="True" KeyboardNavigation.TabIndex="1"/>
      </ItemsControl>
    </Grid>
  </Grid>
</Window>


问:
Keyframes with Inline Styles ReactJS
I'm trying to set the keyframes of a pulsate animation in ReactJS. I tried just setting the keyframes inside the inline style but that doesn't work.

My code

```<code>const NewRelpyheButton = ({style = {}, open, handleOPenSettings}) => {

    var bar = {
    color: '#000',
    padding: '1em 0',
    fontSize: '20px',
    textAlign: 'center',
    cursor: 'pointer',
    position: 'fixed',
    bottom: '0',
    width: '100%',
    zIndex: '10',
    animation: 'pulse 1.2s ease-in-out',
    animationIterationCount: 'infinite',
    }

    Object.assign(style, {});
    let openModal;
    if (open) {
        openModal = <Modal><NewRelpyhe/></Modal>
    }

    return (
        <div>
        {openModal}
        <Bar color='purple' style={bar} onClick={handleOpenSettings}>
            create a new relphye site
        </Bar></div>
    )
}
</code>```

I'm trying to mimic this in css:

```<code>.element {
  width: 100%;
  height: 100%;
  animation: pulse 5s infinite;
}

@keyframes pulse {
  0% {
    background-color: #001F3F;
  }
  100% {
    background-color: #FF4136;
  }
}

html,
body {
  height: 100%;
}
</code>```

答:
Here's how we will achieve it without adding any dependency.

```<code>{/*Your Js File Code */}

import { StrictMode } from "react";
import ReactDOM from "react-dom";
import React from "react";
import "./test.css";

class Anim extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      animationName: ""
    };
  }

  addStylesheetRules(rules) {
    var styleEl = document.createElement("style");
    document.head.appendChild(styleEl);
    var styleSheet = styleEl.sheet;
    styleSheet.insertRule(rules, 0);
  }

  clickHdl() {
    let animationName = `animation${Math.round(Math.random() * 100)}`;
    let keyframes = `
    @-webkit-keyframes ${animationName} {
        10% {-webkit-transform:translate(${Math.random() * 300}px, ${
      Math.random() * 300
    }px)}
        90% {-webkit-transform:translate(${Math.random() * 300}px, ${
      Math.random() * 300
    }px)}
        100% {-webkit-transform:translate(${Math.random() * 300}px, ${
      Math.random() * 300
    }px)}
    }`;

    this.addStylesheetRules(keyframes);

    this.setState({
      animationName: animationName
    });
  }

  render() {
    let style = {
      animationName: this.state.animationName,
      animationTimingFunction: "ease-in-out",
      animationDuration: "0.6s",
      animationDelay: "0.0s",
      animationIterationCount: 1,
      animationDirection: "normal",
      animationFillMode: "forwards"
    };

    return (
      <div>
        <button type="button" onClick={this.clickHdl.bind(this)}>
          Animation!
        </button>
        <div className="box" style={style}></div>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(
  <StrictMode>
    <Anim />
  </StrictMode>,
  rootElement
);

{/*Css Code test.css */}

.box {
  width: 30px;
  height: 30px;
  background: red;
  border-radius: 50%;
  cursor: pointer;
}
</code>```

Demo: https://codesandbox.io/s/reverent-sun-qjo91?file=/src/index.js

Title: Keyframes with Inline Styles ReactJS

Body:
I'm trying to set the keyframes of a pulsate animation in ReactJS. I tried just setting the keyframes inside the inline style but that doesn't work.

My code

const NewRelpyheButton = ({style = {}, open, handleOPenSettings}) => {

    var bar = {
    color: '#000',
    padding: '1em 0',
    fontSize: '20px',
    textAlign: 'center',
    cursor: 'pointer',
    position: 'fixed',
    bottom: '0',
    width: '100%',
    zIndex: '10',
    animation: 'pulse 1.2s ease-in-out',
    animationIterationCount: 'infinite',
    }

    Object.assign(style, {});
    let openModal;
    if (open) {
        openModal = <Modal><NewRelpyhe/></Modal>
    }

    return (

        {openModal}
        <Bar color='purple' style={bar} onClick={handleOpenSettings}>
            create a new relphye site
        </Bar>

    )
}

I'm trying to mimic this in css:

.element {
  width: 100%;
  height: 100%;
  animation: pulse 5s infinite;
}

@keyframes pulse {
  0% {
    background-color: #001F3F;
  }
  100% {
    background-color: #FF4136;
  }
}

html,
body {
  height: 100%;
}

Body:
Here's how we will achieve it without adding any dependency.

{/*Your Js File Code */}

import { StrictMode } from "react";
import ReactDOM from "react-dom";
import React from "react";
import "./test.css";

class Anim extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      animationName: ""
    };
  }

  addStylesheetRules(rules) {
    var styleEl = document.createElement("style");
    document.head.appendChild(styleEl);
    var styleSheet = styleEl.sheet;
    styleSheet.insertRule(rules, 0);
  }

  clickHdl() {
    let animationName = `animation${Math.round(Math.random() * 100)}`;
    let keyframes = `
    @-webkit-keyframes ${animationName} {
        10% {-webkit-transform:translate(${Math.random() * 300}px, ${
      Math.random() * 300
    }px)}
        90% {-webkit-transform:translate(${Math.random() * 300}px, ${
      Math.random() * 300
    }px)}
        100% {-webkit-transform:translate(${Math.random() * 300}px, ${
      Math.random() * 300
    }px)}
    }`;

    this.addStylesheetRules(keyframes);

    this.setState({
      animationName: animationName
    });
  }

  render() {
    let style = {
      animationName: this.state.animationName,
      animationTimingFunction: "ease-in-out",
      animationDuration: "0.6s",
      animationDelay: "0.0s",
      animationIterationCount: 1,
      animationDirection: "normal",
      animationFillMode: "forwards"
    };

    return (
      <div>
        <button type="button" onClick={this.clickHdl.bind(this)}>
          Animation!
        </button>
        <div className="box" style={style}></div>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(
  <StrictMode>
    <Anim />
  </StrictMode>,
  rootElement
);

{/*Css Code test.css */}

.box {
  width: 30px;
  height: 30px;
  background: red;
  border-radius: 50%;
  cursor: pointer;
}

Demo: https://codesandbox.io/s/reverent-sun-qjo91?file=/src/index.js


问:
Not able to add JSON Data inside forEach loop using if condition on elements
Hi I am trying to add few conditional data from one JSON object to another.I am trying below code.Data is having JSON object.I am not getting any one in Data though i am getting correct value in Temp</p>
```<code>const userData= data.rows;
    const claimsB = claimsB;
    let Temp = '';
    let Data = '';
    userData.forEach((element) => {
        if (element.value.A == claimsB.B){
            Temp = element;
            Data += Temp;
        }
        console.log(Temp);
    });
   console.log(Data);
</code>```

答:
let Temp = ''; and let Data = ''; specify that both "Temp" and "Data" are declared as empty strings

Temp = element; is assigning the "element" object to "Temp" variable
At this point, type of "Temp" is converted to Object

Data += Temp; is trying to append an object to a string.
At this point, type of "Data" is still String

As per your statement, you expect "Data" to be a JSON object but that is not the case.
Hence, when you try to console.log(Data) at the end of your snippet, you might be seeing [object Object]... instead of a JSON object.

Suggestion:
Declare "Data" as an array and push conditionally matching elements to this.
Your code will look like this:

```<code>const userData= data.rows;
let Data = [];
userData.forEach((element) => {
    if (element.value.A == claimsB.B){
        Data.push(element);
    }
    console.log(Temp);
});
console.log(Data);
</code>```

Body:
Hi I am trying to add few conditional data from one JSON object to another.I am trying below code.Data is having JSON object.I am not getting any one in Data though i am getting correct value in Temp

const userData= data.rows;
    const claimsB = claimsB;
    let Temp = '';
    let Data = '';
    userData.forEach((element) => {
        if (element.value.A == claimsB.B){
            Temp = element;
            Data += Temp;
        }
        console.log(Temp);
    });
   console.log(Data);

Body:
let Temp = ''; and let Data = ''; specify that both "Temp" and "Data" are declared as empty strings

Temp = element; is assigning the "element" object to "Temp" variable
At this point, type of "Temp" is converted to Object

Data += Temp; is trying to append an object to a string.
At this point, type of "Data" is still String

As per your statement, you expect "Data" to be a JSON object but that is not the case.
Hence, when you try to console.log(Data) at the end of your snippet, you might be seeing [object Object]... instead of a JSON object.

Suggestion:
Declare "Data" as an array and push conditionally matching elements to this.
Your code will look like this:

const userData= data.rows;
let Data = [];
userData.forEach((element) => {
    if (element.value.A == claimsB.B){
        Data.push(element);
    }
    console.log(Temp);
});
console.log(Data);


问:
How to handle multiple path parameters in RestAssured?
We have a restAssured GET call:

```<code> public Response getRequest( final int survey_ID){
    httpRequest.header("Content-Type", ContentType.JSON);
    httpRequest.header("Authorization", System.getProperty("apiKey"));
    httpRequest.pathParams("survey_id", survey_ID);
    return httpRequest.get("/{survey_id}");
}
</code>```

Now there's new end-point which accepts multiple path parms like:

```<code> goals/check-enabled?survey_ids=54321,12345
</code>```

[Here Survey_ids could be 1 or many]

So, how could I handle this in my code?
I was thinking to implement something like below, but I suppose there could be a better way.

```<code>  public Response getRequest( final int[] survey_IDs){
    httpRequest.header("Content-Type", ContentType.JSON);
    httpRequest.header("Authorization",
    System.getProperty("apiKey"));
//        another Option
//        for(int survey_ID : survey_IDs){
//            httpRequest.pathParams("survey_id", survey_ID);
//        }
        return httpRequest.get("/{survey_ids}", survey_IDs);
    }
</code>```

Please suggest

Thanks a lot

答:
The URL example you give in the question, i.e., goals/check-enabled?survey_ids=54321,12345 shows survey_ids being a query parameter, not path parameter as you describe. A path parameter would be something like this: /items/{item_id}, where you need to pass the item id, for example, /items/2. Maybe you could try something like the below, as described here, for passing multiple values for a query parameter (which seems to be what you are looking for).

```<code>String survey_IDs= "54321,12345";
RestAssured.given().urlEncodingEnabled(false).
    contentType(ContentType.JSON).with().
    queryParam("survey_ids", survey_IDs).
    when().get("").then().statusCode(200).log().all();
</code>```

Body:
We have a restAssured GET call:

 public Response getRequest( final int survey_ID){
    httpRequest.header("Content-Type", ContentType.JSON);
    httpRequest.header("Authorization", System.getProperty("apiKey"));
    httpRequest.pathParams("survey_id", survey_ID);
    return httpRequest.get("/{survey_id}");
}

Now there's new end-point which accepts multiple path parms like:

 goals/check-enabled?survey_ids=54321,12345

[Here Survey_ids could be 1 or many]

So, how could I handle this in my code?
I was thinking to implement something like below, but I suppose there could be a better way.

  public Response getRequest( final int[] survey_IDs){
    httpRequest.header("Content-Type", ContentType.JSON);
    httpRequest.header("Authorization",
    System.getProperty("apiKey"));
//        another Option
//        for(int survey_ID : survey_IDs){
//            httpRequest.pathParams("survey_id", survey_ID);
//        }
        return httpRequest.get("/{survey_ids}", survey_IDs);
    }

Please suggest

Thanks a lot

Body:
The URL example you give in the question, i.e., goals/check-enabled?survey_ids=54321,12345 shows survey_ids being a query parameter, not path parameter as you describe. A path parameter would be something like this: /items/{item_id}, where you need to pass the item id, for example, /items/2. Maybe you could try something like the below, as described here, for passing multiple values for a query parameter (which seems to be what you are looking for).

String survey_IDs= "54321,12345";
RestAssured.given().urlEncodingEnabled(false).
    contentType(ContentType.JSON).with().
    queryParam("survey_ids", survey_IDs).
    when().get("").then().statusCode(200).log().all();


问:
Recording video from camera, overlaying bitmaps, adding audio, saving to the device all in as3/AIR mobile
I am tasked with recording a live video stream from the camera on a mobile device, then overlaying bitmaps that change over time, and adding an audio mp3 track to the video file, and then saving it to somewhere on the device like the Camera roll.

I saw a few posts that were helpful, mostly this one: AS3 Flash/AIR recording video with webcam and save it

But apparently, some have experienced app freezes on desktops. I can only imagine that on a mobile device it would be worse...

Also, how can I add the video info together with a separate audio mp3 into one file?

Has anyone accomplished something like this?

答:
Update, I got the video working. Kinda. I still get this error sometimes. Even with short videos.

```<code>Error #2030: End of file was encountered.
</code>```

Sometimes it works fine. But at least I'm able to record FLVs from components. I haven't done the audio addition yet.

To run this code, you'll need the FLVRecorder found here: http://www.joristimmerman.be/wordpress/2008/12/18/flvrecorder-record-to-flv-using-air/

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

```<code>        import mx.core.UIComponent;
        import mx.events.FlexEvent;
        private var file:File;
        private var recorder:FLVRecorder=FLVRecorder.getInstance()
        private var fps:uint = 10;
        private var timer:Timer;
        protected function viewnavigator1_creationCompleteHandler(event:FlexEvent):void
        {

            //              2. Define the target FLV-file’s properties, the file instance to your flv-file, width & height, framerate and the systemManager instance, that’s a Flash internal declared variable and the optional duration in seconds:
            file=File.desktopDirectory.resolvePath("recording.flv");
            recorder.setTarget(file,320,320,fps,systemManager)

            var camera : Camera = Camera.getCamera();

            if (camera)
            {
                var ui      : UIComponent   = new UIComponent();
                var video   : Video     = new Video(320, 320);

                camera.setMode(320, 320, 24.);

                video.attachCamera(camera);
                ui.addChild(video);
                cameraGroup.addElement(ui);
            }

            timer = new Timer(1000/fps);
            timer.addEventListener(TimerEvent.TIMER, captureScreen);
            timer.addEventListener(TimerEvent.TIMER_COMPLETE, stopRecording);

        }

        protected function stopRecording(event:Event):void
        {
            timer.stop();
            //when saving is done
            recorder.addEventListener(FLVRecorderEvent.FLV_CREATED, fileMade)
            //when saving starts
            recorder.addEventListener(FLVRecorderEvent.FLV_START_CREATION, startCreatingFLV)

            // TODO Auto-generated method stub
            recorder.stopRecording()

        }

        private function startCreatingFLV(e:FLVRecorderEvent):void{
            recorder.addEventListener(FLVRecorderEvent.PROGRESS,onFLVCreationProgress)
        }

        private function onFLVCreationProgress(e:FLVRecorderEvent):void{
            //e.progress: percent complete (0 to 1)
            //pbSaving: ProgressBar component in Flex
            trace("saving progress ", e.progress,1);
        }

        protected function captureScreen(event:TimerEvent):void
        {
            trace("captured screen");
            recorder.captureComponent(movieGroup)     //DisplayObject, takes a screenshot from that component

        }

        protected function startRecording(event:MouseEvent):void
        {
            // TODO Auto-generated method stub
            timer.start();
        }

        protected function fileMade(event:Event):void
        {
            trace("file made");
        }

    ]]>
</fx:Script>
<s:VGroup>
    <s:HGroup>
        <s:Button label="start" click="startRecording(event)"/>
        <s:Button label="stop" click="stopRecording(event)"/>
        <s:Label id="progress" text="waiting..."/>
    </s:HGroup>
    <s:Group id="movieGroup" width="50%" height="50%">
        <s:Group id="cameraGroup" width="100%" height="100%"/>
        <s:Image source="image.png" width="25%" height="25%"/>
    </s:Group>
</s:VGroup>
</code>```

Body:
Update, I got the video working. Kinda. I still get this error sometimes. Even with short videos.

Error #2030: End of file was encountered.

Sometimes it works fine. But at least I'm able to record FLVs from components. I haven't done the audio addition yet.

To run this code, you'll need the FLVRecorder found here: http://www.joristimmerman.be/wordpress/2008/12/18/flvrecorder-record-to-flv-using-air/

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

        import mx.core.UIComponent;
        import mx.events.FlexEvent;
        private var file:File;
        private var recorder:FLVRecorder=FLVRecorder.getInstance()
        private var fps:uint = 10;
        private var timer:Timer;
        protected function viewnavigator1_creationCompleteHandler(event:FlexEvent):void
        {

            //              2. Define the target FLV-file’s properties, the file instance to your flv-file, width & height, framerate and the systemManager instance, that’s a Flash internal declared variable and the optional duration in seconds:
            file=File.desktopDirectory.resolvePath("recording.flv");
            recorder.setTarget(file,320,320,fps,systemManager)

            var camera : Camera = Camera.getCamera();

            if (camera)
            {
                var ui      : UIComponent   = new UIComponent();
                var video   : Video     = new Video(320, 320);

                camera.setMode(320, 320, 24.);

                video.attachCamera(camera);
                ui.addChild(video);
                cameraGroup.addElement(ui);
            }

            timer = new Timer(1000/fps);
            timer.addEventListener(TimerEvent.TIMER, captureScreen);
            timer.addEventListener(TimerEvent.TIMER_COMPLETE, stopRecording);

        }

        protected function stopRecording(event:Event):void
        {
            timer.stop();
            //when saving is done
            recorder.addEventListener(FLVRecorderEvent.FLV_CREATED, fileMade)
            //when saving starts
            recorder.addEventListener(FLVRecorderEvent.FLV_START_CREATION, startCreatingFLV)

            // TODO Auto-generated method stub
            recorder.stopRecording()

        }

        private function startCreatingFLV(e:FLVRecorderEvent):void{
            recorder.addEventListener(FLVRecorderEvent.PROGRESS,onFLVCreationProgress)
        }

        private function onFLVCreationProgress(e:FLVRecorderEvent):void{
            //e.progress: percent complete (0 to 1)
            //pbSaving: ProgressBar component in Flex
            trace("saving progress ", e.progress,1);
        }

        protected function captureScreen(event:TimerEvent):void
        {
            trace("captured screen");
            recorder.captureComponent(movieGroup)     //DisplayObject, takes a screenshot from that component

        }

        protected function startRecording(event:MouseEvent):void
        {
            // TODO Auto-generated method stub
            timer.start();
        }

        protected function fileMade(event:Event):void
        {
            trace("file made");
        }

    ]]>
</fx:Script>
<s:VGroup>
    <s:HGroup>
        <s:Button label="start" click="startRecording(event)"/>
        <s:Button label="stop" click="stopRecording(event)"/>
        <s:Label id="progress" text="waiting..."/>
    </s:HGroup>
    <s:Group id="movieGroup" width="50%" height="50%">
        <s:Group id="cameraGroup" width="100%" height="100%"/>
        <s:Image source="image.png" width="25%" height="25%"/>
    </s:Group>
</s:VGroup>


问:
adding width to drawer in flutter
I want to be able to add width to this drawer because it takes up too much of the screen when open and I want to lessen the width a bit, is this possible and  how would I do this?

here is my scaffold

```<code>Widget build(BuildContext context) {
return new Scaffold(
  appBar: new AppBar(
    title: new Text("App Name"),
    centerTitle: true,
  ),
  body: new Center(
  ),

  drawer: Drawer(
  child: ListView(
      padding: EdgeInsets.zero,
      children: <Widget>[
      UserAccountsDrawerHeader(
        accountName: Text('Test123') ,
        accountEmail: Text('test@123.com'),
        currentAccountPicture: Image.network('https://images-wixmp-ed30a86b8c4ca887773594c2.wixmp.com/f/a89c3e38-b6f3-48a0-9f9e-df9a0129fb93/daghh5x-4a77b3ec-fd4f-4d17-9f84-5963a8cb5c03.png?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1cm46YXBwOjdlMGQxODg5ODIyNjQzNzNhNWYwZDQxNWVhMGQyNmUwIiwiaXNzIjoidXJuOmFwcDo3ZTBkMTg4OTgyMjY0MzczYTVmMGQ0MTVlYTBkMjZlMCIsIm9iaiI6W1t7InBhdGgiOiJcL2ZcL2E4OWMzZTM4LWI2ZjMtNDhhMC05ZjllLWRmOWEwMTI5ZmI5M1wvZGFnaGg1eC00YTc3YjNlYy1mZDRmLTRkMTctOWY4NC01OTYzYThjYjVjMDMucG5nIn1dXSwiYXVkIjpbInVybjpzZXJ2aWNlOmZpbGUuZG93bmxvYWQiXX0.dWTFMrwnbAbj5TtUp9U_vQsohW7MnkRPymzR5wZQoV8'),
        ),

        ListTile(
          title: Text('data'),
        ),
      ],
    ),
  ),
);
</code>```

答:
Before

After

Scaffold Drawer with Container or Sizeable widget

```<code>Container(
          width: 125,
          child: Drawer(
            child: ListView(
              // Important: Remove any padding from the ListView.
              padding: EdgeInsets.zero,
              children: [
                const DrawerHeader(
                  decoration: BoxDecoration(
                    color: Colors.blue,
                  ),
                  child: Text('Drawer Header'),
                ),
                ListTile(
                  title: const Text('google.com'),
                  onTap: () {
                    widget._controller!.loadUrl(
                        urlRequest: URLRequest(url: Uri.parse("www.google.com")));

                    // Update the state of the app.
                    // ...
                  },
                ),
                ListTile(
                  title: const Text('yahoo.com'),
                  onTap: () {
                    widget._controller!.loadUrl(
                        urlRequest: URLRequest(url: Uri.parse("www.yahoo.com")));
                    // ...
                  },
                ),
              ],
            ),
          ),
        )
</code>```

Title: adding width to drawer in flutter

Body:
I want to be able to add width to this drawer because it takes up too much of the screen when open and I want to lessen the width a bit, is this possible and  how would I do this?

here is my scaffold

Widget build(BuildContext context) {
return new Scaffold(
  appBar: new AppBar(
    title: new Text("App Name"),
    centerTitle: true,
  ),
  body: new Center(
  ),

  drawer: Drawer(
  child: ListView(
      padding: EdgeInsets.zero,
      children: <Widget>[
      UserAccountsDrawerHeader(
        accountName: Text('Test123') ,
        accountEmail: Text('test@123.com'),
        currentAccountPicture: Image.network('https://images-wixmp-ed30a86b8c4ca887773594c2.wixmp.com/f/a89c3e38-b6f3-48a0-9f9e-df9a0129fb93/daghh5x-4a77b3ec-fd4f-4d17-9f84-5963a8cb5c03.png?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1cm46YXBwOjdlMGQxODg5ODIyNjQzNzNhNWYwZDQxNWVhMGQyNmUwIiwiaXNzIjoidXJuOmFwcDo3ZTBkMTg4OTgyMjY0MzczYTVmMGQ0MTVlYTBkMjZlMCIsIm9iaiI6W1t7InBhdGgiOiJcL2ZcL2E4OWMzZTM4LWI2ZjMtNDhhMC05ZjllLWRmOWEwMTI5ZmI5M1wvZGFnaGg1eC00YTc3YjNlYy1mZDRmLTRkMTctOWY4NC01OTYzYThjYjVjMDMucG5nIn1dXSwiYXVkIjpbInVybjpzZXJ2aWNlOmZpbGUuZG93bmxvYWQiXX0.dWTFMrwnbAbj5TtUp9U_vQsohW7MnkRPymzR5wZQoV8'),
        ),

        ListTile(
          title: Text('data'),
        ),
      ],
    ),
  ),
);

Body:
Before

After

Scaffold Drawer with Container or Sizeable widget

Container(
          width: 125,
          child: Drawer(
            child: ListView(
              // Important: Remove any padding from the ListView.
              padding: EdgeInsets.zero,
              children: [
                const DrawerHeader(
                  decoration: BoxDecoration(
                    color: Colors.blue,
                  ),
                  child: Text('Drawer Header'),
                ),
                ListTile(
                  title: const Text('google.com'),
                  onTap: () {
                    widget._controller!.loadUrl(
                        urlRequest: URLRequest(url: Uri.parse("www.google.com")));

                    // Update the state of the app.
                    // ...
                  },
                ),
                ListTile(
                  title: const Text('yahoo.com'),
                  onTap: () {
                    widget._controller!.loadUrl(
                        urlRequest: URLRequest(url: Uri.parse("www.yahoo.com")));
                    // ...
                  },
                ),
              ],
            ),
          ),
        )


问:
How to upload an Image File modified by OpenCV using FileSystemStorage in Django?
I am taking an uploaded image from the user and then sending it to a YOLO model which then returns me an image.

I want to store that returned image in my Local Directory and then display it on the user interface.

This is the Code of views.py that takes in an image and sends it to the Yolo Model,

```<code>def predictImage(request):
    # print(request)
    # print(request.POST.dict())
    fileObj = request.FILES['filePath']
    fs = FileSystemStorage()
    filePathName = fs.save(fileObj.name, fileObj)
    filePathName = fs.url(filePathName)
    testimage = '.'+filePathName
    # img = image.load_img(testimage, target_size=(img_height, img_width))
    img = detect_image(testimage)
    filePathName = fs.save(fileObj.name + "_result", img) # -> HERE IS THE ERROR
    filePathName = fs.url(filePathName)
</code>```

This is the function of YOLO Model that uses OpenCV to read the image (Image is sent as argument to the function) and then returns that image,

```<code>import numpy as np
import cv2

def detect_image(img_path):

    confidenceThreshold = 0.5
    NMSThreshold = 0.3

    modelConfiguration = 'cfg/yolov3.cfg'
    modelWeights = 'yolov3.weights'

    labelsPath = 'coco.names'
    labels = open(labelsPath).read().strip().split('\n')

    np.random.seed(10)
    COLORS = np.random.randint(0, 255, size=(len(labels), 3), dtype="uint8")

    net = cv2.dnn.readNetFromDarknet(modelConfiguration, modelWeights)

    image = cv2.imread(img_path)
    (H, W) = image.shape[:2]

    #Determine output layer names
    layerName = net.getLayerNames()
    layerName = [layerName[i - 1] for i in net.getUnconnectedOutLayers()]

    blob = cv2.dnn.blobFromImage(image, 1 / 255.0, (416, 416), swapRB = True, crop = False)
    net.setInput(blob)
    layersOutputs = net.forward(layerName)

    boxes = []
    confidences = []
    classIDs = []

    for output in layersOutputs:
        for detection in output:
            scores = detection[5:]
            classID = np.argmax(scores)
            confidence = scores[classID]
            if confidence > confidenceThreshold:
                box = detection[0:4] * np.array([W, H, W, H])
                (centerX, centerY,  width, height) = box.astype('int')
                x = int(centerX - (width/2))
                y = int(centerY - (height/2))

                boxes.append([x, y, int(width), int(height)])
                confidences.append(float(confidence))
                classIDs.append(classID)

    #Apply Non Maxima Suppression
    detectionNMS = cv2.dnn.NMSBoxes(boxes, confidences, confidenceThreshold, NMSThreshold)

    if(len(detectionNMS) > 0):
        for i in detectionNMS.flatten():
            (x, y) = (boxes[i][0], boxes[i][1])
            (w, h) = (boxes[i][2], boxes[i][3])

            color = [int(c) for c in COLORS[classIDs[i]]]
            cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
            text = '{}: {:.4f}'.format(labels[classIDs[i]], confidences[i])
            cv2.putText(image, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)

    return image

    #cv2.imshow('Image', image)
    #cv2.waitKey(0)
</code>```

On this line,

```<code>filePathName = fs.save(fileObj.name + "_result", img)
</code>```

I am getting this following error,

```<code>'numpy.ndarray' object has no attribute 'read'
</code>```

I am not sure how can I resolve this. I tried searching how can I store OpenCV Modified file usnig FileSystemStorage but found nothing of help. Can anyone help me regarding this?

答:
You can use the imwrite function of cv2 library to store your files in the local directory, i.e.,

In your case, simply do this:

```<code>img = detect_image(testimage)
cv2.imwrite(fileObj.name+"_result.jpg", img=img)
</code>```

Body:
I am taking an uploaded image from the user and then sending it to a YOLO model which then returns me an image.

I want to store that returned image in my Local Directory and then display it on the user interface.

This is the Code of views.py that takes in an image and sends it to the Yolo Model,

def predictImage(request):
    # print(request)
    # print(request.POST.dict())
    fileObj = request.FILES['filePath']
    fs = FileSystemStorage()
    filePathName = fs.save(fileObj.name, fileObj)
    filePathName = fs.url(filePathName)
    testimage = '.'+filePathName
    # img = image.load_img(testimage, target_size=(img_height, img_width))
    img = detect_image(testimage)
    filePathName = fs.save(fileObj.name + "_result", img) # -> HERE IS THE ERROR
    filePathName = fs.url(filePathName)

This is the function of YOLO Model that uses OpenCV to read the image (Image is sent as argument to the function) and then returns that image,

import numpy as np
import cv2

def detect_image(img_path):

    confidenceThreshold = 0.5
    NMSThreshold = 0.3

    modelConfiguration = 'cfg/yolov3.cfg'
    modelWeights = 'yolov3.weights'

    labelsPath = 'coco.names'
    labels = open(labelsPath).read().strip().split('\n')

    np.random.seed(10)
    COLORS = np.random.randint(0, 255, size=(len(labels), 3), dtype="uint8")

    net = cv2.dnn.readNetFromDarknet(modelConfiguration, modelWeights)

    image = cv2.imread(img_path)
    (H, W) = image.shape[:2]

    #Determine output layer names
    layerName = net.getLayerNames()
    layerName = [layerName[i - 1] for i in net.getUnconnectedOutLayers()]

    blob = cv2.dnn.blobFromImage(image, 1 / 255.0, (416, 416), swapRB = True, crop = False)
    net.setInput(blob)
    layersOutputs = net.forward(layerName)

    boxes = []
    confidences = []
    classIDs = []

    for output in layersOutputs:
        for detection in output:
            scores = detection[5:]
            classID = np.argmax(scores)
            confidence = scores[classID]
            if confidence > confidenceThreshold:
                box = detection[0:4] * np.array([W, H, W, H])
                (centerX, centerY,  width, height) = box.astype('int')
                x = int(centerX - (width/2))
                y = int(centerY - (height/2))

                boxes.append([x, y, int(width), int(height)])
                confidences.append(float(confidence))
                classIDs.append(classID)

    #Apply Non Maxima Suppression
    detectionNMS = cv2.dnn.NMSBoxes(boxes, confidences, confidenceThreshold, NMSThreshold)

    if(len(detectionNMS) > 0):
        for i in detectionNMS.flatten():
            (x, y) = (boxes[i][0], boxes[i][1])
            (w, h) = (boxes[i][2], boxes[i][3])

            color = [int(c) for c in COLORS[classIDs[i]]]
            cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
            text = '{}: {:.4f}'.format(labels[classIDs[i]], confidences[i])
            cv2.putText(image, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)

    return image

    #cv2.imshow('Image', image)
    #cv2.waitKey(0)

On this line,

filePathName = fs.save(fileObj.name + "_result", img)

I am getting this following error,

'numpy.ndarray' object has no attribute 'read'

I am not sure how can I resolve this. I tried searching how can I store OpenCV Modified file usnig FileSystemStorage but found nothing of help. Can anyone help me regarding this?

Body:
You can use the imwrite function of cv2 library to store your files in the local directory, i.e.,

In your case, simply do this:

img = detect_image(testimage)
cv2.imwrite(fileObj.name+"_result.jpg", img=img)


问:
Can't read swagger JSON file on ASP.NET Core 1.2 Application after hosting into local IIS
After hosting my asp.net core 1.2 application, I am getting an error as:

swagger is unable to find the swagger.json file.

I have tried to solve the problem by giving a virtual path name app.UseSwaggerUI() but it's not working.

Edit to clarify question based on comments:

After hosting Asp.net core application in IIS, the swagger.json file is generating on localhost:<random_port>/swagger/v1/swagger.json path.

How do I serve the swagger.json file on a custom route like:
localhost:<random_port>/virtualpathname/swagger/v1/swagger.json

I have tried to set a virtual path in app.UseSwaggerUI() like {virtualpathname}/swagger/v2/swagger.json but still it is not working

答:
I happened to have a simple copy paste mistake!
see the first line in below code, the if statement env.IsDevelopment() is causing this section to not run when deployed to IIS. One option is to comment it out!</p>
```<code>
     //if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                    app.UseSwagger(c =>
                    {
                        c.RouteTemplate = "swagger/{documentName}/swagger.json";
                    });
                    app.UseSwaggerUI(c => {
                        c.RoutePrefix = "swagger";
                        c.SwaggerEndpoint("/swagger/v1/swagger.json", "StockOps.WebAPI v1");
                    });
                }

</code>```

Body:
I happened to have a simple copy paste mistake!
see the first line in below code, the if statement env.IsDevelopment() is causing this section to not run when deployed to IIS. One option is to comment it out!

     //if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                    app.UseSwagger(c =>
                    {
                        c.RouteTemplate = "swagger/{documentName}/swagger.json";
                    });
                    app.UseSwaggerUI(c => {
                        c.RoutePrefix = "swagger";
                        c.SwaggerEndpoint("/swagger/v1/swagger.json", "StockOps.WebAPI v1");
                    });
                }


问:
Is there a SUBSTR alternative in Oracle SQL
I'm trying to extract the the different sub-strings within one string. The I want different strings for every string divided by the dash (-) symbol.

I have tried using the SUBSTR position function. It does not work since sometimes there are 4 chars in the second sub string, therefore, the 3rd sub string is not correct.

```<code>SELECT SUBSTR(STR, INSTR (STR, '-', -1)+ 1)

STR = F-123-A123-B12 or F-1234-A123-B12
</code>```

I am trying to get a query that will give me F.

I need another query that will give me 123 or 1234 if there are 4 chars

I need another query to get me A123

I need another query to get B12

I was thinking there would be a regex function that I could use. I could not find one.

答: I am working with newest Node 17.3.1 where "substr" function is obsolete and I replace it with "substring" instead and it is the nearest and simplest alternative.</p>

Body:
I'm trying to extract the the different sub-strings within one string. The I want different strings for every string divided by the dash (-) symbol.

I have tried using the SUBSTR position function. It does not work since sometimes there are 4 chars in the second sub string, therefore, the 3rd sub string is not correct.

SELECT SUBSTR(STR, INSTR (STR, '-', -1)+ 1)

STR = F-123-A123-B12 or F-1234-A123-B12

I am trying to get a query that will give me F.

I need another query that will give me 123 or 1234 if there are 4 chars

I need another query to get me A123

I need another query to get B12

I was thinking there would be a regex function that I could use. I could not find one.