问:
How to write unix regular expression to select for specific files in a cp for-loop
I've got a directory with a bunch of files. Instead of describing the filenames and extensions, I'll just show you what is in the directory:

```<code>P01_1.atag  P03_3.tgt   P05_6.src   P08_3.atag  P10_5.tgt
P01_1.src   P03_4.atag  P05_6.tgt   P08_3.src   P10_6.atag
P01_1.tgt   P03_4.src   P06_1.atag  P08_3.tgt   P10_6.src
P01_2.atag  P03_4.tgt   P06_1.src   P08_4.atag  P10_6.tgt
P01_2.src   P03_5.atag  P06_1.tgt   P08_4.src   P11_1.atag
P01_2.tgt   P03_5.src   P06_2.atag  P08_4.tgt   P11_1.src
P01_3.atag  P03_5.tgt   P06_2.src   P08_5.atag  P11_1.tgt
P01_3.src   P03_6.atag  P06_2.tgt   P08_5.src   P11_2.atag
P01_3.tgt   P03_6.src   P06_3.atag  P08_5.tgt   P11_2.src
P01_4.atag  P03_6.tgt   P06_3.src   P08_6.atag  P11_2.tgt
P01_4.src   P04_1.atag  P06_3.tgt   P08_6.src   P11_3.atag
P01_4.tgt   P04_1.src   P06_4.atag  P08_6.tgt   P11_3.src
P01_5.atag  P04_1.tgt   P06_4.src   P09_1.atag  P11_3.tgt
P01_5.src   P04_2.atag  P06_4.tgt   P09_1.src   P11_4.atag
P01_5.tgt   P04_2.src   P06_5.atag  P09_1.tgt   P11_4.src
P01_6.atag  P04_2.tgt   P06_5.src   P09_2.atag  P11_4.tgt
P01_6.src   P04_3.atag  P06_5.tgt   P09_2.src   P11_5.atag
P01_6.tgt   P04_3.src   P06_6.atag  P09_2.tgt   P11_5.src
P02_1.atag  P04_3.tgt   P06_6.src   P09_3.atag  P11_5.tgt
P02_1.src   P04_4.atag  P06_6.tgt   P09_3.src   P11_6.atag
P02_1.tgt   P04_4.src   P07_1.atag  P09_3.tgt   P11_6.src
P02_2.atag  P04_4.tgt   P07_1.src   P09_4.atag  P11_6.tgt
P02_2.src   P04_5.atag  P07_1.tgt   P09_4.src   P12_1.atag
P02_2.tgt   P04_5.src   P07_2.atag  P09_4.tgt   P12_1.src
P02_3.atag  P04_5.tgt   P07_2.src   P09_5.atag  P12_1.tgt
P02_3.src   P04_6.atag  P07_2.tgt   P09_5.src   P12_2.atag
P02_3.tgt   P04_6.src   P07_3.atag  P09_5.tgt   P12_2.src
P02_4.atag  P04_6.tgt   P07_3.src   P09_6.atag  P12_2.tgt
P02_4.src   P05_1.atag  P07_3.tgt   P09_6.src   P12_3.atag
P02_4.tgt   P05_1.src   P07_4.atag  P09_6.tgt   P12_3.src
P02_5.atag  P05_1.tgt   P07_4.src   P10_1.atag  P12_3.tgt
P02_5.src   P05_2.atag  P07_4.tgt   P10_1.src   P12_4.atag
P02_5.tgt   P05_2.src   P07_5.atag  P10_1.tgt   P12_4.src
P02_6.atag  P05_2.tgt   P07_5.src   P10_2.atag  P12_4.tgt
P02_6.src   P05_3.atag  P07_5.tgt   P10_2.src   P12_5.atag
P02_6.tgt   P05_3.src   P07_6.atag  P10_2.tgt   P12_5.src
P03_1.atag  P05_3.tgt   P07_6.src   P10_3.atag  P12_5.tgt
P03_1.src   P05_4.atag  P07_6.tgt   P10_3.src   P12_6.atag
P03_1.tgt   P05_4.src   P08_1.atag  P10_3.tgt   P12_6.src
P03_2.atag  P05_4.tgt   P08_1.src   P10_4.atag  P12_6.tgt
P03_2.src   P05_5.atag  P08_1.tgt   P10_4.src
P03_2.tgt   P05_5.src   P08_2.atag  P10_4.tgt
P03_3.atag  P05_5.tgt   P08_2.src   P10_5.atag
P03_3.src   P05_6.atag  P08_2.tgt   P10_5.src
</code>```

I have a file that is just outside of this directory that I need to copy to all of the files that end with "_1.src" inside the directory.

I'm working with unix in the Terminal app, so I tried writing this for loop, but it rejected my regular expression:

```<code>for .*1.src in ./
> do
> cp ../1.src
> done
</code>```

I've only written regular expressions in Python before and have minimal experience, but I was under the impression that .* would match any combination of characters. However, I got the following error message:

```<code>-bash: `.*1.src': not a valid identifier
</code>```

I then tried the same for loop with the following regular expression:

```<code>^[a-zA-Z0-9_]*1.src$
</code>```

But I got the same error message:

```<code>-bash: `^[a-zA-Z0-9_]*1.src$': not a valid identifier
</code>```

I tried the same regular expression with and without quotation marks, but it always gives the same 'not a valid identifier' error message.

答:
Tested on Bash 4.4.12, the following is possible:

```<code>$ for i in ./*_1.src; do echo "$i" ; done
</code>```

This will echo every file ending with _1.src to the screen, thus moving it will be possible as well.

```<code>$ mkdir tmp
$ for i in ./*_1.src; do mv "$i" tmp/.; done
</code>```

I've tested with the following data:

```<code>$ touch P{1,2}{0,1,2}_{0..6}.{src,tgt,atag}
$ ls
P10_0.atag  P10_5.src   P11_3.tgt   P12_2.atag  P20_0.src   P20_5.tgt   P21_4.atag  P22_2.src
P10_0.src   P10_5.tgt   P11_4.atag  P12_2.src   P20_0.tgt   P20_6.atag  P21_4.src   P22_2.tgt
P10_0.tgt   P10_6.atag  P11_4.src   P12_2.tgt   P20_1.atag  P20_6.src   P21_4.tgt   P22_3.atag
P10_1.atag  P10_6.src   P11_4.tgt   P12_3.atag  P20_1.src   P20_6.tgt   P21_5.atag  P22_3.src
P10_1.src   P10_6.tgt   P11_5.atag  P12_3.src   P20_1.tgt   P21_0.atag  P21_5.src   P22_3.tgt
P10_1.tgt   P11_0.atag  P11_5.src   P12_3.tgt   P20_2.atag  P21_0.src   P21_5.tgt   P22_4.atag
P10_2.atag  P11_0.src   P11_5.tgt   P12_4.atag  P20_2.src   P21_0.tgt   P21_6.atag  P22_4.src
P10_2.src   P11_0.tgt   P11_6.atag  P12_4.src   P20_2.tgt   P21_1.atag  P21_6.src   P22_4.tgt
P10_2.tgt   P11_1.atag  P11_6.src   P12_4.tgt   P20_3.atag  P21_1.src   P21_6.tgt   P22_5.atag
P10_3.atag  P11_1.src   P11_6.tgt   P12_5.atag  P20_3.src   P21_1.tgt   P22_0.atag  P22_5.src
P10_3.src   P11_1.tgt   P12_0.atag  P12_5.src   P20_3.tgt   P21_2.atag  P22_0.src   P22_5.tgt
P10_3.tgt   P11_2.atag  P12_0.src   P12_5.tgt   P20_4.atag  P21_2.src   P22_0.tgt   P22_6.atag
P10_4.atag  P11_2.src   P12_0.tgt   P12_6.atag  P20_4.src   P21_2.tgt   P22_1.atag  P22_6.src
P10_4.src   P11_2.tgt   P12_1.atag  P12_6.src   P20_4.tgt   P21_3.atag  P22_1.src   P22_6.tgt
P10_4.tgt   P11_3.atag  P12_1.src   P12_6.tgt   P20_5.atag  P21_3.src   P22_1.tgt   P10_5.atag
P11_3.src   P12_1.tgt   P20_0.atag  P20_5.src   P21_3.tgt   P22_2.atag
</code>```

Body:
I've got a directory with a bunch of files. Instead of describing the filenames and extensions, I'll just show you what is in the directory:

P01_1.atag  P03_3.tgt   P05_6.src   P08_3.atag  P10_5.tgt
P01_1.src   P03_4.atag  P05_6.tgt   P08_3.src   P10_6.atag
P01_1.tgt   P03_4.src   P06_1.atag  P08_3.tgt   P10_6.src
P01_2.atag  P03_4.tgt   P06_1.src   P08_4.atag  P10_6.tgt
P01_2.src   P03_5.atag  P06_1.tgt   P08_4.src   P11_1.atag
P01_2.tgt   P03_5.src   P06_2.atag  P08_4.tgt   P11_1.src
P01_3.atag  P03_5.tgt   P06_2.src   P08_5.atag  P11_1.tgt
P01_3.src   P03_6.atag  P06_2.tgt   P08_5.src   P11_2.atag
P01_3.tgt   P03_6.src   P06_3.atag  P08_5.tgt   P11_2.src
P01_4.atag  P03_6.tgt   P06_3.src   P08_6.atag  P11_2.tgt
P01_4.src   P04_1.atag  P06_3.tgt   P08_6.src   P11_3.atag
P01_4.tgt   P04_1.src   P06_4.atag  P08_6.tgt   P11_3.src
P01_5.atag  P04_1.tgt   P06_4.src   P09_1.atag  P11_3.tgt
P01_5.src   P04_2.atag  P06_4.tgt   P09_1.src   P11_4.atag
P01_5.tgt   P04_2.src   P06_5.atag  P09_1.tgt   P11_4.src
P01_6.atag  P04_2.tgt   P06_5.src   P09_2.atag  P11_4.tgt
P01_6.src   P04_3.atag  P06_5.tgt   P09_2.src   P11_5.atag
P01_6.tgt   P04_3.src   P06_6.atag  P09_2.tgt   P11_5.src
P02_1.atag  P04_3.tgt   P06_6.src   P09_3.atag  P11_5.tgt
P02_1.src   P04_4.atag  P06_6.tgt   P09_3.src   P11_6.atag
P02_1.tgt   P04_4.src   P07_1.atag  P09_3.tgt   P11_6.src
P02_2.atag  P04_4.tgt   P07_1.src   P09_4.atag  P11_6.tgt
P02_2.src   P04_5.atag  P07_1.tgt   P09_4.src   P12_1.atag
P02_2.tgt   P04_5.src   P07_2.atag  P09_4.tgt   P12_1.src
P02_3.atag  P04_5.tgt   P07_2.src   P09_5.atag  P12_1.tgt
P02_3.src   P04_6.atag  P07_2.tgt   P09_5.src   P12_2.atag
P02_3.tgt   P04_6.src   P07_3.atag  P09_5.tgt   P12_2.src
P02_4.atag  P04_6.tgt   P07_3.src   P09_6.atag  P12_2.tgt
P02_4.src   P05_1.atag  P07_3.tgt   P09_6.src   P12_3.atag
P02_4.tgt   P05_1.src   P07_4.atag  P09_6.tgt   P12_3.src
P02_5.atag  P05_1.tgt   P07_4.src   P10_1.atag  P12_3.tgt
P02_5.src   P05_2.atag  P07_4.tgt   P10_1.src   P12_4.atag
P02_5.tgt   P05_2.src   P07_5.atag  P10_1.tgt   P12_4.src
P02_6.atag  P05_2.tgt   P07_5.src   P10_2.atag  P12_4.tgt
P02_6.src   P05_3.atag  P07_5.tgt   P10_2.src   P12_5.atag
P02_6.tgt   P05_3.src   P07_6.atag  P10_2.tgt   P12_5.src
P03_1.atag  P05_3.tgt   P07_6.src   P10_3.atag  P12_5.tgt
P03_1.src   P05_4.atag  P07_6.tgt   P10_3.src   P12_6.atag
P03_1.tgt   P05_4.src   P08_1.atag  P10_3.tgt   P12_6.src
P03_2.atag  P05_4.tgt   P08_1.src   P10_4.atag  P12_6.tgt
P03_2.src   P05_5.atag  P08_1.tgt   P10_4.src
P03_2.tgt   P05_5.src   P08_2.atag  P10_4.tgt
P03_3.atag  P05_5.tgt   P08_2.src   P10_5.atag
P03_3.src   P05_6.atag  P08_2.tgt   P10_5.src

I have a file that is just outside of this directory that I need to copy to all of the files that end with "_1.src" inside the directory.

I'm working with unix in the Terminal app, so I tried writing this for loop, but it rejected my regular expression:

for .*1.src in ./
> do
> cp ../1.src
> done

I've only written regular expressions in Python before and have minimal experience, but I was under the impression that .* would match any combination of characters. However, I got the following error message:

-bash: `.*1.src': not a valid identifier

I then tried the same for loop with the following regular expression:

^[a-zA-Z0-9_]*1.src$

But I got the same error message:

-bash: `^[a-zA-Z0-9_]*1.src$': not a valid identifier

I tried the same regular expression with and without quotation marks, but it always gives the same 'not a valid identifier' error message.

Body:
Tested on Bash 4.4.12, the following is possible:

$ for i in ./*_1.src; do echo "$i" ; done

This will echo every file ending with _1.src to the screen, thus moving it will be possible as well.

$ mkdir tmp
$ for i in ./*_1.src; do mv "$i" tmp/.; done

I've tested with the following data:

$ touch P{1,2}{0,1,2}_{0..6}.{src,tgt,atag}
$ ls
P10_0.atag  P10_5.src   P11_3.tgt   P12_2.atag  P20_0.src   P20_5.tgt   P21_4.atag  P22_2.src
P10_0.src   P10_5.tgt   P11_4.atag  P12_2.src   P20_0.tgt   P20_6.atag  P21_4.src   P22_2.tgt
P10_0.tgt   P10_6.atag  P11_4.src   P12_2.tgt   P20_1.atag  P20_6.src   P21_4.tgt   P22_3.atag
P10_1.atag  P10_6.src   P11_4.tgt   P12_3.atag  P20_1.src   P20_6.tgt   P21_5.atag  P22_3.src
P10_1.src   P10_6.tgt   P11_5.atag  P12_3.src   P20_1.tgt   P21_0.atag  P21_5.src   P22_3.tgt
P10_1.tgt   P11_0.atag  P11_5.src   P12_3.tgt   P20_2.atag  P21_0.src   P21_5.tgt   P22_4.atag
P10_2.atag  P11_0.src   P11_5.tgt   P12_4.atag  P20_2.src   P21_0.tgt   P21_6.atag  P22_4.src
P10_2.src   P11_0.tgt   P11_6.atag  P12_4.src   P20_2.tgt   P21_1.atag  P21_6.src   P22_4.tgt
P10_2.tgt   P11_1.atag  P11_6.src   P12_4.tgt   P20_3.atag  P21_1.src   P21_6.tgt   P22_5.atag
P10_3.atag  P11_1.src   P11_6.tgt   P12_5.atag  P20_3.src   P21_1.tgt   P22_0.atag  P22_5.src
P10_3.src   P11_1.tgt   P12_0.atag  P12_5.src   P20_3.tgt   P21_2.atag  P22_0.src   P22_5.tgt
P10_3.tgt   P11_2.atag  P12_0.src   P12_5.tgt   P20_4.atag  P21_2.src   P22_0.tgt   P22_6.atag
P10_4.atag  P11_2.src   P12_0.tgt   P12_6.atag  P20_4.src   P21_2.tgt   P22_1.atag  P22_6.src
P10_4.src   P11_2.tgt   P12_1.atag  P12_6.src   P20_4.tgt   P21_3.atag  P22_1.src   P22_6.tgt
P10_4.tgt   P11_3.atag  P12_1.src   P12_6.tgt   P20_5.atag  P21_3.src   P22_1.tgt   P10_5.atag
P11_3.src   P12_1.tgt   P20_0.atag  P20_5.src   P21_3.tgt   P22_2.atag


来源: stackexchange

问:
How can I fix this warning produced when I run my Test::Unit tests
I'm getting this warning in my Test::Unit output...

```<code>/usr/local/bin/ruby -I.:lib:test -rtest/unit -e "%w[test/functional/sessions_controller_test.rb].each { |f| require f }" | unit_diff -u
Loaded suite -e
Started
.../Users/ethan/project/mtc/contactdb/app/views/sessions/new.html.haml:30: warning: multiple values for a block parameter (0 for 1)
    from /usr/local/lib/ruby/gems/1.8/gems/haml-2.0.8/lib/haml/helpers/action_view_mods.rb:142
[...repeated eight times...]
</code>```

I think the relevant part is:

```<code>/contactdb/app/views/sessions/new.html.haml:30: warning:
  multiple values for a block parameter (0 for 1)
</code>```

Looking at my Haml file, I've narrowed it down to this snippet (I think)...

```<code>- form_tag( recover_login_path, :method => 'get') do |f|
  %p
    = text_field_tag :email, '', { :size => '35', :maxlength => '255' }
</code>```

recover_login is a named route.

I looked at the API docs for form_tag. It seems like my code is following what they have in the examples.

答:
form_tag only passes in the form builder object |f| when you use a model object with it.

```<code>form_tag @user, :method => :get do |f|
  f.text_field :first_name
end
</code>```

But constructing your own form path with no passed in model object, the block argument is not passed in or used.

```<code>form_tag user_path(@user.id), :method => :get do
  text_field :user, :first_name
end
</code>```

OwnerDisplayName: Ethan

ContentLicense: CC BY-SA 2.5

Body:
I'm getting this warning in my Test::Unit output...

/usr/local/bin/ruby -I.:lib:test -rtest/unit -e "%w[test/functional/sessions_controller_test.rb].each { |f| require f }" | unit_diff -u
Loaded suite -e
Started
.../Users/ethan/project/mtc/contactdb/app/views/sessions/new.html.haml:30: warning: multiple values for a block parameter (0 for 1)
    from /usr/local/lib/ruby/gems/1.8/gems/haml-2.0.8/lib/haml/helpers/action_view_mods.rb:142
[...repeated eight times...]

I think the relevant part is:

/contactdb/app/views/sessions/new.html.haml:30: warning:
  multiple values for a block parameter (0 for 1)

Looking at my Haml file, I've narrowed it down to this snippet (I think)...

- form_tag( recover_login_path, :method => 'get') do |f|
  %p
    = text_field_tag :email, '', { :size => '35', :maxlength => '255' }

recover_login is a named route.

I looked at the API docs for form_tag. It seems like my code is following what they have in the examples.

Body:
form_tag only passes in the form builder object |f| when you use a model object with it.

form_tag @user, :method => :get do |f|
  f.text_field :first_name
end

But constructing your own form path with no passed in model object, the block argument is not passed in or used.

form_tag user_path(@user.id), :method => :get do
  text_field :user, :first_name
end

OwnerDisplayName: Squeegy

ContentLicense: CC BY-SA 3.0


问:
Obj C - resign first responder on touch UIView
I'm trying to get the keyboard to disappear when the screen is touched, a question that is answered all over stackoverflow.  I was able to get the keyboard to disappear when the enter key was pressed thanks to a thread here.  I'm not having luck on the background touch resigning the first responder.  The method is being entered, I have an NSLog in the method saying, "in backgroundTouched" but the keyboard is still there.

I've tried making the UIView a UIControl class so I could use the touch event.
journalComment is a UITextView.

```<code>-(IBAction)backgroundTouched:(id)sender
    {
        [journalComment resignFirstResponder];
        NSLog(@ "in backgroundTouched");

}
</code>```

I've also tried having a invisible button under everything that calles the backGroundTouched method.  I think it maybe that I'm missing something in interface builder, but I'm not sure what.

Thank you for any help!

This is what works for the done button:

```<code>-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range
 replacementText:(NSString *)text
{
    // Any new character added is passed in as the "text" parameter
    if ([text isEqualToString:@"\n"]) {
        // Be sure to test for equality using the "isEqualToString" message
        [textView resignFirstResponder];

        // Return FALSE so that the final '\n' character doesn't get added
        return FALSE;
    }
    // For any other character return TRUE so that the text gets added to the view
    return TRUE;
}
</code>```

答:
Try this. We had this problem eariler, but eventually found the right solution.

```<code>  -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

        [yourtextfield resignFirstResponder];

        // you can have multiple textfields here

    }
</code>```

This should resolve the problem with the keyboard not dissapearing when pushing the background.

Body:
I'm trying to get the keyboard to disappear when the screen is touched, a question that is answered all over stackoverflow.  I was able to get the keyboard to disappear when the enter key was pressed thanks to a thread here.  I'm not having luck on the background touch resigning the first responder.  The method is being entered, I have an NSLog in the method saying, "in backgroundTouched" but the keyboard is still there.

I've tried making the UIView a UIControl class so I could use the touch event.
journalComment is a UITextView.

-(IBAction)backgroundTouched:(id)sender
    {
        [journalComment resignFirstResponder];
        NSLog(@ "in backgroundTouched");

}

I've also tried having a invisible button under everything that calles the backGroundTouched method.  I think it maybe that I'm missing something in interface builder, but I'm not sure what.

Thank you for any help!

This is what works for the done button:

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range
 replacementText:(NSString *)text
{
    // Any new character added is passed in as the "text" parameter
    if ([text isEqualToString:@"\n"]) {
        // Be sure to test for equality using the "isEqualToString" message
        [textView resignFirstResponder];

        // Return FALSE so that the final '\n' character doesn't get added
        return FALSE;
    }
    // For any other character return TRUE so that the text gets added to the view
    return TRUE;
}

Body:
Try this. We had this problem eariler, but eventually found the right solution.

  -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

        [yourtextfield resignFirstResponder];

        // you can have multiple textfields here

    }

This should resolve the problem with the keyboard not dissapearing when pushing the background.


问:
dash update dash_core_components widget value programmatically
I am new to dash and i am not able to find out how to update a widget value without having to create a function and wrap it with a callback and an input from another widget.

```<code>import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html

app = dash.Dash()

# create radio items widget
widget=dcc.RadioItems(
        options=[
            {'label': 'New York City', 'value': 'NYC'},
            {'label': 'Montreal', 'value': 'MTL'},
            {'label': 'San Francisco', 'value': 'SF'}
        ],
        value='MTL')

# append this to a html.div children.
div  = html.Div([widget])
app.layout = div

if __name__ == '__main__':
    app.run_server(debug=True)

# normally I would like to be able to update the widget value programmatically and have the html UI updated automatically too
widget.set_value('SF')
</code>```

appreciate any help

答: You have already found the Dash answer. Any updates to the UI will come from callbacks. You can have the Input value that triggers the callback come from the user interacting with another component, such as clicking on a button, or it can update every x seconds with the Interval component, or it can be one in a cascade of updates with each one listening to the one before it, ultimately triggered by, likely, a user interaction.

ContentLicense: CC BY-SA 4.0

Body:
I am new to dash and i am not able to find out how to update a widget value without having to create a function and wrap it with a callback and an input from another widget.

import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html

app = dash.Dash()

# create radio items widget
widget=dcc.RadioItems(
        options=[
            {'label': 'New York City', 'value': 'NYC'},
            {'label': 'Montreal', 'value': 'MTL'},
            {'label': 'San Francisco', 'value': 'SF'}
        ],
        value='MTL')

# append this to a html.div children.
div  = html.Div([widget])
app.layout = div

if __name__ == '__main__':
    app.run_server(debug=True)

# normally I would like to be able to update the widget value programmatically and have the html UI updated automatically too
widget.set_value('SF')

appreciate any help


问:
(Too) complex configuration management (Java properties)
I'm working at a company having a (too) complex configuration management process:

In each module there is an application.properties file. There are properties for the developers like: database.host = localhost

Properties which change in other environments are maintained in an application.properties file in an override-properties folder (for each module) like: database.host=@dbhost@

There is a default-deployment.properties file with default values for other environments like: database.HOST=noValueConfigured.DB_HOST

A postconfigure.properties file with DATABASE_ HOST=@configure.DB_HOST@

Those files are only needed if a property value depends on the environments (is different for development, testing, live).

Finally there is a Excel document with a sheet for every environment and a row like: configure.DB_HOST - a comment ... - 127.0.0.1 (just as example). The Excel is responsible for generating the correct property files for the rpm packages.

This process is not only complex but also error prone.
How could it be simplified/improved?

The approach should be compatbiel with Spring DI.

答:
If not to take into consideration all the redesign methods mentioned in the previous comments, you can wrap all the complexity into Tomtit task manager which is good with these types if tasks.

Just create properties files templates and populate them using environments


问:
how to start 2 animations parallel
I try to make an animation effect, box coming from outside of the container and text appears after that box.

When I add delay to text animation, it breaks, how to sync the two animations?

Help me, please.
Ask me for more details...

@keyframes animText {
  0% {
        max-width: 0;
        visibility: hidden;
    }
    100% {
        max-width: 100%;
        visibility: visible;
    }
}
@keyframes animBox {
  0% {
        right: 100%;
        visibility: hidden;
    }
    100% {
        right: 0;
        visibility: visible;
    }
}
#box {
  position: relative;
  overflow: hidden;
  padding: 10px;
  width: 220px;
  height: 75px;
  background-color: #343434;
  display: flex;
}

.redbox {
  background-color: crimson;
  opacity: 0.95;
  width: 74px;
  height: 74px;
  max-width: 75px;
  flex: 1 0;
  position: relative;
  animation: animBox 2s cubic-bezier(0,0,1,1);
}

p {
  font-size: 50px;
  line-height: 0.75em;
  color: #fff;
  margin: 0;
  overflow: hidden;
  flex: 1 0;
  animation: animText 3s cubic-bezier(0,0,1,1) 1s;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="box">
  <p>Some Text</p>
  <div class="redbox"></div>
</div></code>```

答:
Take it bro.

@keyframes animText {
   0% {
        max-width: 0;
        visibility: hidden;
    }

    33% {
        max-width: 0%;
        visibility: visible;
    }

    100% {
        max-width: 100%;
        visibility: visible;
    }
}

@keyframes animBox {
  0% {
        right: 100%;
        visibility: hidden;
    }

    100% {
        right: 0;
        visibility: visible;
    }
}

#box {
  position: relative;
  overflow: hidden;
  padding: 10px;
  width: 220px;
  height: 75px;
  background-color: #343434;
  display: flex;
}

.redbox {
  background-color: crimson;
  opacity: 0.95;
  width: 74px;
  height: 74px;
  max-width: 75px;
  flex: 1 0;
  position: relative;
  animation: animBox 1s cubic-bezier(0, 0, 1, 1);

}

p {
  font-size: 50px;
  line-height: 0.75em;
  color: #fff;
  margin: 0;
  overflow: hidden;
  flex: 1 0;
  animation: animText 2s cubic-bezier(0, 0, 1, 1);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="box">
  <p>Some Text</p>
  <div class="redbox"></div>
</div></code>```

Title: how to start 2 animations parallel

Body:
I try to make an animation effect, box coming from outside of the container and text appears after that box.

When I add delay to text animation, it breaks, how to sync the two animations?

Help me, please.
Ask me for more details...

@keyframes animText {
  0% {
        max-width: 0;
        visibility: hidden;
    }
    100% {
        max-width: 100%;
        visibility: visible;
    }
}
@keyframes animBox {
  0% {
        right: 100%;
        visibility: hidden;
    }
    100% {
        right: 0;
        visibility: visible;
    }
}
#box {
  position: relative;
  overflow: hidden;
  padding: 10px;
  width: 220px;
  height: 75px;
  background-color: #343434;
  display: flex;
}

.redbox {
  background-color: crimson;
  opacity: 0.95;
  width: 74px;
  height: 74px;
  max-width: 75px;
  flex: 1 0;
  position: relative;
  animation: animBox 2s cubic-bezier(0,0,1,1);
}

p {
  font-size: 50px;
  line-height: 0.75em;
  color: #fff;
  margin: 0;
  overflow: hidden;
  flex: 1 0;
  animation: animText 3s cubic-bezier(0,0,1,1) 1s;
}

Some Text

Body:
Take it bro.

@keyframes animText {
   0% {
        max-width: 0;
        visibility: hidden;
    }

    33% {
        max-width: 0%;
        visibility: visible;
    }

    100% {
        max-width: 100%;
        visibility: visible;
    }
}

@keyframes animBox {
  0% {
        right: 100%;
        visibility: hidden;
    }

    100% {
        right: 0;
        visibility: visible;
    }
}

#box {
  position: relative;
  overflow: hidden;
  padding: 10px;
  width: 220px;
  height: 75px;
  background-color: #343434;
  display: flex;
}

.redbox {
  background-color: crimson;
  opacity: 0.95;
  width: 74px;
  height: 74px;
  max-width: 75px;
  flex: 1 0;
  position: relative;
  animation: animBox 1s cubic-bezier(0, 0, 1, 1);

}

p {
  font-size: 50px;
  line-height: 0.75em;
  color: #fff;
  margin: 0;
  overflow: hidden;
  flex: 1 0;
  animation: animText 2s cubic-bezier(0, 0, 1, 1);
}

<div id="box">
  <p>Some Text</p>
  <div class="redbox"></div>
</div>


问:
NoSuchElementException, when method is called after code above it is run
When I run my code, it will run fine up to the line "scanner.close()".
After than, when I run the "SumTenNumbers()" method... it will run the first line of the while loop once and crash with the "NoSuchElementException"...
When I remove the code above the line calling the method, it runs fine...
Why does this occur, and how can I solve it?

This is the code:

```<code>public class Main
{

    public static void main(String[] args)
    {
        // we use the class "scanner" for input data
        Scanner scanner = new Scanner(System.in); //System.in allows you to type input data into the console which can be returned into the console
        System.out.println("Enter your name: ");
        String name = scanner.nextLine();
        System.out.println("Your name is " + name);

        System.out.println("Enter your year of birth: ");
        boolean isInt = scanner.hasNextInt();
        if (isInt)
        {
            int yearOfBirth = scanner.nextInt();

            int age = 2019 - yearOfBirth;
            if (age >= 0 && age <= 120)
            {
                System.out.println("You are " + age + " years old");
            }
            else
            {
                System.out.println("Invalid year of birth");
            }
        }
        else
        {
            System.out.println("Unable to parse year of birth");
        }
        scanner.close(); // we must close scanner

        SumTenNumbers();

    }

    public static void SumTenNumbers()
    {
        var reader = new Scanner(System.in);

        int sum = 0;
        int count = 1;

        while (count < 11)
        {
            System.out.println("Enter number " + count + ": ");
            boolean valid = reader.hasNextInt();
            if (valid)
            {
                int userNum = reader.nextInt();
                sum += userNum;
                count++;
            }
            else
            {
                reader.next();
                System.out.println("INVALID");
            }
        }

        System.out.println(sum);

        reader.close();
    }
}
</code>```

This is how it looks when I run the code...

```<code>Enter your name:
Siddharth
Your name is Siddharth
Enter your year of birth:
2001
You are 18 years old
Enter number 1:
Exception in thread "main" java.util.NoSuchElementException
    at java.base/java.util.Scanner.throwFor(Scanner.java:937)
    at java.base/java.util.Scanner.next(Scanner.java:1478)
    at com.company.Main.SumTenNumbers(Main.java:64)
    at com.company.Main.main(Main.java:39)

Process finished with exit code 1
</code>```

答:
the line reader.close() closes the Scanner and, with it, System.in.

After that, you cannot read from stdin (System.in) anymore.

In order to prevent this you can:

use only one Scanner object and close it after using it the last time

close System.in after using it the last time (using a Scanner or System.in.close())

close System.in at the end of your Program

never close System.in (Problem: other Processes cannot use the resource, stdin can also be a File, a Network Connection or something else)

Body:
When I run my code, it will run fine up to the line "scanner.close()".
After than, when I run the "SumTenNumbers()" method... it will run the first line of the while loop once and crash with the "NoSuchElementException"...
When I remove the code above the line calling the method, it runs fine...
Why does this occur, and how can I solve it?

This is the code:

public class Main
{

    public static void main(String[] args)
    {
        // we use the class "scanner" for input data
        Scanner scanner = new Scanner(System.in); //System.in allows you to type input data into the console which can be returned into the console
        System.out.println("Enter your name: ");
        String name = scanner.nextLine();
        System.out.println("Your name is " + name);

        System.out.println("Enter your year of birth: ");
        boolean isInt = scanner.hasNextInt();
        if (isInt)
        {
            int yearOfBirth = scanner.nextInt();

            int age = 2019 - yearOfBirth;
            if (age >= 0 && age <= 120)
            {
                System.out.println("You are " + age + " years old");
            }
            else
            {
                System.out.println("Invalid year of birth");
            }
        }
        else
        {
            System.out.println("Unable to parse year of birth");
        }
        scanner.close(); // we must close scanner

        SumTenNumbers();

    }

    public static void SumTenNumbers()
    {
        var reader = new Scanner(System.in);

        int sum = 0;
        int count = 1;

        while (count < 11)
        {
            System.out.println("Enter number " + count + ": ");
            boolean valid = reader.hasNextInt();
            if (valid)
            {
                int userNum = reader.nextInt();
                sum += userNum;
                count++;
            }
            else
            {
                reader.next();
                System.out.println("INVALID");
            }
        }

        System.out.println(sum);

        reader.close();
    }
}

This is how it looks when I run the code...

Enter your name:
Siddharth
Your name is Siddharth
Enter your year of birth:
2001
You are 18 years old
Enter number 1:
Exception in thread "main" java.util.NoSuchElementException
    at java.base/java.util.Scanner.throwFor(Scanner.java:937)
    at java.base/java.util.Scanner.next(Scanner.java:1478)
    at com.company.Main.SumTenNumbers(Main.java:64)
    at com.company.Main.main(Main.java:39)

Process finished with exit code 1


问:
Conditional cast from string to string always succeds in swift 3

```<code>func resetUserDefaults() {
    let userDefaults = UserDefaults.standard
    let dict = userDefaults.dictionaryRepresentation()

    for (key,_) in dict {
        if let key = key as? String {
            userDefaults.removeObject(forKey: key)
        } else {
            #if DEBUG
                NSLog("\(key)")
            #endif
        }
    }
}
</code>```

I'm getting this warning. can anyone suggest me how to avoid this warnoing

答:
I had the same issue with a private function in Swift 5 and I found a solution working for me.

The solution was to change the value to optional.
I added a question mark after the type I was looking for. (as String"?")

You can see an example here :

```<code>private func doSomeThing(completion: @escaping (String) -> ()) {
    let Something = somethingElse;
        if let anoterThing = something as String?{
        completion(anoterThing)
    }else{
        completion("Error at private func doSomeThing")
    }
}
</code>```

You can find more pieces of information here:

https://docs.swift.org/swift-book/LanguageGuide/OptionalChaining.html

Swift: difference as String? vs. as? String

Downcasting in Swift with as and as?

Best Regards

Body:
func resetUserDefaults() {
    let userDefaults = UserDefaults.standard
    let dict = userDefaults.dictionaryRepresentation()

    for (key,_) in dict {
        if let key = key as? String {
            userDefaults.removeObject(forKey: key)
        } else {
            #if DEBUG
                NSLog("\(key)")
            #endif
        }
    }
}

I'm getting this warning. can anyone suggest me how to avoid this warnoing

Body:
I had the same issue with a private function in Swift 5 and I found a solution working for me.

The solution was to change the value to optional.
I added a question mark after the type I was looking for. (as String"?")

You can see an example here :

private func doSomeThing(completion: @escaping (String) -> ()) {
    let Something = somethingElse;
        if let anoterThing = something as String?{
        completion(anoterThing)
    }else{
        completion("Error at private func doSomeThing")
    }
}

You can find more pieces of information here:

https://docs.swift.org/swift-book/LanguageGuide/OptionalChaining.html

Swift: difference as String? vs. as? String

Downcasting in Swift with as and as?

Best Regards


问:
Scaling a UIView during transitionFromView?
I'm using a container UIView to replicate the kind of behavior the iTunes store does when you tap on album artwork and it flips and scales.

Current code looks like:

```<code>//mainView is 300x300x, smallView is 30x30

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:2.0];
[UIView transitionFromView:mainView toView:smallView duration:3.0 options:UIViewAnimationOptionTransitionFlipFromLeft completion:nil];

containerView.frame = CGRectMake(275, 415, 30, 30);

[UIView commitAnimations];
</code>```

I can't seem to get the content of the containerView to scale during the animation, the frame just closes in on the content. I tried applying some transforms to both the view and the layers and a bunch of other things but I can't seem to get it to behave properly.

答:
Rather than setting the frame, try using a transform instead:

```<code>- (void)setStartTransform:(CGAffineTransform)transform;
- (void)setEndTransform:(CGAffineTransform)transform;
</code>```

Something like

```<code>[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:2.0];
[UIView transitionFromView:mainView toView:smallView duration:3.0 options:UIViewAnimationOptionTransitionFlipFromLeft completion:nil];

//containerView.frame = CGRectMake(275, 415, 30, 30);

[containerView setStartTransform: CGAffineTransformIdentity];
[containerView setEndTransform: CGAffineTransformMakeScale(0.1, 0.1)];

[UIView commitAnimations];
</code>```

(You might need to apply a translate to the transform too.)

Body:
I'm using a container UIView to replicate the kind of behavior the iTunes store does when you tap on album artwork and it flips and scales.

Current code looks like:

//mainView is 300x300x, smallView is 30x30

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:2.0];
[UIView transitionFromView:mainView toView:smallView duration:3.0 options:UIViewAnimationOptionTransitionFlipFromLeft completion:nil];

containerView.frame = CGRectMake(275, 415, 30, 30);

[UIView commitAnimations];

I can't seem to get the content of the containerView to scale during the animation, the frame just closes in on the content. I tried applying some transforms to both the view and the layers and a bunch of other things but I can't seem to get it to behave properly.

Body:
Rather than setting the frame, try using a transform instead:

- (void)setStartTransform:(CGAffineTransform)transform;
- (void)setEndTransform:(CGAffineTransform)transform;

Something like

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:2.0];
[UIView transitionFromView:mainView toView:smallView duration:3.0 options:UIViewAnimationOptionTransitionFlipFromLeft completion:nil];

//containerView.frame = CGRectMake(275, 415, 30, 30);

[containerView setStartTransform: CGAffineTransformIdentity];
[containerView setEndTransform: CGAffineTransformMakeScale(0.1, 0.1)];

[UIView commitAnimations];

(You might need to apply a translate to the transform too.)


问:
Query column value of related object and store as variable
I'm trying to grab the value of my column name in my model Category which is linked to my Post model. I want to save the value of name into a variable for later use. I tried print(post.categories.name) but it returns value None. I can confirm that there is an actual value by running post.categories.values() which returns <QuerySet [{'id': 1, 'name': 'General'}]>

Model:

```<code>from django.db import models

class Category(models.Model):
    name = models.CharField(max_length=30)

class Post(models.Model):
    title = models.SlugField(max_length = 250, null = True, blank = True)
    body = models.TextField()
    created_on = models.DateTimeField(null=True)
    last_modified = models.DateTimeField(null=True)
    categories = models.ManyToManyField('Category', related_name='posts')

class Comment(models.Model):
    author = models.CharField(max_length=60)
    body = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)
    post = models.ForeignKey('Post', on_delete=models.CASCADE)
</code>```

Views:

```<code>def blog_detail(request, pk):
    post = Post.objects.select_related().get(pk=pk)
    category = post.categories.name # This returns None but should return General
    form = CommentForm()
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = Comment(
                author=form.cleaned_data["author"],
                body=form.cleaned_data["body"],
                post=post
            )
            comment.save()

    comments = Comment.objects.filter(post=post)
    context = {
        "post": post,
        "comments": comments,
        "form": form,
    }
    return render(request, "blog_detail.html", context)
</code>```

答:
You can't. You defined categories as a ManyToManyField on your Post model, so post.categories is a ModelManager to fetch the categories and post.categories.all() returns all the categories associated to post.

You can get a list of names for the categories of a post like this:

```<code>category_names = [category.name for category in post.categories.all()]
</code>```

Body:
I'm trying to grab the value of my column name in my model Category which is linked to my Post model. I want to save the value of name into a variable for later use. I tried print(post.categories.name) but it returns value None. I can confirm that there is an actual value by running post.categories.values() which returns <QuerySet [{'id': 1, 'name': 'General'}]>

Model:

from django.db import models

class Category(models.Model):
    name = models.CharField(max_length=30)

class Post(models.Model):
    title = models.SlugField(max_length = 250, null = True, blank = True)
    body = models.TextField()
    created_on = models.DateTimeField(null=True)
    last_modified = models.DateTimeField(null=True)
    categories = models.ManyToManyField('Category', related_name='posts')

class Comment(models.Model):
    author = models.CharField(max_length=60)
    body = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)
    post = models.ForeignKey('Post', on_delete=models.CASCADE)

Views:

def blog_detail(request, pk):
    post = Post.objects.select_related().get(pk=pk)
    category = post.categories.name # This returns None but should return General
    form = CommentForm()
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = Comment(
                author=form.cleaned_data["author"],
                body=form.cleaned_data["body"],
                post=post
            )
            comment.save()

    comments = Comment.objects.filter(post=post)
    context = {
        "post": post,
        "comments": comments,
        "form": form,
    }
    return render(request, "blog_detail.html", context)

Body:
You can't. You defined categories as a ManyToManyField on your Post model, so post.categories is a ModelManager to fetch the categories and post.categories.all() returns all the categories associated to post.

You can get a list of names for the categories of a post like this:

category_names = [category.name for category in post.categories.all()]


问:
How to split Nginx event into two separate events
In Nginx, I've a file called x_event.js that has two methods, method A() and methodB() which return stringified JSON objects.

```<code>js_include path2nginxconf/njs/x_event.js;
js_set $methodA methodA;
js_set $methodB methodB;
log_format x_event escape=none js_set $methodA $methodB;
</code>```

This works well, however, it concatenates the two JSON strings into a single event log. I would like to have them output as two separate events. Is this possible and how? Thanks.

Currently, I see:

```<code>{outputA}{outputB}
</code>```

Expected:

```<code>{outputA}
{outputB}
</code>```

答:
I got it working by setting the following configuration:</p>

```<code>js_set $methodA methodA;
js_set $methodB methodB;
log_format x_event_A escape=none $methodA;
log_format x_event_B escape=none $methodB;
access_log ~/logs/access.log x_event_A;
access_log ~/logs/access.log x_event_B;
</code>```

Body:
In Nginx, I've a file called x_event.js that has two methods, method A() and methodB() which return stringified JSON objects.

js_include path2nginxconf/njs/x_event.js;
js_set $methodA methodA;
js_set $methodB methodB;
log_format x_event escape=none js_set $methodA $methodB;

This works well, however, it concatenates the two JSON strings into a single event log. I would like to have them output as two separate events. Is this possible and how? Thanks.

Currently, I see:

{outputA}{outputB}

Expected:

{outputA}
{outputB}

Body:
I got it working by setting the following configuration:

js_set $methodA methodA;
js_set $methodB methodB;
log_format x_event_A escape=none $methodA;
log_format x_event_B escape=none $methodB;
access_log ~/logs/access.log x_event_A;
access_log ~/logs/access.log x_event_B;


问:
keep getting http bad request on rest api
I can't create a user in Artifactory via REST API.

Doc I'm using: https://www.jfrog.com/confluence/display/RTF/Artifactory+REST+API#ArtifactoryRESTAPI-CreateorReplaceUser

my rest call:

```<code>curl -k -u user:pass -X PUT -H "Content-Type: application/json" "$API_URL/security/user/$USERNAME" -t $BUILD_ID.json
</code>```

content of $BUILD_ID.json:

```<code>{"name" : "test","password" : "password","groups" : ["test","Test_AJU_group"]}
</code>```

but unfortunately still getting http error 400 - bad request.

14:57:12 {

  14:57:12   "errors" : [ {

  14:57:12     "status" : 400,

  14:57:12     "message" : "Bad Request"

  14:57:12   } ]

  14:57:12 }Finished: SUCCESS

I tried to send data in URL instead of file with same results.

答: Perhaps /security/user => /security/users?

Body:
I can't create a user in Artifactory via REST API.

Doc I'm using: https://www.jfrog.com/confluence/display/RTF/Artifactory+REST+API#ArtifactoryRESTAPI-CreateorReplaceUser

my rest call:

curl -k -u user:pass -X PUT -H "Content-Type: application/json" "$API_URL/security/user/$USERNAME" -t $BUILD_ID.json

content of $BUILD_ID.json:

{"name" : "test","password" : "password","groups" : ["test","Test_AJU_group"]}

but unfortunately still getting http error 400 - bad request.

14:57:12 {

  14:57:12   "errors" : [ {

  14:57:12     "status" : 400,

  14:57:12     "message" : "Bad Request"

  14:57:12   } ]

  14:57:12 }Finished: SUCCESS

I tried to send data in URL instead of file with same results.


问:
Where can I find MySql 4.0.30 for windows?
I need to adapt our testing server to our production one that is stored on Aruba.
Aruba use MySql 4.0.30 but I can't find them nowhere!
Anybody know where can I find it ? or anybody has the installer stored anywhere?

Davide

答:
Here for you source: http://mirror.provenscaling.com/mysql/community/source/4.0/mysql-4.0.30.tar.gz

Binaries only there for 4.1: http://mirror.provenscaling.com/mysql/community/binaries/4.1/


问:
Sorting Youtube API result from playlist
I have been struggling with Youtube's API v3 now and I can't get it work in the way I want. My goal is to load the latest videos from a selected playlist into my website. The problem is that I only the the oldest videos in my response.

To load the playlist I request following API URI:
https://www.googleapis.com/youtube/v3/playlistItems

Here is an example of a request (just click execute):
http://developers.google.com/apis-explorer/#p/youtube/v3/youtube.playlistItems.list?part=id%252Csnippet%252CcontentDetails%252Cstatus&playlistId=PLOU2XLYxmsIKGo-dgliIJQNZ6L3G8UV4b&_h=1&

How can a sort the result and get the latest videos first? I can't find anything in the docs and I have been googling without any luck. There is no point with this API if you can't sort the result. The only way is to load all videos by keep loading the next page by token but that is just insane.

Any idea? Sounds like a basic problem but I can't find a solution...

答:
This is the only option right now available. Instead of trying to sort video list from the Http request Url, you can sort the order in the youtube account's playlist setting.

In the Playlist setting you can either manually drag and change the list or there is a option to change the  order. Youtube Data API will output the data as the playlist shows the data.

Summary : change the playlist order in youtube account instead trying to filter data using http requests.

FYI: playlist settings can be only changed by the uploader's account
Hope this helps.


问:
Laravel update record with Passport
Hi all today i have this problem with my api.
I don't update the record on DB.
In postaman the response is true but don.t save in db.
In Postaman i passed with PUT method and set in Body name a text

ProductController:

```<code>public function update(Request $request, $id)
{
    $product = auth()->user()->products()->find($id);

    if (!$product) {
        return response()->json([
            'success' => false,
            'message' => 'Product with id ' . $id . ' not found'
        ], 400);
    }

    $updated = $product->fill($request->all())->save();

    if ($updated)
        return response()->json([
            'success' => true
        ]);
    else
        return response()->json([
            'success' => false,
            'message' => 'Product could not be updated'
        ], 500);
}
</code>```

答: You should take a look at your Product Model to see if name is set as a fillable field:  $fillable = ['name'];. Also, the key is probably just name instead of "name".

Title: Laravel update record with Passport

Body:
Hi all today i have this problem with my api.
I don't update the record on DB.
In postaman the response is true but don.t save in db.
In Postaman i passed with PUT method and set in Body name a text

ProductController:

public function update(Request $request, $id)
{
    $product = auth()->user()->products()->find($id);

    if (!$product) {
        return response()->json([
            'success' => false,
            'message' => 'Product with id ' . $id . ' not found'
        ], 400);
    }

    $updated = $product->fill($request->all())->save();

    if ($updated)
        return response()->json([
            'success' => true
        ]);
    else
        return response()->json([
            'success' => false,
            'message' => 'Product could not be updated'
        ], 500);
}


问:
Remove a list inside a list
I want to remove the list [1,2,3] inside the outer list.
I tried or isinstance(item, list) but that didn't work, the nested list was still there.

```<code>messy_list = ["a", 2, 3, 1, False, [1, 2, 3]]

# Your code goes below here
messy_list.pop(3)
messy_list.insert(0,1)

for item in messy_list:
    if isinstance(item, str) or isinstance(item, bool):
        messy_list.remove(item)

messy_list.pop(-1)

print(messy_list)
</code>```

I would like to know if there wasn't a better way to check if there's a list inside the list, and then remove from the outer list, instead of having to hardcode it with .pop(-1)

答:
We can remove a list inside a list same way like we remove the single list, just provide the reference of the list object to the del function.

```<code>del(list_object).
</code>```

for example :-

```<code>a = [1,2,3,[4,5,6]]
del(a[3])
</code>```

after this a will look like.

```<code>[1, 2, 3]
</code>```

Title: Remove a list inside a list

Body:
I want to remove the list [1,2,3] inside the outer list.
I tried or isinstance(item, list) but that didn't work, the nested list was still there.

messy_list = ["a", 2, 3, 1, False, [1, 2, 3]]

# Your code goes below here
messy_list.pop(3)
messy_list.insert(0,1)

for item in messy_list:
    if isinstance(item, str) or isinstance(item, bool):
        messy_list.remove(item)

messy_list.pop(-1)

print(messy_list)

I would like to know if there wasn't a better way to check if there's a list inside the list, and then remove from the outer list, instead of having to hardcode it with .pop(-1)

Body:
We can remove a list inside a list same way like we remove the single list, just provide the reference of the list object to the del function.

del(list_object).

for example :-

a = [1,2,3,[4,5,6]]
del(a[3])

after this a will look like.

[1, 2, 3]


问:
Clearing the Cache on OS Versions above Marshmallow
I want to make an Android App which will clean the cache of other apps. I have figured out how to do that for Android Version below Marshmallow.

This is what I am using for Android Honeycom and above:

```<code>    if (isExternalStorageWritable()) {
        final File externalDataDirectory = new File(Environment
                .getExternalStorageDirectory().getAbsolutePath(), "/Android/data");

        final String externalCachePath = externalDataDirectory.getAbsolutePath() +
                "/%s/cache";

        if (externalDataDirectory.isDirectory()) {
            final File[] files = externalDataDirectory.listFiles();

            for (File file : files) {
                if (!deleteDirectory(new File(String.format(externalCachePath,
                        file.getName())), true)) {
                    Log.e(TAG, "External storage suddenly becomes unavailable");

                    return false;
                }
            }
        } else {
            Log.e(TAG, "External data directory is not a directory!");
        }
    } else {
        Log.d(TAG, "External storage is unavailable");
    }
</code>```

But I am having an issue to figure out how to do it for Android Version Marshmallow and above.

Other cache cleaners present in the market are able to perform this by taking accessibility permission or any other way?

答:
If the application is a system app, it can request the android.permission.DELETE_CACHE_FILES and you could use reflection to access the PackageManager.deleteApplicationCacheFiles()

```<code>  // Lazily instantiated by reflection
  @Nullable private Method deleteApplicationCacheMethod;

  public ListenableFuture<Void> deleteApplicationCache(String packageName) throws Exception {
    SettableFuture<Void> futureDelete = SettableFuture.create();
    ClearCacheObserver observer = new ClearCacheObserver(packageName, deleteObserver);
    // Invoke deleteApplicationCacheFiles() by reflection
    Method deleteApplicationCacheMethod = deleteApplicationCacheMethod(packageManager);
    deleteApplicationCacheMethod.invoke(packageManager, packageName, observer);
    return futureDelete;
  }

  /** Returns an accessible version of the {@link PackageManager#deleteApplicationCacheFiles}. */
  private static Method deleteApplicationCacheMethod() throws InvocationTargetException {
    if (deleteApplicationCacheMethod == null) {
      deleteApplicationCacheMethod = packageManager
          .getClass()
          .getDeclaredMethod(
               "deleteApplicationCacheFiles", String.class, IPackageDataObserver.class);
     deleteApplicationCacheMethod.setAccessible(true);
   }
   return deleteApplicationCacheMethod;
 }

  /** Wraps a Guava Future in a IPackageDataObserver. */
  private static class ClearCacheObserver extends IPackageDataObserver.Stub {
    final String packageName;
    final SettableFuture<Void> futureDelete;

    ClearCacheObserver(String packageName, SettableFuture<Void> futureDelete) {
      this.packageName = packageName;
      this.futureDelete = futureDelete;
    }

    @Override
    public void onRemoveCompleted(String package, boolean succeeded) {
      if (!packageName.equals(package))) {
        return;
      }
      if (succeeded) {
        futureDelete.set(null);
      } else {
        futureDelete.setException(new Exception("Failed to delete cache for " + package));
      }
    }
  }
</code>```

Body:
I want to make an Android App which will clean the cache of other apps. I have figured out how to do that for Android Version below Marshmallow.

This is what I am using for Android Honeycom and above:

    if (isExternalStorageWritable()) {
        final File externalDataDirectory = new File(Environment
                .getExternalStorageDirectory().getAbsolutePath(), "/Android/data");

        final String externalCachePath = externalDataDirectory.getAbsolutePath() +
                "/%s/cache";

        if (externalDataDirectory.isDirectory()) {
            final File[] files = externalDataDirectory.listFiles();

            for (File file : files) {
                if (!deleteDirectory(new File(String.format(externalCachePath,
                        file.getName())), true)) {
                    Log.e(TAG, "External storage suddenly becomes unavailable");

                    return false;
                }
            }
        } else {
            Log.e(TAG, "External data directory is not a directory!");
        }
    } else {
        Log.d(TAG, "External storage is unavailable");
    }

But I am having an issue to figure out how to do it for Android Version Marshmallow and above.

Other cache cleaners present in the market are able to perform this by taking accessibility permission or any other way?

Body:
If the application is a system app, it can request the android.permission.DELETE_CACHE_FILES and you could use reflection to access the PackageManager.deleteApplicationCacheFiles()

  // Lazily instantiated by reflection
  @Nullable private Method deleteApplicationCacheMethod;

  public ListenableFuture<Void> deleteApplicationCache(String packageName) throws Exception {
    SettableFuture<Void> futureDelete = SettableFuture.create();
    ClearCacheObserver observer = new ClearCacheObserver(packageName, deleteObserver);
    // Invoke deleteApplicationCacheFiles() by reflection
    Method deleteApplicationCacheMethod = deleteApplicationCacheMethod(packageManager);
    deleteApplicationCacheMethod.invoke(packageManager, packageName, observer);
    return futureDelete;
  }

  /** Returns an accessible version of the {@link PackageManager#deleteApplicationCacheFiles}. */
  private static Method deleteApplicationCacheMethod() throws InvocationTargetException {
    if (deleteApplicationCacheMethod == null) {
      deleteApplicationCacheMethod = packageManager
          .getClass()
          .getDeclaredMethod(
               "deleteApplicationCacheFiles", String.class, IPackageDataObserver.class);
     deleteApplicationCacheMethod.setAccessible(true);
   }
   return deleteApplicationCacheMethod;
 }

  /** Wraps a Guava Future in a IPackageDataObserver. */
  private static class ClearCacheObserver extends IPackageDataObserver.Stub {
    final String packageName;
    final SettableFuture<Void> futureDelete;

    ClearCacheObserver(String packageName, SettableFuture<Void> futureDelete) {
      this.packageName = packageName;
      this.futureDelete = futureDelete;
    }

    @Override
    public void onRemoveCompleted(String package, boolean succeeded) {
      if (!packageName.equals(package))) {
        return;
      }
      if (succeeded) {
        futureDelete.set(null);
      } else {
        futureDelete.setException(new Exception("Failed to delete cache for " + package));
      }
    }
  }


问:
linux: Print String at The End of Each Output Line
I execute below script

```<code>grep -i 'Exception' Exceptions.log |
sort |
uniq -c |
sort -n
</code>```

and get below result (each time result set will be different)

```<code>6 java.lang.NullPointerException
48 java.sql.SQLException
64 excep.NotFoundException
671 exception.ParseErrorException
690 Exception
</code>```

Actually I want to print the filename as well at the start or end of each line

```<code>6 java.lang.NullPointerException Exceptions
48 java.sql.SQLException Exceptions
64 excep.NotFoundException Exceptions
671 exception.ParseErrorException Exceptions
690 Exception Exceptions
</code>```

OR

```<code>Exceptions 6 java.lang.NullPointerException
Exceptions 48 java.sql.SQLException
Exceptions 64 excep.NotFoundException
Exceptions 671 exception.ParseErrorException
Exceptions 690 Exception
</code>```

Please help me to achieve this object.

答:
It seems easiest to tack on a ...| sed -e 's/^/Exceptions.log /' to the pipeline.   But you might just do:

```<code>awk '/Exception/ {a[$0 " " FILENAME]++}
    END {for(i in a) print a[i], i}' Exceptions.log | sort -n
</code>```

Which would allow you to easily search multiple files.  (Eg, just replace Exceptions.log with *)

Body:
I execute below script

grep -i 'Exception' Exceptions.log |
sort |
uniq -c |
sort -n

and get below result (each time result set will be different)

6 java.lang.NullPointerException
48 java.sql.SQLException
64 excep.NotFoundException
671 exception.ParseErrorException
690 Exception

Actually I want to print the filename as well at the start or end of each line

6 java.lang.NullPointerException Exceptions
48 java.sql.SQLException Exceptions
64 excep.NotFoundException Exceptions
671 exception.ParseErrorException Exceptions
690 Exception Exceptions

OR

Exceptions 6 java.lang.NullPointerException
Exceptions 48 java.sql.SQLException
Exceptions 64 excep.NotFoundException
Exceptions 671 exception.ParseErrorException
Exceptions 690 Exception

Please help me to achieve this object.

Body:
It seems easiest to tack on a ...| sed -e 's/^/Exceptions.log /' to the pipeline.   But you might just do:

awk '/Exception/ {a[$0 " " FILENAME]++}
    END {for(i in a) print a[i], i}' Exceptions.log | sort -n

Which would allow you to easily search multiple files.  (Eg, just replace Exceptions.log with *)


问:
Fitting a string into a predetermined pattern?
I have a dataframe column that looks like:

```<code>A002
A0011
A0001
A0001A
A2
A3A
A02
</code>```

and need to fit it into the format A00XXY
i.e.:

```<code>A0002
A0011
A0001
A0001A
A0002
A0003A
A0002
</code>```

I currently have

```<code>df.col.str.lstrip('A0')
for x in df.col.str.contains(r'[0-9]\w{1}$'):
    if x:
        df.col = 'A000' + df.col
    else:
        df.col = 'A00' + df.col
</code>```

But this becomes recursive? What would be the best method to do this?

答:
If you have at lead pandas 0.20, Series.str.replace can use a match object via a callable. So you can do:

```<code>df['col'] = df.col.str.replace(r'A([0-9]{0,4})(\S*)',
                               lambda m: "A00{:02d}{}".format(int(m.group(1)), m.group(2)))
</code>```

If you have an older version of pandas, you can replace the values:

```<code>df['col'] = ["A00{:02d}{}".format(int(m.group(1)), m.group(2))
             for m in [re.match(r'A([0-9]{0,4})(\S*)', k) for k in df.col]]
</code>```

Body:
I have a dataframe column that looks like:

A002
A0011
A0001
A0001A
A2
A3A
A02

and need to fit it into the format A00XXY
i.e.:

A0002
A0011
A0001
A0001A
A0002
A0003A
A0002

I currently have

df.col.str.lstrip('A0')
for x in df.col.str.contains(r'[0-9]\w{1}$'):
    if x:
        df.col = 'A000' + df.col
    else:
        df.col = 'A00' + df.col

But this becomes recursive? What would be the best method to do this?

Body:
If you have at lead pandas 0.20, Series.str.replace can use a match object via a callable. So you can do:

df['col'] = df.col.str.replace(r'A([0-9]{0,4})(\S*)',
                               lambda m: "A00{:02d}{}".format(int(m.group(1)), m.group(2)))

If you have an older version of pandas, you can replace the values:

df['col'] = ["A00{:02d}{}".format(int(m.group(1)), m.group(2))
             for m in [re.match(r'A([0-9]{0,4})(\S*)', k) for k in df.col]]


问:
Check if user is already logged in and skip if it is true
I am creating web scraping code to login to website and input some data. There is login form before getting to the actual page. My code works there is login first. However website does not ask to login in if you have already logged in. Is there any way to check if login is needed or not?

Here is my code:

```<code>Sub ChechAutomate()
    Dim ie As New InternetExplorer, url As String, ws As Worksheet

    Set ws = ThisWorkbook.Sheets("Other Data")

    url = "https://infra.com/"

    With ie
        .Visible = True
        .Navigate2 url

        While .Busy Or .ReadyState < 4: DoEvents: Wend

        With .Document
            .querySelector("[name=userName]").Value = "username"
            .querySelector("[name=password]").Value = "password123"
            .querySelector("[type=submit]").Click

            'While .Busy Or .ReadyState < 4: DoEvents: Wend

            .querySelector("[id=companySearchKeyData]").Value = ws.Range("T24").Value
            .querySelector("[type=submit]").Click
        End With

    End With

End Sub
</code>```

答:
You can create a conditional statement to check which page you are on. In that case the following logic might help:</p>

```<code>Sub ChechAutomate()
    Dim IE As New InternetExplorer, url As String, ws As Worksheet
    Dim Html As HTMLDocument, idCheck As Object

    Set ws = ThisWorkbook.Sheets("Other Data")

    url = "https://infra.com/"

    With IE
        .Visible = True
        .Navigate2 url
        While .Busy Or .readyState < 4: DoEvents: Wend
        Set Html = .document
    End With

    Set idCheck = Html.querySelector("#login-bis-id-btn")
    If Not idCheck Is Nothing Then
        Html.querySelector("[name=userName]").Value = "username"
        Html.querySelector("[name=password]").Value = "password123"
        Html.querySelector("[type=submit]").Click
        While IE.Busy Or IE.readyState < 4: DoEvents: Wend
    Else:
        Debug.Print "You are already logged-in"
    End If

    'I don't know the role of the following two lines, though

    Html.querySelector("[id=companySearchKeyData]").Value = ws.Range("T24").Value
    Html.querySelector("[type=submit]").Click
End Sub
</code>```

Body:
I am creating web scraping code to login to website and input some data. There is login form before getting to the actual page. My code works there is login first. However website does not ask to login in if you have already logged in. Is there any way to check if login is needed or not?

Here is my code:

Sub ChechAutomate()
    Dim ie As New InternetExplorer, url As String, ws As Worksheet

    Set ws = ThisWorkbook.Sheets("Other Data")

    url = "https://infra.com/"

    With ie
        .Visible = True
        .Navigate2 url

        While .Busy Or .ReadyState < 4: DoEvents: Wend

        With .Document
            .querySelector("[name=userName]").Value = "username"
            .querySelector("[name=password]").Value = "password123"
            .querySelector("[type=submit]").Click

            'While .Busy Or .ReadyState < 4: DoEvents: Wend

            .querySelector("[id=companySearchKeyData]").Value = ws.Range("T24").Value
            .querySelector("[type=submit]").Click
        End With

    End With

End Sub

Body:
You can create a conditional statement to check which page you are on. In that case the following logic might help:

Sub ChechAutomate()
    Dim IE As New InternetExplorer, url As String, ws As Worksheet
    Dim Html As HTMLDocument, idCheck As Object

    Set ws = ThisWorkbook.Sheets("Other Data")

    url = "https://infra.com/"

    With IE
        .Visible = True
        .Navigate2 url
        While .Busy Or .readyState < 4: DoEvents: Wend
        Set Html = .document
    End With

    Set idCheck = Html.querySelector("#login-bis-id-btn")
    If Not idCheck Is Nothing Then
        Html.querySelector("[name=userName]").Value = "username"
        Html.querySelector("[name=password]").Value = "password123"
        Html.querySelector("[type=submit]").Click
        While IE.Busy Or IE.readyState < 4: DoEvents: Wend
    Else:
        Debug.Print "You are already logged-in"
    End If

    'I don't know the role of the following two lines, though

    Html.querySelector("[id=companySearchKeyData]").Value = ws.Range("T24").Value
    Html.querySelector("[type=submit]").Click
End Sub


问:
Calling a function from beanstalk
I have a function in PHP that does some task that needs to call another function asynchronously.

```<code>function doTask1() {
    // some task
    asyncTask()
}
</code>```

I did some research and was told I need to use beanstalk to achieve the same, but I am confused about how to achieve it, As I am not able to find any documentation or tutorials to do the same.

heres what the async function looks like

```<code>function asyncTask(){
// raise an event
console.log("event raised");
}
</code>```

The idea is the function doTask1() should go ahead and complete irrespective of whatever happens in asyncTask();.

答:
The way we manage this here is to launch the second task from a php cli.

In Task1 :

Put the params you want to pass to the async function in a tube

call a script with your async function

Continue your Task1...

In Task2 :

Open Beanstalk tube

retrieve the params

do what you need !

function doTask1() {
    // some task

    // 1. Open the tube (here in a Phalcon framework app) and fill the params
    $queue = $this->di->getShared("queue", ["tube" => "myAsyncTube"]);
    $idQueue = $queue->put([
        "myparam1" => $this->param1,
        "myparam2" => $this->param2
    ],[
        "priority" => 250,
        "delay" => 10,
        "ttr" => 3600
    ]);

    // 2. Call the async task (man bash !)
    exec('bash -c "exec nohup setsid php -q /var/www/asyncTask.php /dev/null 2>&1 &"');

    // finish some tasks
}
```

<p>And in the asyncTask.php :</p>

```<?php
    // 1. Get the tube
    $queue = $this->di->getShared("queue", ["tube" => "myAsyncTube"]);
    // 2. Execute all the queued tasks of the tube
    While($job = $queue->peekReady() !== false){
          $job = $queue->reserve();
          $message = $job->getBody();

          $this->param1 = $message['param1'];
          $this->param2 = $message['param2'];

          // Do all the time consuming job you want !
    }
```

<p>Notes on the bash params :</p>

<ul>
<li>nohup : detach job from session (so it will continue)</li>
<li>setsid : in a new session (separate env)</li>
<li>php : could be almost any executable binary you want !</li>
<li>/var/www/asyncTask.php : the file with your second function</li>
<li>/dev/null 2>&1 : we don't need logs so redirect all to trash</li>
<li>& : this one is the key : run this backward and return to the prompt, so the exec() could finish, and the task1 could continue !</li>
</ul>

<p>Notice also that as the task2 runs in backward, it can't return something to task1, but it can put the response in an other tube to notify other subscribers that the task is done, etc. !</p>

<p>++</p>

```Rom1deTroyes
```

Title: Calling a function from beanstalk

Body:
I have a function in PHP that does some task that needs to call another function asynchronously.

function doTask1() {
    // some task
    asyncTask()
}

I did some research and was told I need to use beanstalk to achieve the same, but I am confused about how to achieve it, As I am not able to find any documentation or tutorials to do the same.

heres what the async function looks like

function asyncTask(){
// raise an event
console.log("event raised");
}

The idea is the function doTask1() should go ahead and complete irrespective of whatever happens in asyncTask();.

Body:
The way we manage this here is to launch the second task from a php cli.

In Task1 :

Put the params you want to pass to the async function in a tube

call a script with your async function

Continue your Task1...

In Task2 :

Open Beanstalk tube

retrieve the params

do what you need !

function doTask1() {
    // some task

    // 1. Open the tube (here in a Phalcon framework app) and fill the params
    $queue = $this->di->getShared("queue", ["tube" => "myAsyncTube"]);
    $idQueue = $queue->put([
        "myparam1" => $this->param1,
        "myparam2" => $this->param2
    ],[
        "priority" => 250,
        "delay" => 10,
        "ttr" => 3600
    ]);

    // 2. Call the async task (man bash !)
    exec('bash -c "exec nohup setsid php -q /var/www/asyncTask.php /dev/null 2>&1 &"');

    // finish some tasks
}

And in the asyncTask.php :

<?php
    // 1. Get the tube
    $queue = $this->di->getShared("queue", ["tube" => "myAsyncTube"]);
    // 2. Execute all the queued tasks of the tube
    While($job = $queue->peekReady() !== false){
          $job = $queue->reserve();
          $message = $job->getBody();

          $this->param1 = $message['param1'];
          $this->param2 = $message['param2'];

          // Do all the time consuming job you want !
    }

Notes on the bash params :

nohup : detach job from session (so it will continue)

setsid : in a new session (separate env)

php : could be almost any executable binary you want !

/var/www/asyncTask.php : the file with your second function

/dev/null 2>&1 : we don't need logs so redirect all to trash

& : this one is the key : run this backward and return to the prompt, so the exec() could finish, and the task1 could continue !

Notice also that as the task2 runs in backward, it can't return something to task1, but it can put the response in an other tube to notify other subscribers that the task is done, etc. !

++

Rom1deTroyes


问:
How to uniquely display SQL
Task 9
What is the total cost of medications prescribed by each vet each day? Only display the vet’s id, date of visit and the total cost. Sort the report by the vet’s id and the date of visit.

This is the output I got:

```<code>VET_ID  VISIT_DATE  TOTAL_COST
V01     21-Apr-2004 36.49
V01     21-Apr-2004 38.49
V01     21-Apr-2004 41.88
V01     21-Apr-2004 40.24
V01     21-Apr-2004 35.99
V01     21-Apr-2004 35.99
V01     27-Apr-2004 32.5
V01     27-Apr-2004 37.89
V01     27-Apr-2004 32
V01     27-Apr-2004 34.5

SELECT Visit.Vet_id, Visit.Visit_Date, (Basic_Cost + Cost) AS Total_Cost
FROM Visit
INNER JOIN Medication ON Visit.Vet_id = Medication.Vet_id
ORDER BY Vet_ID, Visit_Date;
</code>```

This is the expected output:

```<code>Vet Date      Total Cost
--- --------- ------------
V01 21-APR-04 12
V01 27-APR-04 16.25
V01 03-MAY-04 26.5
V01 22-JUN-04 30.39
V02 21-APR-04 38.5
V02 28-APR-04 12.5
V02 16-MAY-04 27.5
V03 28-APR-04 7.99
V03 08-MAY-04 7.99
V03 13-MAY-04 28.25
V04 03-MAY-04 10.49
V04 07-MAY-04 16.75
V04 12-MAY-04 46.05
V04 13-MAY-04 22.5
V04 17-MAY-04 32.85
V04 19-MAY-04 17.5
</code>```

答:
You have to group by Visit.Vet_id, Visit.Visit_Date after the join to calculate the sum:

```<code>SELECT
  Visit.Vet_id,
  Visit.Visit_Date,
  SUM(Medication.Basic_Cost + Medication.Cost) AS Total_Cost
FROM Visit INNER JOIN Medication
ON Visit.Vet_id = Medication.Vet_id
GROUP BY Visit.Vet_id, Visit.Visit_Date
ORDER BY Visit.Vet_id, Visit.Visit_Date;
</code>```

I guess Basic_Cost and Cost are columns in the table Medication, if not change to Visit.

Title: How to uniquely display SQL

Body:
Task 9
What is the total cost of medications prescribed by each vet each day? Only display the vet’s id, date of visit and the total cost. Sort the report by the vet’s id and the date of visit.

This is the output I got:

VET_ID  VISIT_DATE  TOTAL_COST
V01     21-Apr-2004 36.49
V01     21-Apr-2004 38.49
V01     21-Apr-2004 41.88
V01     21-Apr-2004 40.24
V01     21-Apr-2004 35.99
V01     21-Apr-2004 35.99
V01     27-Apr-2004 32.5
V01     27-Apr-2004 37.89
V01     27-Apr-2004 32
V01     27-Apr-2004 34.5

SELECT Visit.Vet_id, Visit.Visit_Date, (Basic_Cost + Cost) AS Total_Cost
FROM Visit
INNER JOIN Medication ON Visit.Vet_id = Medication.Vet_id
ORDER BY Vet_ID, Visit_Date;

This is the expected output:

Vet Date      Total Cost
--- --------- ------------
V01 21-APR-04 12
V01 27-APR-04 16.25
V01 03-MAY-04 26.5
V01 22-JUN-04 30.39
V02 21-APR-04 38.5
V02 28-APR-04 12.5
V02 16-MAY-04 27.5
V03 28-APR-04 7.99
V03 08-MAY-04 7.99
V03 13-MAY-04 28.25
V04 03-MAY-04 10.49
V04 07-MAY-04 16.75
V04 12-MAY-04 46.05
V04 13-MAY-04 22.5
V04 17-MAY-04 32.85
V04 19-MAY-04 17.5

Body:
You have to group by Visit.Vet_id, Visit.Visit_Date after the join to calculate the sum:

SELECT
  Visit.Vet_id,
  Visit.Visit_Date,
  SUM(Medication.Basic_Cost + Medication.Cost) AS Total_Cost
FROM Visit INNER JOIN Medication
ON Visit.Vet_id = Medication.Vet_id
GROUP BY Visit.Vet_id, Visit.Visit_Date
ORDER BY Visit.Vet_id, Visit.Visit_Date;

I guess Basic_Cost and Cost are columns in the table Medication, if not change to Visit.


问:
Graphing time-series data when date column doesn't exist
I have the following data:

```<code>set.seed(12)
df <- rnorm(1260, 0.06, 0.2)
</code>```

These are 5 years worth of daily returns (with 1 year = 252 working days) and what I would like to do is draw a line-chart with months on the x axis. Basically, I would have the sequence Jan:Dec repeated five times on the x-axis, with 21 days being one month.

What I did is the following:

Create a column with months jan-dec repeated 5 times

date <- c("Jan", "Feb", "Mär", "Apr", "Mai", "Jun",
          "Jul", "Aug", "Sep", "Okt", "Nov", "Dez")
date <- rep(date, 5)
```

<ol start="2">
<li>Draw graph</li>
</ol>

<pre class="lang-r prettyprint-override"><code>df %>%
       ggplot(aes(x = date, y = return)) +
       geom_line() +
       labs(title = "Stock return Chart", y = "return", x = "date")
</code>```

Unfortunately I get the following error:

```<code> Error: Aesthetics must be either length 1 or the same as the data (1260): x
</code>```

答:
Try this:</p>

```<code>price <- rnorm(1260, 0.06, 0.2)

date.base <- c("Jan", "Feb", "Mär", "Apr", "Mai", "Jun",
          "Jul", "Aug", "Sep", "Okt", "Nov", "Dez")
date <- rep(date.base, 5)

data.frame(date=factor(date, ordered=TRUE, levels=date.base), price=price) %>%
  ggplot(aes(x = date, y = price)) +
  geom_line() +
  labs(title = "Stock Price Chart", y = "Price", x = "date")
</code>```

Body:
I have the following data:

set.seed(12)
df <- rnorm(1260, 0.06, 0.2)

These are 5 years worth of daily returns (with 1 year = 252 working days) and what I would like to do is draw a line-chart with months on the x axis. Basically, I would have the sequence Jan:Dec repeated five times on the x-axis, with 21 days being one month.

What I did is the following:

Create a column with months jan-dec repeated 5 times

date <- c("Jan", "Feb", "Mär", "Apr", "Mai", "Jun",
          "Jul", "Aug", "Sep", "Okt", "Nov", "Dez")
date <- rep(date, 5)

Draw graph

df %>%
       ggplot(aes(x = date, y = return)) +
       geom_line() +
       labs(title = "Stock return Chart", y = "return", x = "date")

Unfortunately I get the following error:

 Error: Aesthetics must be either length 1 or the same as the data (1260): x

Body:
Try this:

price <- rnorm(1260, 0.06, 0.2)

date.base <- c("Jan", "Feb", "Mär", "Apr", "Mai", "Jun",
          "Jul", "Aug", "Sep", "Okt", "Nov", "Dez")
date <- rep(date.base, 5)

data.frame(date=factor(date, ordered=TRUE, levels=date.base), price=price) %>%
  ggplot(aes(x = date, y = price)) +
  geom_line() +
  labs(title = "Stock Price Chart", y = "Price", x = "date")


问:
assigning an array of strings to another one
I'm trying to parse a C array of strings, assigning a part of the words to one array of strings, and the other part to another array. But when I use the strcpy function, I get segfault. Any idea how to solve this?

```<code>#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])  {
    char **one = malloc(16 * sizeof(char*));
    char **two = malloc(32 * sizeof(char*));

    one[0] = "string";

    strcpy(two[0], one[0]);

    printf("%s\n", two[0]);
}
</code>```

as a result of compiling and running this, I get segfault.

答:
The array two holds space for 32 character pointers after the malloc.
However, these pointers are uninitialized and do not point to valid allocated memory at this point.

Therefore, the strcpy essentially has a destination (two[0]) which is some unknown, uninitialized value. A pointer is essentially a value stored in memory. In this case, the value is grabage.

The write to a garbage address by strcpy generates a SEGFAULT due to the illegal memory access.

To resolve this, make sure that the destination (two[0]) points to a legitimate, writable buffer (perhaps two[0] = malloc(128 * sizeof(char))).

On a related note, look up the similar (but safer) function strncpy.

Body:
I'm trying to parse a C array of strings, assigning a part of the words to one array of strings, and the other part to another array. But when I use the strcpy function, I get segfault. Any idea how to solve this?

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])  {
    char **one = malloc(16 * sizeof(char*));
    char **two = malloc(32 * sizeof(char*));

    one[0] = "string";

    strcpy(two[0], one[0]);

    printf("%s\n", two[0]);
}

as a result of compiling and running this, I get segfault.


问:
Some confusion about Firebase regarding static vs dynamic pages
So according to docs I've read, a webpage written in html code which includes script src="some_JavaScript_file.js is always a dynamic page even though the embedded JavaScript only has const sum=3+5 because no matter how simple it is, as long as there's even a tiny amount of backend involved, that webpage is definitely a dynamic webpage. so with that premise(please confirm that the premise I wrote is actually correct), my question is how does it make sense that Firebase claims it runs index.html sitting in Public folder ONLY when it's running a static webpage even though if that index.html file includes script src="some_JavaScript_file.js, it's a dynamic webpage?</p>

答:
Firebase Hosting doesn't interpret the content you host on it in any way. So if there's JavaScript in any of your files, Firebase doesn't execute that JavaScript code on its servers. Same for any other code: Firebase will serve the code as text (or whatever other format you stored it in) to clients that request it.

If your pages contain JavaScript that you want to run in the client's browser, that is precisely what you want. So you can serve a web site that contains client-side JavaScript on Firebase Hosting.

If you have any code that you want to run server-side you will have to look beyond Firebase Hosting. Nowadays you can stay within Google's infrastructure by integrating Firebase Hosting with Cloud Functions or Cloud Run.


问:
Parse business hours Time Slots and Week Days from JSON array with PHP
Can't figure out how to properly parse a JSON array with PHP.

In my script, I have a foreach statement that parses a local JSON file, extract data and insert it on the database.

Everything is ok except the parsing of the week and business hours.

This is what i've done:

```<code>$openingHours = $json_data['openingHours'];
</code>```

every json file may return an array with different rows like in this output:

```<code>example 1:
"openingHours" : [
"Su 09:00 - 23:59",
"Mo 00:00 - 23:59",
"Tu 00:00 - 13:00, 15:30 - 19:30",
"We 08:30 - 13:00, 15:30 - 19:30",
"Th 08:30 - 13:00, 15:30 - 19:30",
"Fr 08:30 - 13:00, 15:30 - 19:30",
"Sa 08:30 - 13:00, 15:30 - 19:30" ]

 exampe 2:
"openingHours" : [
"Mo 08:00 - 13:00, 16:00 - 20:00",
"Tu 08:00 - 13:00, 16:00 - 20:00",
"We 08:00 - 13:00, 16:00 - 20:00",
"Th 08:00 - 13:00, 16:00 - 20:00",
"Fr 08:00 - 13:00, 16:00 - 20:00",
"Sa 08:00 - 13:00, 16:00 - 20:00" ]

 example 3:
 "openingHours" : [
"Mo 08:00 - 13:00, 16:00 - 20:00",
"We 08:00 - 13:00, 16:00 - 20:00",
"Th 08:00 - 13:00, 16:00 - 20:00",
"Sa 08:00 - 13:00, 16:00 - 20:00" ]
</code>```

As you can see, in the first json I have all 7 days, on the second example there are 6 days from Monday to Saturday, and in the third example there are 4 days Mo-We-Th-Sa

So I'm going to create a foreach statement to output the data;

```<code>foreach ($openingHours as $k_day=>$v_day) {

    $openHrs = $openingHours[$k_day];
    echo print_r($openHrs)."<br>";

}
</code>```

it produce an output like this:

```<code>FILE 1:
Mo 08:30 - 12:30, 16:00 - 20:00
Tu 08:30 - 12:30, 16:00 - 20:00
We 08:30 - 12:30, 16:00 - 20:00
Th 16:00 - 20:00
Fr 08:30 - 12:30, 16:00 - 20:00
Sa 08:30 - 12:30, 16:00 - 20:00

FILE 2:
Su 09:00 - 23:59
Mo 00:00 - 23:59
Tu 00:00 - 13:00, 15:30 - 19:30
We 08:30 - 13:00, 15:30 - 19:30
Th 08:30 - 13:00, 15:30 - 19:30
Sa 08:30 - 13:00, 15:30 - 19:30

FILE N:
.....
</code>```

At this point i need to create some rules to properly format and extract days and business hours from array.

First of all I have to declare days of the week that start from Sunday

```<code>0 - Su
1 - Mo
2 - Tu
3 - We
4 - Th
5 - Fr
6 - Sa
</code>```

Then, check if there all week string (Su - Mo -Tu...) in array and if some day is missing, add them to the list in a correct position.

As in this example

```<code>"openingHours" : [
"Mo 08:00 - 13:00, 16:00 - 20:00",
"We 08:00 - 13:00",
"Th 08:00 - 13:00, 16:00 - 20:00",
"Sa 08:00 - 13:00, 16:00 - 20:00" ]
</code>```

the days: Su - Tu - Fr, doesn't exist (it means that in these days the Shop is closed).

On "Wednesday" it's open only from 08:00 to 13:00, and the 3rd and 4th-time slots don't exist. It means that I need to insert 2-time slots.
Obviously for closed days i need to insert the time slots too ("00:00 - 00:00, 00:00 - 00:00").

```<code>0 - <-- insert
1 - Mo
2 - <-- insert
3 - We --> add "00:00 - 00:00"
4 - Th
5 - <-- insert
6 - Sa
</code>```

Summing up,
all days rows and their slots must be populated with proper data.

At the last point, before pass the data to the database, I need the properly parameterize variables.

This is mine CREATE TABLE statement of the table where i want to put data:

```<code>CREATE TABLE `business_hours_temp` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`place_id` INT(11) NOT NULL,
`day` INT(1) NOT NULL,
`open_1` TIME NOT NULL,
`close_1` TIME NOT NULL,
`open_2` TIME NOT NULL,
`close_2` TIME NOT NULL,
PRIMARY KEY (`id`),
INDEX `place_id` (`place_id`)
)
 COLLATE='utf8mb4_unicode_ci'
 ENGINE=InnoDB
 AUTO_INCREMENT=12;
</code>```

and this is an INSERT INTO statement

```<code>$stmt_hours = $conn->prepare(
    'INSERT INTO business_hours_temp( place_id, day, open_1, close_1, open_2, close_2 )
     VALUES(:place_id, :field_id, :field_value)');
$stmt_hours->bindValue(':place_id', $place_id);
$stmt_hours->bindValue(':day', $day);
$stmt_hours->bindValue(':open_1', $open_1);
$stmt_hours->bindValue(':close_1', $close_1);
$stmt_hours->bindValue(':open_2', $open_2);
$stmt_hours->bindValue(':close_2', $close_2);
$stmt_hours->execute();
</code>```

I need to get vals for $day - $open_1 - $close_1 - $open_2 - $close_2

Thank you guys for any help.

答:
Thanx Jimmix!
It Works!

I just make some little changes to catch the values for the variables i wanted.
The code has comments. Thnak you again.

```<code>foreach($resultFilledList as $result) {
    $line = '';
    $line .= $daysLut2[$result['dayNo']];
    $line .= ' ' . $result['open1'];
    $line .= ', ' . $result['open2'];

    $lineList[] = $line;

    //FOR STORING DATA IN DB
    //get DAY - INT
    $day = $daysLut2[$result['dayNo']];

    // SPLIT/EXPLODE Main slot 1 and 2
    // and get time_slot 1,2, 3 and 4
    // trim the EXPLODE and add ":00" for proper MySQL TIME type
    $main_slot_1 = $result['open1'];
    $main_slot_1_expl = explode('-',$main_slot_1,2);

    $main_slot_2 = $result['open2'];
    $main_slot_2_expl = explode('-',$main_slot_2,2);

    $time_slot_1 = trim($main_slot_1_expl[0], ' ').":00";
    $time_slot_2 = trim($main_slot_1_expl[1], ' ').":00";
    $time_slot_3 = trim($main_slot_2_expl[0], ' ').":00";
    $time_slot_4 = trim($main_slot_2_expl[1], ' ').":00";
    }
</code>```

Body:
Can't figure out how to properly parse a JSON array with PHP.

In my script, I have a foreach statement that parses a local JSON file, extract data and insert it on the database.

Everything is ok except the parsing of the week and business hours.

This is what i've done:

$openingHours = $json_data['openingHours'];

every json file may return an array with different rows like in this output:

example 1:
"openingHours" : [
"Su 09:00 - 23:59",
"Mo 00:00 - 23:59",
"Tu 00:00 - 13:00, 15:30 - 19:30",
"We 08:30 - 13:00, 15:30 - 19:30",
"Th 08:30 - 13:00, 15:30 - 19:30",
"Fr 08:30 - 13:00, 15:30 - 19:30",
"Sa 08:30 - 13:00, 15:30 - 19:30" ]

 exampe 2:
"openingHours" : [
"Mo 08:00 - 13:00, 16:00 - 20:00",
"Tu 08:00 - 13:00, 16:00 - 20:00",
"We 08:00 - 13:00, 16:00 - 20:00",
"Th 08:00 - 13:00, 16:00 - 20:00",
"Fr 08:00 - 13:00, 16:00 - 20:00",
"Sa 08:00 - 13:00, 16:00 - 20:00" ]

 example 3:
 "openingHours" : [
"Mo 08:00 - 13:00, 16:00 - 20:00",
"We 08:00 - 13:00, 16:00 - 20:00",
"Th 08:00 - 13:00, 16:00 - 20:00",
"Sa 08:00 - 13:00, 16:00 - 20:00" ]

As you can see, in the first json I have all 7 days, on the second example there are 6 days from Monday to Saturday, and in the third example there are 4 days Mo-We-Th-Sa

So I'm going to create a foreach statement to output the data;

foreach ($openingHours as $k_day=>$v_day) {

    $openHrs = $openingHours[$k_day];
    echo print_r($openHrs)."
";

}

it produce an output like this:

FILE 1:
Mo 08:30 - 12:30, 16:00 - 20:00
Tu 08:30 - 12:30, 16:00 - 20:00
We 08:30 - 12:30, 16:00 - 20:00
Th 16:00 - 20:00
Fr 08:30 - 12:30, 16:00 - 20:00
Sa 08:30 - 12:30, 16:00 - 20:00

FILE 2:
Su 09:00 - 23:59
Mo 00:00 - 23:59
Tu 00:00 - 13:00, 15:30 - 19:30
We 08:30 - 13:00, 15:30 - 19:30
Th 08:30 - 13:00, 15:30 - 19:30
Sa 08:30 - 13:00, 15:30 - 19:30

FILE N:
.....

At this point i need to create some rules to properly format and extract days and business hours from array.

First of all I have to declare days of the week that start from Sunday

0 - Su
1 - Mo
2 - Tu
3 - We
4 - Th
5 - Fr
6 - Sa

Then, check if there all week string (Su - Mo -Tu...) in array and if some day is missing, add them to the list in a correct position.

As in this example

"openingHours" : [
"Mo 08:00 - 13:00, 16:00 - 20:00",
"We 08:00 - 13:00",
"Th 08:00 - 13:00, 16:00 - 20:00",
"Sa 08:00 - 13:00, 16:00 - 20:00" ]

the days: Su - Tu - Fr, doesn't exist (it means that in these days the Shop is closed).

On "Wednesday" it's open only from 08:00 to 13:00, and the 3rd and 4th-time slots don't exist. It means that I need to insert 2-time slots.
Obviously for closed days i need to insert the time slots too ("00:00 - 00:00, 00:00 - 00:00").

0 - <-- insert
1 - Mo
2 - <-- insert
3 - We --> add "00:00 - 00:00"
4 - Th
5 - <-- insert
6 - Sa

Summing up,
all days rows and their slots must be populated with proper data.

At the last point, before pass the data to the database, I need the properly parameterize variables.

This is mine CREATE TABLE statement of the table where i want to put data:

CREATE TABLE `business_hours_temp` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`place_id` INT(11) NOT NULL,
`day` INT(1) NOT NULL,
`open_1` TIME NOT NULL,
`close_1` TIME NOT NULL,
`open_2` TIME NOT NULL,
`close_2` TIME NOT NULL,
PRIMARY KEY (`id`),
INDEX `place_id` (`place_id`)
)
 COLLATE='utf8mb4_unicode_ci'
 ENGINE=InnoDB
 AUTO_INCREMENT=12;

and this is an INSERT INTO statement

$stmt_hours = $conn->prepare(
    'INSERT INTO business_hours_temp( place_id, day, open_1, close_1, open_2, close_2 )
     VALUES(:place_id, :field_id, :field_value)');
$stmt_hours->bindValue(':place_id', $place_id);
$stmt_hours->bindValue(':day', $day);
$stmt_hours->bindValue(':open_1', $open_1);
$stmt_hours->bindValue(':close_1', $close_1);
$stmt_hours->bindValue(':open_2', $open_2);
$stmt_hours->bindValue(':close_2', $close_2);
$stmt_hours->execute();

I need to get vals for $day - $open_1 - $close_1 - $open_2 - $close_2

Thank you guys for any help.

Body:
Thanx Jimmix!
It Works!

I just make some little changes to catch the values for the variables i wanted.
The code has comments. Thnak you again.

foreach($resultFilledList as $result) {
    $line = '';
    $line .= $daysLut2[$result['dayNo']];
    $line .= ' ' . $result['open1'];
    $line .= ', ' . $result['open2'];

    $lineList[] = $line;

    //FOR STORING DATA IN DB
    //get DAY - INT
    $day = $daysLut2[$result['dayNo']];

    // SPLIT/EXPLODE Main slot 1 and 2
    // and get time_slot 1,2, 3 and 4
    // trim the EXPLODE and add ":00" for proper MySQL TIME type
    $main_slot_1 = $result['open1'];
    $main_slot_1_expl = explode('-',$main_slot_1,2);

    $main_slot_2 = $result['open2'];
    $main_slot_2_expl = explode('-',$main_slot_2,2);

    $time_slot_1 = trim($main_slot_1_expl[0], ' ').":00";
    $time_slot_2 = trim($main_slot_1_expl[1], ' ').":00";
    $time_slot_3 = trim($main_slot_2_expl[0], ' ').":00";
    $time_slot_4 = trim($main_slot_2_expl[1], ' ').":00";
    }


问:
How to Perfectly stop DispatcherTimer in C# WPF
In my project, when I started and finished the timer with the 'start button' and 'stop button' first time, it would work normally.

But when I pressed the 'start button' again without turning off the program, it started to insert data twice per interval as if two timers were working.

The third and fourth time I repeated, it showed an insertion error as much.

There's  my summarized code below, I think it's not a complete stop. It's a pause and overlap i think.

Did i do something wrong?

```<code>public partial class Window1 : Window
     { DispatcherTimer timer = new DispatcherTimer();

     private void btnStart_Click(object sender, RoutedEventArgs e)
         {
             timer.Interval = TimeSpan.FromMilliseconds(1000);
             timer.Tick += new EventHandler(timer_Tick);
             timer.Start();
         }

     private void timer_Tick(object sender, EventArgs e)
         {
             //data insert
         }

     private void btnStop_Click(object sender, RoutedEventArgs e)
         {
             timer.Stop();
         }
}
</code>```

答:
You're adding a new Tick handler each time you click the Button. You may also want to check if the timer is already running before starting it again. Otherwise you would reset the interval.

Move the first two lines of btnStart_Click to a Window1 constructor:

```<code>private readonly DispatcherTimer timer = new DispatcherTimer();

public Window1()
{
    timer.Interval = TimeSpan.FromMilliseconds(1000);
    timer.Tick += new EventHandler(timer_Tick);
}

private void btnStart_Click(object sender, RoutedEventArgs e)
{
    if (!timer.IsEnabled)
    {
        timer.Start();
    }
}

private void btnStop_Click(object sender, RoutedEventArgs e)
{
    timer.Stop();
}

private void timer_Tick(object sender, EventArgs e)
{
    //data insert
}
</code>```

As further improvements you could do the following:

enable and disable the Start and Stop Buttons according to the IsEnabled state of the timer

replace the two Buttons by a single ToggleButton

bind the ToggleButton's IsChecked property to the IsEnabled property of the timer.

move the timer code to a view model

Body:
In my project, when I started and finished the timer with the 'start button' and 'stop button' first time, it would work normally.

But when I pressed the 'start button' again without turning off the program, it started to insert data twice per interval as if two timers were working.

The third and fourth time I repeated, it showed an insertion error as much.

There's  my summarized code below, I think it's not a complete stop. It's a pause and overlap i think.

Did i do something wrong?

public partial class Window1 : Window
     { DispatcherTimer timer = new DispatcherTimer();

     private void btnStart_Click(object sender, RoutedEventArgs e)
         {
             timer.Interval = TimeSpan.FromMilliseconds(1000);
             timer.Tick += new EventHandler(timer_Tick);
             timer.Start();
         }

     private void timer_Tick(object sender, EventArgs e)
         {
             //data insert
         }

     private void btnStop_Click(object sender, RoutedEventArgs e)
         {
             timer.Stop();
         }
}

Body:
You're adding a new Tick handler each time you click the Button. You may also want to check if the timer is already running before starting it again. Otherwise you would reset the interval.

Move the first two lines of btnStart_Click to a Window1 constructor:

private readonly DispatcherTimer timer = new DispatcherTimer();

public Window1()
{
    timer.Interval = TimeSpan.FromMilliseconds(1000);
    timer.Tick += new EventHandler(timer_Tick);
}

private void btnStart_Click(object sender, RoutedEventArgs e)
{
    if (!timer.IsEnabled)
    {
        timer.Start();
    }
}

private void btnStop_Click(object sender, RoutedEventArgs e)
{
    timer.Stop();
}

private void timer_Tick(object sender, EventArgs e)
{
    //data insert
}

As further improvements you could do the following:

enable and disable the Start and Stop Buttons according to the IsEnabled state of the timer

replace the two Buttons by a single ToggleButton

bind the ToggleButton's IsChecked property to the IsEnabled property of the timer.

move the timer code to a view model


问:
Mysql Filter data using Timestamp stored in table
I have stored bill date in timestamp in mysql.

In reports, i get from and to date in dd-mm-YYYY format.In query I have used like this,

```<code>WHERE  (from_unixtime(bill.bill_date,"%d-%m-%Y")) >='06-04-2019' AND (from_unixtime(bill.bill_date,"%d-%m-%Y")) <= '30-04-2019'
</code>```

But the data 06/05/2019 also fetched. I don't know why it is happening.

答:
Have you tried to use between instead?

WHERE (from_unixtime(bill.bill_date,"%d-%m-%Y")) BETWEEN '06-04-2019' AND '30-04-2019'
```

Body:
I have stored bill date in timestamp in mysql.

In reports, i get from and to date in dd-mm-YYYY format.In query I have used like this,

WHERE  (from_unixtime(bill.bill_date,"%d-%m-%Y")) >='06-04-2019' AND (from_unixtime(bill.bill_date,"%d-%m-%Y")) <= '30-04-2019'

But the data 06/05/2019 also fetched. I don't know why it is happening.


问:
Controller instance variable not renders at JS view
I have controller:

```<code>class CommentariesController < ApplicationController

  before_action :authenticate_user!
  before_action :find_commentary, only: [:update, :destroy]
  before_action :find_commentable, only: [:create]

  def create
    @commentary = @commentable.commentaries.new(commentary_params)
    @commentary.user_id = current_user.id
    @commentary.save!
  end

  def update
    @commentary.update(commentary_params) if current_user.authorized_for?(@commentary)
  end

  def destroy
    @commentary.destroy  if current_user.authorized_for?(@commentary)
  end

  private

  def find_commentary
    @commentary = Commentary.find(params[:id])
  end

  def commentary_params
    params.require(:commentary).permit(:body)
  end

  def find_commentable
    if params[:question_id]
      @commentable = Question.find(params[:question_id])
    elsif params[:answer_id]
      @commentable = Answer.find(params[:answer_id])
    end
  end
end
</code>```

And view for it's create action:

```<code>("#<% @commentary.commentable_type.underscore %>-<% @commentary.id %>").append("<% j render @commentary %>")
</code>```

_commentary.html.slim:

```<code>div class='d-flex justify-content-end mb-2'
  div class='card col-10'
    div class='card-body small text-muted' = commentary.body

</code>```

When create action is being processed, all is right, commentaries are being created, and saved to the DB successfully, but instead of jQuery adds a commentary html code rendered, I get no errors, but such response:

```<code>$("#-").append("")
</code>```

I can't realize what happens here, so that I get no errors, commentaries are saved, but I get empty commentary object fields.

答:
There is a difference between <% %> and <%= %> in ERB, first one doesnt output anything, the second one does.

```<code>$("#<% @commentary.commentable_type.underscore %>-<% @commentary.id %>")
</code>```

Shoud be:

```<code>$("#<%= @commentary.commentable_type.underscore %>-<%= @commentary.id %>")
</code>```

Body:
I have controller:

class CommentariesController < ApplicationController

  before_action :authenticate_user!
  before_action :find_commentary, only: [:update, :destroy]
  before_action :find_commentable, only: [:create]

  def create
    @commentary = @commentable.commentaries.new(commentary_params)
    @commentary.user_id = current_user.id
    @commentary.save!
  end

  def update
    @commentary.update(commentary_params) if current_user.authorized_for?(@commentary)
  end

  def destroy
    @commentary.destroy  if current_user.authorized_for?(@commentary)
  end

  private

  def find_commentary
    @commentary = Commentary.find(params[:id])
  end

  def commentary_params
    params.require(:commentary).permit(:body)
  end

  def find_commentable
    if params[:question_id]
      @commentable = Question.find(params[:question_id])
    elsif params[:answer_id]
      @commentable = Answer.find(params[:answer_id])
    end
  end
end

And view for it's create action:

("#<% @commentary.commentable_type.underscore %>-<% @commentary.id %>").append("<% j render @commentary %>")

_commentary.html.slim:

div class='d-flex justify-content-end mb-2'
  div class='card col-10'
    div class='card-body small text-muted' = commentary.body

When create action is being processed, all is right, commentaries are being created, and saved to the DB successfully, but instead of jQuery adds a commentary html code rendered, I get no errors, but such response:

$("#-").append("")

I can't realize what happens here, so that I get no errors, commentaries are saved, but I get empty commentary object fields.

Body:
There is a difference between <% %> and <%= %> in ERB, first one doesnt output anything, the second one does.

$("#<% @commentary.commentable_type.underscore %>-<% @commentary.id %>")

Shoud be:

$("#<%= @commentary.commentable_type.underscore %>-<%= @commentary.id %>")