问:
How can I convert a UTC timestamp to local time, seconds past the hour?
I have a large data set with timestamps that are in UTC time in milliseconds. I'm synchronizing this data set with another's who has timestamps of microseconds past the hour, so I need to convert the first to local time, in seconds past the hour.

Most of the similar questions I've read on this subject get UTC time from the time() function which gets the current time.

I've tried implementing the following which was pulled from C++ Reference.

The timestamp I'm trying to convert is a double, but I'm not sure how to actually use this value.

An example ts from my data set: 1512695257869

```<code>int main ()
{
  double my_utc_ts; //value acquired from the data set

  time_t rawtime;
  struct tm * ptm;

  time ( &rawtime ); //getting current time
  //rawtime = my_utc_ts;  //this is what I tried and is wrong, and results in a nullptr

  ptm = gmtime ( &rawtime );

  puts ("Current time around the World:");
  printf ("Phoenix, AZ (U.S.) :  %2d:%02d\n", (ptm->tm_hour+MST)%24, ptm->tm_min);

  return 0;
}
</code>```

After I'm able to convert it to a usable gmtime object or whatever, I need to get seconds past the hour... I think I'll be able to figure this part out if I can get the UTC timestamps to successfully convert, but I haven't thought this far ahead.

Guidance would be much appreciated. Thanks in advance.

答:
I'd start by converting the floating point number to a time_t. A time_t is normally a count of seconds since an epoch (most often the POSIX epoch--midnight, 1 Jan 1970), so it sounds like that's going to take little more than a bit of fairly simple math.

So let's assume for the sake of argument that your input uses a different epoch. Just for the sake of argument let's assume it's using an epoch of midnight, 1 jan 1900 instead (and, as noted, it's in milliseconds instead of seconds).

So, to convert that to a time_t, you'd start by dividing by 1000 to convert from milliseconds to seconds. Then you'd subtract off the number of seconds between midnight 1 jan 1900 and midnight 1 jan 1970. Now you have a value you can treat as a time_t that the standard library can deal with1.

Then use localtime to get that same time as a struct tm.

Then zero out the minutes and seconds from that tm, and use mktime to get a time_t representing that time.

Finally, use difftime to get the difference between the two.

1. For the moment, I'm assuming your standard library is based around a standard POSIX epoch, but that's a pretty safe assumption.

Body:
I have a large data set with timestamps that are in UTC time in milliseconds. I'm synchronizing this data set with another's who has timestamps of microseconds past the hour, so I need to convert the first to local time, in seconds past the hour.

Most of the similar questions I've read on this subject get UTC time from the time() function which gets the current time.

I've tried implementing the following which was pulled from C++ Reference.

The timestamp I'm trying to convert is a double, but I'm not sure how to actually use this value.

An example ts from my data set: 1512695257869

int main ()
{
  double my_utc_ts; //value acquired from the data set

  time_t rawtime;
  struct tm * ptm;

  time ( &rawtime ); //getting current time
  //rawtime = my_utc_ts;  //this is what I tried and is wrong, and results in a nullptr

  ptm = gmtime ( &rawtime );

  puts ("Current time around the World:");
  printf ("Phoenix, AZ (U.S.) :  %2d:%02d\n", (ptm->tm_hour+MST)%24, ptm->tm_min);

  return 0;
}

After I'm able to convert it to a usable gmtime object or whatever, I need to get seconds past the hour... I think I'll be able to figure this part out if I can get the UTC timestamps to successfully convert, but I haven't thought this far ahead.

Guidance would be much appreciated. Thanks in advance.


来源: stackexchange

问:
codeigniter $this->image_lib->resize() function not resizing image
i want to resize image, but it not working properly, $this->image_lib->resize()  this function can not resize image. it produce orginal image size. i am upload 600*600  size image. but i want to resize 300*300
please check my code below.</p>

```<code>if( $this->input->post('save')){

        $config['upload_path'] = 'images';
        $config['allowed_types'] = 'jpg|png';
        $config['max_size'] = 1000;
        $config['overwrite'] = false;
        $config['encrypt_name'] = true;
        $this->load->library('upload', $config);

        $this->upload->initialize($config);

        if(!$this->upload->do_upload('user_image')){
            $this->session->set_flashdata('message', $this->upload->display_errors());
            $this->load->view('create',$data);
            return;
        }else{
            $upicture = $this->upload->data();
            $image_data = $upicture;
            $config2['image_library'] = 'gd2';
            $config2['source_image'] = $image_data['full_path']; //get original image
            $config2 ['new_image'] = 'images'; //save as new image //need to create thumbs first
            $config2 ['maintain_ratio'] = false;
            $config2 ['create_thumb'] = false;
            $config2 ['overwrite'] = false;
            $config2['width'] = 300;
            $config2['height'] = 300;
            $this->load->library('image_lib', $config2);
            $this->image_lib->resize();

            $img_name = $upicture['file_name'];
        }

        $this->form_validation->set_rules('student_name', 'Student Name','required');
        $this->form_validation->set_rules('student_email', 'Student Email','required|valid_email|is_unique[std_info.std_email]',['is_unique'=> 'The {field} field is alredy exits']);

        $this->form_validation->set_message('valid_email','This {field} field is invalid');
        //$this->form_validation->set_message('is_unique', 'This {field} is Alreay exist!');

        $receive = $this->input->post(['student_name','student_email','student_about'], TRUE);
        $param = [
            'std_name'  => (string) $receive['student_name'],
            'std_email' => (string) $receive['student_email'],
            'std_about' => (string) $receive['student_about'],
            'images'    => $img_name
        ];
        if($this->form_validation->run()){
            $response = $this->std_model->insert_data('std_info',$param);
            if($response['status'] === 'success'){
                redirect('welcome');
            }
        }else{
            $this->load->view('create',$data);
            return;
        }

    }
</code>```

答:
If neither of the two preferences listed above (create_thumb, and
  new_image) are used, the resizing method will instead target the
  original image for processing.

I tested your code and as to my suspicions, you should do the following:

```<code>$config2['image_library'] = 'gd2';
$config2['source_image'] = $image_data['full_path']; //get original image
//$config2 ['new_image'] = 'images'; //save as new image //need to create thumbs first
$config2 ['maintain_ratio'] = false;
$config2 ['create_thumb'] = false;
//$config2 ['overwrite'] = true;
$config2['width'] = 300;
$config2['height'] = 300;
</code>```

From the documentation on Creating a Copy: "The resizing method will create a copy of the
  image file (and preserve the original) if you set a path and/or a
  new filename using this preference"

https://www.codeigniter.com/userguide3/libraries/image_lib.html

If you want to keep the original and have a thumb, either make a new name for the file in the new_image field as in 'images/someimage.jpg' or set create_thumb as TRUE.

Refactor

I would also highly suggest refactoring your logic. Assuming form validation fails you will left with a lot of orphaned images as every post makes a new image (and you are not overwriting or have known filenames). So first do form validation, then upload, then add to database:

```<code>if ($this->input->post('save')) {
    $this->form_validation->set_rules('student_name', 'Student Name', 'required');
    $this->form_validation->set_rules('student_email', 'Student Email', 'required|valid_email|is_unique[std_info.std_email]', ['is_unique' => 'The {field} field is alredy exits']);
    $this->form_validation->set_message('valid_email', 'This {field} field is invalid');
    if (!$this->form_validation->run()) {
        $this->load->view('create', $data);
        return;
    }
    $config['upload_path'] = 'images';
    $config['allowed_types'] = 'jpg|png';
    $config['max_size'] = 1000;
    $config['overwrite'] = false;
    $config['encrypt_name'] = true;
    $this->load->library('upload', $config);
    $this->upload->initialize($config);
    if (!$this->upload->do_upload('user_image')) {
        $this->session->set_flashdata('message', $this->upload->display_errors());
        $this->load->view('create', $data);
        return;
    }
    $image_data = $this->upload->data();
    $config2['image_library'] = 'gd2';
    $config2['source_image'] = $image_data['full_path']; //get original image
    //$config2['new_image'] = 'images'; //save as new image //need to create thumbs first
    $config2['maintain_ratio'] = false;
    $config2['create_thumb'] = false;
    //$config2['overwrite'] = false;
    $config2['width'] = 300;
    $config2['height'] = 300;
    $this->load->library('image_lib', $config2);
    if (!$this->image_lib->resize()) {
        $this->session->set_flashdata('message', $this->image_lib->display_errors());
        $this->load->view('create', $data);
        return;
    }
    $receive = $this->input->post(['student_name', 'student_email', 'student_about'], TRUE);
    $param = [
        'std_name' => (string) $receive['student_name'],
        'std_email' => (string) $receive['student_email'],
        'std_about' => (string) $receive['student_about'],
        'images' => $image_data['file_name']
    ];
    $response = $this->std_model->insert_data('std_info', $param);
    if ($response['status'] === 'success') {
        redirect('welcome');
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i want to resize image, but it not working properly, $this->image_lib->resize()  this function can not resize image. it produce orginal image size. i am upload 600*600  size image. but i want to resize 300*300
please check my code below.

if( $this->input->post('save')){

        $config['upload_path'] = 'images';
        $config['allowed_types'] = 'jpg|png';
        $config['max_size'] = 1000;
        $config['overwrite'] = false;
        $config['encrypt_name'] = true;
        $this->load->library('upload', $config);

        $this->upload->initialize($config);

        if(!$this->upload->do_upload('user_image')){
            $this->session->set_flashdata('message', $this->upload->display_errors());
            $this->load->view('create',$data);
            return;
        }else{
            $upicture = $this->upload->data();
            $image_data = $upicture;
            $config2['image_library'] = 'gd2';
            $config2['source_image'] = $image_data['full_path']; //get original image
            $config2 ['new_image'] = 'images'; //save as new image //need to create thumbs first
            $config2 ['maintain_ratio'] = false;
            $config2 ['create_thumb'] = false;
            $config2 ['overwrite'] = false;
            $config2['width'] = 300;
            $config2['height'] = 300;
            $this->load->library('image_lib', $config2);
            $this->image_lib->resize();

            $img_name = $upicture['file_name'];
        }

        $this->form_validation->set_rules('student_name', 'Student Name','required');
        $this->form_validation->set_rules('student_email', 'Student Email','required|valid_email|is_unique[std_info.std_email]',['is_unique'=> 'The {field} field is alredy exits']);

        $this->form_validation->set_message('valid_email','This {field} field is invalid');
        //$this->form_validation->set_message('is_unique', 'This {field} is Alreay exist!');

        $receive = $this->input->post(['student_name','student_email','student_about'], TRUE);
        $param = [
            'std_name'  => (string) $receive['student_name'],
            'std_email' => (string) $receive['student_email'],
            'std_about' => (string) $receive['student_about'],
            'images'    => $img_name
        ];
        if($this->form_validation->run()){
            $response = $this->std_model->insert_data('std_info',$param);
            if($response['status'] === 'success'){
                redirect('welcome');
            }
        }else{
            $this->load->view('create',$data);
            return;
        }

    }

Body:
If neither of the two preferences listed above (create_thumb, and
  new_image) are used, the resizing method will instead target the
  original image for processing.

I tested your code and as to my suspicions, you should do the following:

$config2['image_library'] = 'gd2';
$config2['source_image'] = $image_data['full_path']; //get original image
//$config2 ['new_image'] = 'images'; //save as new image //need to create thumbs first
$config2 ['maintain_ratio'] = false;
$config2 ['create_thumb'] = false;
//$config2 ['overwrite'] = true;
$config2['width'] = 300;
$config2['height'] = 300;

From the documentation on Creating a Copy: "The resizing method will create a copy of the
  image file (and preserve the original) if you set a path and/or a
  new filename using this preference"

https://www.codeigniter.com/userguide3/libraries/image_lib.html

If you want to keep the original and have a thumb, either make a new name for the file in the new_image field as in 'images/someimage.jpg' or set create_thumb as TRUE.

Refactor

I would also highly suggest refactoring your logic. Assuming form validation fails you will left with a lot of orphaned images as every post makes a new image (and you are not overwriting or have known filenames). So first do form validation, then upload, then add to database:

if ($this->input->post('save')) {
    $this->form_validation->set_rules('student_name', 'Student Name', 'required');
    $this->form_validation->set_rules('student_email', 'Student Email', 'required|valid_email|is_unique[std_info.std_email]', ['is_unique' => 'The {field} field is alredy exits']);
    $this->form_validation->set_message('valid_email', 'This {field} field is invalid');
    if (!$this->form_validation->run()) {
        $this->load->view('create', $data);
        return;
    }
    $config['upload_path'] = 'images';
    $config['allowed_types'] = 'jpg|png';
    $config['max_size'] = 1000;
    $config['overwrite'] = false;
    $config['encrypt_name'] = true;
    $this->load->library('upload', $config);
    $this->upload->initialize($config);
    if (!$this->upload->do_upload('user_image')) {
        $this->session->set_flashdata('message', $this->upload->display_errors());
        $this->load->view('create', $data);
        return;
    }
    $image_data = $this->upload->data();
    $config2['image_library'] = 'gd2';
    $config2['source_image'] = $image_data['full_path']; //get original image
    //$config2['new_image'] = 'images'; //save as new image //need to create thumbs first
    $config2['maintain_ratio'] = false;
    $config2['create_thumb'] = false;
    //$config2['overwrite'] = false;
    $config2['width'] = 300;
    $config2['height'] = 300;
    $this->load->library('image_lib', $config2);
    if (!$this->image_lib->resize()) {
        $this->session->set_flashdata('message', $this->image_lib->display_errors());
        $this->load->view('create', $data);
        return;
    }
    $receive = $this->input->post(['student_name', 'student_email', 'student_about'], TRUE);
    $param = [
        'std_name' => (string) $receive['student_name'],
        'std_email' => (string) $receive['student_email'],
        'std_about' => (string) $receive['student_about'],
        'images' => $image_data['file_name']
    ];
    $response = $this->std_model->insert_data('std_info', $param);
    if ($response['status'] === 'success') {
        redirect('welcome');
    }
}


问:
Good practice for JSON error response for 400 and 500
I have read many RESTful API design pattern resources.

But I'm not confident for deciding API.

It seems there does not not exist a standard JSON response format.
I need advice for my Json error response as below.

401

jwt token related fail

```<code>{
  code:1,
  message: "no access token"
}

{
  code:2,
  message: "invalid access token"
}

{
  code:3,
  message: "expired access token"
}
</code>```

400

client's insufficient input parameter

```<code>{
  code:20,
  message: "input paramter 'search' is missing"
}
</code>```

client's invalid value request

```<code>{
  code:21,
  message: "invalid serial no"
}
</code>```

client's invalid request format

```<code>{
  code:22,
  message: "input parameter indate is invalid date format"
}
</code>```

500
another mesh-up server's problem

```<code>{
  code:30,
  message: "no reply from external server API"
}
</code>```

program logic error (ex. exception)

```<code>{
  code:31,
  message: "internal server error"
}
</code>```

For 500 cases, I think client also needs more information.
And another concern is "Is error code needed?"

答:
You could use Problem Details for HTTP APIs.

It's a nice format that can be extended easily to provide the client a good way to react on each error/problem appropriately.

https://www.rfc-editor.org/rfc/rfc7807

Here is an example taken from the RFC:

```<code>{
  "type": "https://example.com/probs/out-of-credit",
  "title": "You do not have enough credit.",
  "detail": "Your current balance is 30, but that costs 50.",
  "instance": "/account/12345/msgs/abc",
  "balance": 30,
  "accounts": ["/account/12345", "/account/67890"]
}
</code>```

Body:
I have read many RESTful API design pattern resources.

But I'm not confident for deciding API.

It seems there does not not exist a standard JSON response format.
I need advice for my Json error response as below.

401

jwt token related fail

{
  code:1,
  message: "no access token"
}

{
  code:2,
  message: "invalid access token"
}

{
  code:3,
  message: "expired access token"
}

400

client's insufficient input parameter

{
  code:20,
  message: "input paramter 'search' is missing"
}

client's invalid value request

{
  code:21,
  message: "invalid serial no"
}

client's invalid request format

{
  code:22,
  message: "input parameter indate is invalid date format"
}

500
another mesh-up server's problem

{
  code:30,
  message: "no reply from external server API"
}

program logic error (ex. exception)

{
  code:31,
  message: "internal server error"
}

For 500 cases, I think client also needs more information.
And another concern is "Is error code needed?"

Body:
You could use Problem Details for HTTP APIs.

It's a nice format that can be extended easily to provide the client a good way to react on each error/problem appropriately.

https://www.rfc-editor.org/rfc/rfc7807

Here is an example taken from the RFC:

{
  "type": "https://example.com/probs/out-of-credit",
  "title": "You do not have enough credit.",
  "detail": "Your current balance is 30, but that costs 50.",
  "instance": "/account/12345/msgs/abc",
  "balance": 30,
  "accounts": ["/account/12345", "/account/67890"]
}


问:
My batch script doesn't work. Can anyone tell me why?
I need help with my script. All of the stuff keeps falling through and not doing the goto. Can you help?</p>

```<code>@ECHO OFF
goto joshua
:joshua
Echo Hello my name is Joshua.
echo What is yours?
set /p name=
cls
Echo Hello %name%.
cls
Echo How are you?
set /p feeling=
cls
echo Is this good?
echo Im sorry I am still learning human feelings.
set /p humanfeelings=Yes/No
if %humanfeelings%==Yes goto Good
if %humanfeelings%==No goto Bad
cls
:Good
Echo Well that is pleasent.
Echo Would you like to play a game %name%?
set /p answer=Yes/No
if %answer%==Yes goto startmenu
if %answer%== No goto quit
cls
:Bad
echo That is not good.
echo Would you like to play a game %name%?
set /p answera=Yes/No
if %answera%==Yes goto startmenu
if %answera%== No goto later
cls
:startmenu
start menu.bat
cls
:later
Echo That is fine %name%, maybe later
pause
exit
</code>```

答:
Your original code with line numbers:

```<code>1 :  @ECHO OFF
2 :  goto joshua
3 :  :joshua
4 :  Echo Hello my name is Joshua.
5 :  echo What is yours?
6 :  set /p name=
7 :  cls
8 :  Echo Hello %name%.
9 :  cls
10:  Echo How are you?
11:  set /p feeling=
12:  cls
13:  echo Is this good?
14:  echo Im sorry I am still learning human feelings.
15:  set /p humanfeelings=Yes/No
16:  if %humanfeelings%==Yes goto Good
17:  if %humanfeelings%==No goto Bad
18:  cls
19:  :Good
20:  Echo Well that is pleasent.
21:  Echo Would you like to play a game %name%?
22:  set /p answer=Yes/No
23:  if %answer%==Yes goto startmenu
24:  if %answer%== No goto quit
25:  cls
26:  :Bad
27:  echo That is not good.
28:  echo Would you like to play a game %name%?
29:  set /p answera=Yes/No
30:  if %answera%==Yes goto startmenu
31:  if %answera%== No goto later
32:  cls
33:  :startmenu
34:  start menu.bat
35:  cls
36:  :later
37:  Echo That is fine %name%, maybe later
38:  pause
39:  exit
</code>```

Line 2: goto joshua unnecessary since joshua is at the very next line.

Line 9: cls erases the preceding echo (hides Hello %name%.)

Line 16, 17, 30, and 31: variables should be quoted or else unexpected input (e.g., hell
no!!! or yes, i am.) would cause a syntax error

Line 18, 25, and 32: there is no default case, so if the answer is neither "Yes" nor "No", the script continues to the next line.

I'd also suggest changing these if statements into if-else, and use case-insensitive string comparison with if /I. Try these modifications:

```<code>@echo off

:joshua
echo Hello. My name is Joshua.
echo What is yours?
set /p name=
cls
echo Hello, %name%.
echo How are you?
set /p feeling=
cls

echo Is this good?
echo I'm sorry. I am still learning human feelings.
set /p humanfeelings=Yes/No

if /I "%humanfeelings%"=="yes" (
    goto Good
) else (
    goto Bad
)
cls

:Good
echo Well that is pleasant.
goto AskPlay

:Bad
echo That is not good.

:AskPlay
echo Would you like to play a game, %name%?
set /p answera=Yes/No
if /I "%answera%"=="yes" (
    goto startmenu
) else (
    goto later
)
cls

:startmenu
start menu.bat
cls

:later
echo That is fine, %name%. Maybe later!
pause
exit
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I need help with my script. All of the stuff keeps falling through and not doing the goto. Can you help?

@ECHO OFF
goto joshua
:joshua
Echo Hello my name is Joshua.
echo What is yours?
set /p name=
cls
Echo Hello %name%.
cls
Echo How are you?
set /p feeling=
cls
echo Is this good?
echo Im sorry I am still learning human feelings.
set /p humanfeelings=Yes/No
if %humanfeelings%==Yes goto Good
if %humanfeelings%==No goto Bad
cls
:Good
Echo Well that is pleasent.
Echo Would you like to play a game %name%?
set /p answer=Yes/No
if %answer%==Yes goto startmenu
if %answer%== No goto quit
cls
:Bad
echo That is not good.
echo Would you like to play a game %name%?
set /p answera=Yes/No
if %answera%==Yes goto startmenu
if %answera%== No goto later
cls
:startmenu
start menu.bat
cls
:later
Echo That is fine %name%, maybe later
pause
exit

Body:
Your original code with line numbers:

1 :  @ECHO OFF
2 :  goto joshua
3 :  :joshua
4 :  Echo Hello my name is Joshua.
5 :  echo What is yours?
6 :  set /p name=
7 :  cls
8 :  Echo Hello %name%.
9 :  cls
10:  Echo How are you?
11:  set /p feeling=
12:  cls
13:  echo Is this good?
14:  echo Im sorry I am still learning human feelings.
15:  set /p humanfeelings=Yes/No
16:  if %humanfeelings%==Yes goto Good
17:  if %humanfeelings%==No goto Bad
18:  cls
19:  :Good
20:  Echo Well that is pleasent.
21:  Echo Would you like to play a game %name%?
22:  set /p answer=Yes/No
23:  if %answer%==Yes goto startmenu
24:  if %answer%== No goto quit
25:  cls
26:  :Bad
27:  echo That is not good.
28:  echo Would you like to play a game %name%?
29:  set /p answera=Yes/No
30:  if %answera%==Yes goto startmenu
31:  if %answera%== No goto later
32:  cls
33:  :startmenu
34:  start menu.bat
35:  cls
36:  :later
37:  Echo That is fine %name%, maybe later
38:  pause
39:  exit

Line 2: goto joshua unnecessary since joshua is at the very next line.

Line 9: cls erases the preceding echo (hides Hello %name%.)

Line 16, 17, 30, and 31: variables should be quoted or else unexpected input (e.g., hell
no!!! or yes, i am.) would cause a syntax error

Line 18, 25, and 32: there is no default case, so if the answer is neither "Yes" nor "No", the script continues to the next line.

I'd also suggest changing these if statements into if-else, and use case-insensitive string comparison with if /I. Try these modifications:

@echo off

:joshua
echo Hello. My name is Joshua.
echo What is yours?
set /p name=
cls
echo Hello, %name%.
echo How are you?
set /p feeling=
cls

echo Is this good?
echo I'm sorry. I am still learning human feelings.
set /p humanfeelings=Yes/No

if /I "%humanfeelings%"=="yes" (
    goto Good
) else (
    goto Bad
)
cls

:Good
echo Well that is pleasant.
goto AskPlay

:Bad
echo That is not good.

:AskPlay
echo Would you like to play a game, %name%?
set /p answera=Yes/No
if /I "%answera%"=="yes" (
    goto startmenu
) else (
    goto later
)
cls

:startmenu
start menu.bat
cls

:later
echo That is fine, %name%. Maybe later!
pause
exit


问:
Normalize CSV data before inserting into SQLite database with Pandas or plain SQL
Here is a diagram of what I want to accomplish:

The actual CSV files can have tens of thousands or hundreds of thousands of rows per their equivalent of a Name/Phone combination, which wastes an enormous amount of memory and disk space. I know how to normalize this data once it is actually in the database using SQL, but I wish to avoid copying all those duplicates in the first place and instead insert a foreign key relation. The disk space consumed by repeated values in these columns is considerable.

Currently I am using Python and Pandas to automate the process of creating a SQLite database and inserting the data into it. I have also tried PostgreSQL for this, though found it slower than pandas+sqlite for some reason.

How do I split this data into multiple tables before inserting into the database?

EDIT Because of the size of the files, I am processing them in chunks, like this:

```<code>import glob
import pandas as pd
import sqlite3

def read_nlines(file: str, n: int = 10) -> pd.DataFrame:
    return pd.read_csv(file, nrows=n, comment='#', skip_blank_lines=True,
                       sep='\t', encoding='utf-8')

conn = sqlite3.connect("data.db")
cur = conn.cursor()

files = glob.glob("data/*.txt")

for file in files:
    data = read_nlines(file)
###--->
###---> This is where I want to transform the data, before writing to sql <---###
###--->
    data.to_sql('table',con=conn,if_exists='replace')

conn.close()
</code>```

答:
Feel free to work with whatever data structures you prefer, but this is how it made sense to me.

Load each row in your csv file into a list of two dictionaries. One dictionary for your person-related fields, one for the other fields. You can use the csv library for this - but I imagine if you've gotten this far, you've already got a process in place for this.

Then, create a list of person dictionaries, only adding a dictionary in if it's not in the list.

You can then loop through your original list of lists and add a personKey key to the second dictionary in each of the children lists. Set the key of this list equal to the index of the person dictionary in your list of person dictionaries.

```<code>dictList = [
    [{'Name': 'Bob', 'Phone': '098-765-4321'}, {'S1': 0.36, 'S2': 0.91, 'S3': 0.24}],
    [{'Name': 'Bob', 'Phone': '098-765-4321'}, {'S1': 0.44, 'S2': 0.36, 'S3': 0.78}],
    [{'Name': 'Steve', 'Phone': '768-098-1234'}, {'S1': 0.55, 'S2': 0.15, 'S3': 0.74}]
]

personRecords = []
numberRecords = []
for item in dictList:
    numberRecord = item[1]
    if item[0] not in personRecords:
        personRecords.append(item[0])
    numberRecord['personKey'] = personRecords.index(item[0])
    numberRecords.append(numberRecord)

for person in personRecords:
    print(person)

for record in numberRecords:
    print(record)
</code>```

You can then take each list of dictionaries, parse them into whatever data structures are needed by your database library, and then upload.

Body:
Here is a diagram of what I want to accomplish:

The actual CSV files can have tens of thousands or hundreds of thousands of rows per their equivalent of a Name/Phone combination, which wastes an enormous amount of memory and disk space. I know how to normalize this data once it is actually in the database using SQL, but I wish to avoid copying all those duplicates in the first place and instead insert a foreign key relation. The disk space consumed by repeated values in these columns is considerable.

Currently I am using Python and Pandas to automate the process of creating a SQLite database and inserting the data into it. I have also tried PostgreSQL for this, though found it slower than pandas+sqlite for some reason.

How do I split this data into multiple tables before inserting into the database?

EDIT Because of the size of the files, I am processing them in chunks, like this:

import glob
import pandas as pd
import sqlite3

def read_nlines(file: str, n: int = 10) -> pd.DataFrame:
    return pd.read_csv(file, nrows=n, comment='#', skip_blank_lines=True,
                       sep='\t', encoding='utf-8')

conn = sqlite3.connect("data.db")
cur = conn.cursor()

files = glob.glob("data/*.txt")

for file in files:
    data = read_nlines(file)
###--->
###---> This is where I want to transform the data, before writing to sql <---###
###--->
    data.to_sql('table',con=conn,if_exists='replace')

conn.close()

Body:
Feel free to work with whatever data structures you prefer, but this is how it made sense to me.

Load each row in your csv file into a list of two dictionaries. One dictionary for your person-related fields, one for the other fields. You can use the csv library for this - but I imagine if you've gotten this far, you've already got a process in place for this.

Then, create a list of person dictionaries, only adding a dictionary in if it's not in the list.

You can then loop through your original list of lists and add a personKey key to the second dictionary in each of the children lists. Set the key of this list equal to the index of the person dictionary in your list of person dictionaries.

dictList = [
    [{'Name': 'Bob', 'Phone': '098-765-4321'}, {'S1': 0.36, 'S2': 0.91, 'S3': 0.24}],
    [{'Name': 'Bob', 'Phone': '098-765-4321'}, {'S1': 0.44, 'S2': 0.36, 'S3': 0.78}],
    [{'Name': 'Steve', 'Phone': '768-098-1234'}, {'S1': 0.55, 'S2': 0.15, 'S3': 0.74}]
]

personRecords = []
numberRecords = []
for item in dictList:
    numberRecord = item[1]
    if item[0] not in personRecords:
        personRecords.append(item[0])
    numberRecord['personKey'] = personRecords.index(item[0])
    numberRecords.append(numberRecord)

for person in personRecords:
    print(person)

for record in numberRecords:
    print(record)

You can then take each list of dictionaries, parse them into whatever data structures are needed by your database library, and then upload.


问:
Can I add additional type that will combine multiple json properties when deserializing JSON?
The original JSON C# class structure looks like

```<code> public class Main
    {
        public double temp { get; set; }
        public double temp_min { get; set; }
        public double temp_max { get; set; }
        public double pressure { get; set; }
        public double sea_level { get; set; }
        public double grnd_level { get; set; }
        public int humidity { get; set; }
        public double temp_kf { get; set; }
    }

    public class Weather
    {
        public int id { get; set; }
        public string main { get; set; }
        public string description { get; set; }
        public string icon { get; set; }
    }

    public class Clouds
    {
        public int all { get; set; }
    }

    public class Wind
    {
        public double speed { get; set; }
        public double deg { get; set; }
    }

    public class Snow
    {
        public double? 3h { get; set; }
    }

    public class Sys
    {
        public string pod { get; set; }
    }

    public class Rain
    {
        public double 3h { get; set; }
    }

    public class List
    {
        public int dt { get; set; }
        public Main main { get; set; }
        public IList<Weather> weather { get; set; }
        public Clouds clouds { get; set; }
        public Wind wind { get; set; }
        public Snow snow { get; set; }
        public Sys sys { get; set; }
        public string dt_txt { get; set; }
        public Rain rain { get; set; }
    }

    public class Coord
    {
        public double lat { get; set; }
        public double lon { get; set; }
    }

    public class City
    {
        public int id { get; set; }
        public string name { get; set; }
        public Coord coord { get; set; }
        public string country { get; set; }
    }

    public class Example
    {
        public string cod { get; set; }
        public double message { get; set; }
        public int cnt { get; set; }
        public IList<List> list { get; set; }
        public City city { get; set; }
    }
</code>```

I want to remove some properties and merge other into my types, so at the end I want to get next C# class structure:

```<code>public class WeatherForecast
    {
        [JsonProperty("city")]
        public City City { get; set; }

        [JsonProperty("list")]
        public IList<ClimateIndicators> ClimateIndicators { get; set; }
    }

 public class ClimateIndicators
    {
        public Atmospheric Atmospheric { get; set; }
        public Hydrospheric Hydrospheric { get; set; }
        public Lithospheric Lithospheric { get; set; }
        public DateTime Date { get; set; }

        public IList<WeatherDetails> WeatherDetails { get; set; }
    }

 public class Atmospheric
    {
        [JsonProperty("pressure")]
        public double Pressure { get; set; }
        [JsonProperty("humidity")]
        public int Humidity { get; set; }
        [JsonProperty("sea_level")]
        public double SeaLevel { get; set; }
        [JsonProperty("grnd_level")]
        public double GroundLevel { get; set; }
        [JsonProperty("all")]
        public int Cloudiness { get; set; }
        [JsonProperty("rain")]
        public double? Rain { get; set; }
        [JsonProperty("snow")]
        public double? Snow { get; set; }
    }
</code>```

I am adding custom classification for the weather conditions. So the problem I am facing is that I don't know how to merge multiple JSON Properties into a single class that is a property of another JSON property.

答:
Since the class structure you want has a different shape than the JSON, you will need to create a custom JsonConverter to bridge the differences.  In your case, the WeatherForecast and City classes don't need any special handling (just using the [JsonProperty] attributes is sufficient), but the ClimateIndicators class definitely needs a converter.

Here is what it would look like in code.  The converter works by loading the JSON data for each item of the list array into a temporary JObject.  (Json.Net calls ReadJson once for each item, so that is why there is no loop in the converter.)  From there, SelectToken is used to pick out the values from the various nested item properties needed to populate an instance of the ClimateIndicators class and its supporting class Atmospheric.  The ClimateIndicators instance is then returned to Json.Net, which automatically adds it to the list in the WeatherForecast class.

```<code>class ClimateIndicatorsConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(ClimateIndicators);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JObject obj = JObject.Load(reader);

        Atmospheric atm = new Atmospheric();
        atm.Pressure = (double)obj.SelectToken("main.pressure");
        atm.Humidity = (int)obj.SelectToken("main.humidity");
        atm.SeaLevel = (double)obj.SelectToken("main.sea_level");
        atm.GroundLevel = (double)obj.SelectToken("main.grnd_level");
        atm.Cloudiness = (int)obj.SelectToken("clouds.all");
        atm.Rain = (double?)obj.SelectToken("rain.3h");
        atm.Snow = (double?)obj.SelectToken("snow.3h");

        ClimateIndicators indicators = new ClimateIndicators();
        indicators.Atmospheric = atm;
        indicators.Date = (DateTime)obj.SelectToken("dt_txt");

        return indicators;
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}
</code>```

To use the converter, add a [JsonConverter] attribute to the ClimateIndicators class like this:

```<code>    [JsonConverter(typeof(ClimateIndicatorsConverter))]
    public class ClimateIndicators
    {
        ...
    }
</code>```

Note that you do not need [JsonProperty] attributes on the properties within the ClimateIndicators or Atmospheric class, because the property mapping is being handled by the converter.

Here is a working demo: https://dotnetfiddle.net/Fc9G69

Body:
The original JSON C# class structure looks like

 public class Main
    {
        public double temp { get; set; }
        public double temp_min { get; set; }
        public double temp_max { get; set; }
        public double pressure { get; set; }
        public double sea_level { get; set; }
        public double grnd_level { get; set; }
        public int humidity { get; set; }
        public double temp_kf { get; set; }
    }

    public class Weather
    {
        public int id { get; set; }
        public string main { get; set; }
        public string description { get; set; }
        public string icon { get; set; }
    }

    public class Clouds
    {
        public int all { get; set; }
    }

    public class Wind
    {
        public double speed { get; set; }
        public double deg { get; set; }
    }

    public class Snow
    {
        public double? 3h { get; set; }
    }

    public class Sys
    {
        public string pod { get; set; }
    }

    public class Rain
    {
        public double 3h { get; set; }
    }

    public class List
    {
        public int dt { get; set; }
        public Main main { get; set; }
        public IList<Weather> weather { get; set; }
        public Clouds clouds { get; set; }
        public Wind wind { get; set; }
        public Snow snow { get; set; }
        public Sys sys { get; set; }
        public string dt_txt { get; set; }
        public Rain rain { get; set; }
    }

    public class Coord
    {
        public double lat { get; set; }
        public double lon { get; set; }
    }

    public class City
    {
        public int id { get; set; }
        public string name { get; set; }
        public Coord coord { get; set; }
        public string country { get; set; }
    }

    public class Example
    {
        public string cod { get; set; }
        public double message { get; set; }
        public int cnt { get; set; }
        public IList<List> list { get; set; }
        public City city { get; set; }
    }

I want to remove some properties and merge other into my types, so at the end I want to get next C# class structure:

public class WeatherForecast
    {
        [JsonProperty("city")]
        public City City { get; set; }

        [JsonProperty("list")]
        public IList<ClimateIndicators> ClimateIndicators { get; set; }
    }

 public class ClimateIndicators
    {
        public Atmospheric Atmospheric { get; set; }
        public Hydrospheric Hydrospheric { get; set; }
        public Lithospheric Lithospheric { get; set; }
        public DateTime Date { get; set; }

        public IList<WeatherDetails> WeatherDetails { get; set; }
    }

 public class Atmospheric
    {
        [JsonProperty("pressure")]
        public double Pressure { get; set; }
        [JsonProperty("humidity")]
        public int Humidity { get; set; }
        [JsonProperty("sea_level")]
        public double SeaLevel { get; set; }
        [JsonProperty("grnd_level")]
        public double GroundLevel { get; set; }
        [JsonProperty("all")]
        public int Cloudiness { get; set; }
        [JsonProperty("rain")]
        public double? Rain { get; set; }
        [JsonProperty("snow")]
        public double? Snow { get; set; }
    }

I am adding custom classification for the weather conditions. So the problem I am facing is that I don't know how to merge multiple JSON Properties into a single class that is a property of another JSON property.

Body:
Since the class structure you want has a different shape than the JSON, you will need to create a custom JsonConverter to bridge the differences.  In your case, the WeatherForecast and City classes don't need any special handling (just using the [JsonProperty] attributes is sufficient), but the ClimateIndicators class definitely needs a converter.

Here is what it would look like in code.  The converter works by loading the JSON data for each item of the list array into a temporary JObject.  (Json.Net calls ReadJson once for each item, so that is why there is no loop in the converter.)  From there, SelectToken is used to pick out the values from the various nested item properties needed to populate an instance of the ClimateIndicators class and its supporting class Atmospheric.  The ClimateIndicators instance is then returned to Json.Net, which automatically adds it to the list in the WeatherForecast class.

class ClimateIndicatorsConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(ClimateIndicators);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JObject obj = JObject.Load(reader);

        Atmospheric atm = new Atmospheric();
        atm.Pressure = (double)obj.SelectToken("main.pressure");
        atm.Humidity = (int)obj.SelectToken("main.humidity");
        atm.SeaLevel = (double)obj.SelectToken("main.sea_level");
        atm.GroundLevel = (double)obj.SelectToken("main.grnd_level");
        atm.Cloudiness = (int)obj.SelectToken("clouds.all");
        atm.Rain = (double?)obj.SelectToken("rain.3h");
        atm.Snow = (double?)obj.SelectToken("snow.3h");

        ClimateIndicators indicators = new ClimateIndicators();
        indicators.Atmospheric = atm;
        indicators.Date = (DateTime)obj.SelectToken("dt_txt");

        return indicators;
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

To use the converter, add a [JsonConverter] attribute to the ClimateIndicators class like this:

    [JsonConverter(typeof(ClimateIndicatorsConverter))]
    public class ClimateIndicators
    {
        ...
    }

Note that you do not need [JsonProperty] attributes on the properties within the ClimateIndicators or Atmospheric class, because the property mapping is being handled by the converter.

Here is a working demo: https://dotnetfiddle.net/Fc9G69


问:
How to successfully draw background JPanel once and update foreground JPanel constantly?
I have a custom JLayeredPane, and I am repainting it in my game loop. There are two custom JPanels added into the JLayeredPane. These are foreground and background JPanels. How do I successfully only draw my background JPanel once, (And repaint when window is re-sized or any other reason) to reduce impact on system resources, while continuing to update my foreground JPanel constantly.

To re-iterate, I dont want to constantly repaint the background JPanel in a loop. I want to repaint it only when it is nessessary, as the background does not change. and is large.

In my attempt to do this, I have only drawn the background once. However. the background JPanel is simply not visible. while the foreground JPanel updates as normal. It is almost as if the foreground JPanel paints ontop of the background JPanel, even though I have both of the JPanels set to setOpaque(false)

I have made a mvce which shows my attempt at only drawing the background JPanel once, while updating the foreground JPanel constantly.

The problem with my code is that the background JPanel does not show.

Now. I know that if I were to draw it constantly it would show. But that defeats the purpose of what i'm trying to do. I am trying to only draw it once, and have be seen at the same time

My code successfully only draws the background JPanel once. The problem is that the background JPanel does not show. How do I fix THIS problem

```<code>import javax.swing.*;

import java.awt.*;
import java.awt.event.*;

public class Main extends JLayeredPane {
    static JFrame frame;
    static Main main;
    static Dimension screenSize;
    public Main() {
        JPanel backPanel = new BackPanel();
        JPanel frontPanel = new FrontPanel();
        add(backPanel, new Integer(7));
        add(frontPanel, new Integer(8));

        new Thread(() -> {
            while (true){
                repaint();
            }
        }).start();

    }

    public static void main(String[] args) {
        screenSize = Toolkit.getDefaultToolkit().getScreenSize();

        frame = new JFrame("Game"); // Just use the constructor

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        main = new Main();
        frame.add(main, BorderLayout.CENTER);

        frame.pack();
        frame.setSize(screenSize);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

    }
    public class BackPanel extends JPanel{
        public boolean drawn = false;
        public BackPanel(){
            setVisible(true);
            setOpaque(false);
            setSize(screenSize);
            JLabel test1 = new JLabel("Test1");
            JLabel test2 = new JLabel("Test2");
            add(test1);
            add(test2);
        }
        @Override
        public void paintComponent(Graphics g){
            super.paintComponent(g);
            drawOnce(g);
        }
        public void drawOnce(Graphics g){
            if (!drawn){
                g.setColor(Color.red);
                g.fillRect(0, 0, screenSize.width, 200);
                drawn=true;
            }

        }
    }
    public class FrontPanel extends JPanel{

        public FrontPanel(){
            setVisible(true);
            setOpaque(false);
            setSize(screenSize);
            JLabel test = new JLabel("Test");
            add(test);
        }
        @Override
        public void paintComponent(Graphics g){
            super.paintComponent(g);
            g.setColor(Color.blue);
            g.fillRect(0+screenSize.width/2, 0, screenSize.width/4, 300);
        }
    }
}
</code>```

答:
I don't know if this two lines of code

```<code>super.paintComponent(g);
drawOnce(g);
</code>```

are the root of problem, I sincerly don't remember how paintComponent works (a test could help) but try to swap them :

```<code>drawOnce(g);
super.paintComponent(g);
</code>```

maybe, on your original version, you tells JVM to paint the whole component and, only after the AWTEvent has been added to the queue, to draw what you need.
I guess that the awt's documentation will explain it.

Body:
I have a custom JLayeredPane, and I am repainting it in my game loop. There are two custom JPanels added into the JLayeredPane. These are foreground and background JPanels. How do I successfully only draw my background JPanel once, (And repaint when window is re-sized or any other reason) to reduce impact on system resources, while continuing to update my foreground JPanel constantly.

To re-iterate, I dont want to constantly repaint the background JPanel in a loop. I want to repaint it only when it is nessessary, as the background does not change. and is large.

In my attempt to do this, I have only drawn the background once. However. the background JPanel is simply not visible. while the foreground JPanel updates as normal. It is almost as if the foreground JPanel paints ontop of the background JPanel, even though I have both of the JPanels set to setOpaque(false)

I have made a mvce which shows my attempt at only drawing the background JPanel once, while updating the foreground JPanel constantly.

The problem with my code is that the background JPanel does not show.

Now. I know that if I were to draw it constantly it would show. But that defeats the purpose of what i'm trying to do. I am trying to only draw it once, and have be seen at the same time

My code successfully only draws the background JPanel once. The problem is that the background JPanel does not show. How do I fix THIS problem

import javax.swing.*;

import java.awt.*;
import java.awt.event.*;

public class Main extends JLayeredPane {
    static JFrame frame;
    static Main main;
    static Dimension screenSize;
    public Main() {
        JPanel backPanel = new BackPanel();
        JPanel frontPanel = new FrontPanel();
        add(backPanel, new Integer(7));
        add(frontPanel, new Integer(8));

        new Thread(() -> {
            while (true){
                repaint();
            }
        }).start();

    }

    public static void main(String[] args) {
        screenSize = Toolkit.getDefaultToolkit().getScreenSize();

        frame = new JFrame("Game"); // Just use the constructor

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        main = new Main();
        frame.add(main, BorderLayout.CENTER);

        frame.pack();
        frame.setSize(screenSize);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

    }
    public class BackPanel extends JPanel{
        public boolean drawn = false;
        public BackPanel(){
            setVisible(true);
            setOpaque(false);
            setSize(screenSize);
            JLabel test1 = new JLabel("Test1");
            JLabel test2 = new JLabel("Test2");
            add(test1);
            add(test2);
        }
        @Override
        public void paintComponent(Graphics g){
            super.paintComponent(g);
            drawOnce(g);
        }
        public void drawOnce(Graphics g){
            if (!drawn){
                g.setColor(Color.red);
                g.fillRect(0, 0, screenSize.width, 200);
                drawn=true;
            }

        }
    }
    public class FrontPanel extends JPanel{

        public FrontPanel(){
            setVisible(true);
            setOpaque(false);
            setSize(screenSize);
            JLabel test = new JLabel("Test");
            add(test);
        }
        @Override
        public void paintComponent(Graphics g){
            super.paintComponent(g);
            g.setColor(Color.blue);
            g.fillRect(0+screenSize.width/2, 0, screenSize.width/4, 300);
        }
    }
}

Body:
I don't know if this two lines of code

super.paintComponent(g);
drawOnce(g);

are the root of problem, I sincerly don't remember how paintComponent works (a test could help) but try to swap them :

drawOnce(g);
super.paintComponent(g);

maybe, on your original version, you tells JVM to paint the whole component and, only after the AWTEvent has been added to the queue, to draw what you need.
I guess that the awt's documentation will explain it.


问:
Add active class to woocommerce product category current-menu-item

I've used the below code to add the active class to menu items. The site is 99% Ecomm using Woocommerce and I'm using product categories as top level navigation items. The below code works with almost all items except when being active on a product sub-category.

add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);

function special_nav_class ($classes, $item) {
    if (in_array('current-post-ancestor', $classes) || in_array('current-page-ancestor', $classes) || in_array('current-menu-item', $classes) ){
        $classes[] = 'active ';
    }
    return $classes;
}```

Essentially, I'd like the top level nav item to be marked with the active class even when a sub-category has been selected.

答:
I think the best apporach to this is using javascript or jquery, let's say your menu looks like this :

```<code><nav>
    <ul>
        <li><a href="">Top level</a></li>
        <li><a href="">Top level</a></li>
        <li><a href="">Top level</a>
            <ul>
                <li><a href="">Sub category</a></li>
                <li><a href="">Sub category</a></li>
                <li class="active"><a href="">Sub category</a></li>
                <li><a href="">Sub category</a></li>
            </ul>
        </li>
        <li><a href="">Top level</a></li>
        <li><a href="">Top level</a></li>
    </ul>
</nav>
</code>```

All we need to do is to check which one of the top-level menus has an li with class active in them, so our jquery code looks like this:

```<code><script>
    jQuery(document).ready(function(){
        // Adding class "active" to all top-level menus that contain an li.active item
        $('nav > ul > li').each(function(){
            if( $(this).has('li.active').length ) {
                $(this).addClass('active');
            }
        });
    });
</script>
</code>```

Here's a fiddle

Body:
I've used the below code to add the active class to menu items. The site is 99% Ecomm using Woocommerce and I'm using product categories as top level navigation items. The below code works with almost all items except when being active on a product sub-category.

add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);

function special_nav_class ($classes, $item) {
    if (in_array('current-post-ancestor', $classes) || in_array('current-page-ancestor', $classes) || in_array('current-menu-item', $classes) ){
        $classes[] = 'active ';
    }
    return $classes;
}

Essentially, I'd like the top level nav item to be marked with the active class even when a sub-category has been selected.

Body:
I think the best apporach to this is using javascript or jquery, let's say your menu looks like this :

<nav>
    <ul>
        <li><a href="">Top level</a></li>
        <li><a href="">Top level</a></li>
        <li><a href="">Top level</a>
            <ul>
                <li><a href="">Sub category</a></li>
                <li><a href="">Sub category</a></li>
                <li class="active"><a href="">Sub category</a></li>
                <li><a href="">Sub category</a></li>
            </ul>
        </li>
        <li><a href="">Top level</a></li>
        <li><a href="">Top level</a></li>
    </ul>
</nav>

All we need to do is to check which one of the top-level menus has an li with class active in them, so our jquery code looks like this:

<script>
    jQuery(document).ready(function(){
        // Adding class "active" to all top-level menus that contain an li.active item
        $('nav > ul > li').each(function(){
            if( $(this).has('li.active').length ) {
                $(this).addClass('active');
            }
        });
    });
</script>

Here's a fiddle


问:
How to reset password of openstack instance using KVM and libvirt?
I'm using Openstack with KVM and libvirt. when I try to reset instance password with nova api, I received error 501 not Implemented!
How can I change instance password?</p>

答:
You can use guestfish as it is explained here. Basically you need to install the tool:

apt-get update
 apt-get install libguestfs-tools or guestfish (depends on your distro)

Then you can modify directly the VM image (remember to shut down the VM before doing any modification to avoid corruption issues):

```<code>cd /var/lib/nova/instances/<your instance GUID>/
guestfish --rw -a disk -i edit /etc/ssh/sshd_config
</code>```

So you can include

```<code>PasswordAuthentication no
</code>```

Then you can ssh your VM using the key you generated during creation. Or you can modify the password.

```<code>guestfish --rw -a disk -i edit /etc/sudoers
</code>```

Include at the end of the file for instance

```<code>[USERNAME] ALL=(ALL) NOPASSWD: ALL
</code>```

Finally to change the password:

```<code>guestfish --rw -a disk -i command "bash -c 'echo USERNAME:PASSWORD | chpasswd'"
</code>```

Body:
You can use guestfish as it is explained here. Basically you need to install the tool:

apt-get update
 apt-get install libguestfs-tools or guestfish (depends on your distro)

Then you can modify directly the VM image (remember to shut down the VM before doing any modification to avoid corruption issues):

cd /var/lib/nova/instances/<your instance GUID>/
guestfish --rw -a disk -i edit /etc/ssh/sshd_config

So you can include

PasswordAuthentication no

Then you can ssh your VM using the key you generated during creation. Or you can modify the password.

guestfish --rw -a disk -i edit /etc/sudoers

Include at the end of the file for instance

[USERNAME] ALL=(ALL) NOPASSWD: ALL

Finally to change the password:

guestfish --rw -a disk -i command "bash -c 'echo USERNAME:PASSWORD | chpasswd'"


问:
How properly deploy Docker Compose to Amason EC2 instance?
I'm having docker-compose config with postgres, 2*python, nginx and redis services. Now I'm instantiated an ec2 instance and successfully logged in via .pem file. But I expected, that I can deploy my docker-compose image only with aws-cli commands. My question is should I instantiate ec2 for each of service and how to use ec2 with docker-compose properly?

答:
How you want to design your infrastructure - how many servers, autoscaling, routing, etc - is entirely up to you.

To answer your question though; to deploy a docker-compose.yml file you do so the same as you would on any other server.

docker-compose is a tool made for development and is not made to be used in Production - you should deploy your services with:

```<code>docker stack deploy -c your-compose-file.yml your_stack_name
</code>```

It sounds like this is new to you though; so I should state that there are various options that are available with docker-compose that are not available with docker stack deploy. Often times you can't just use the same compose file as you're using in development.

Body:
How you want to design your infrastructure - how many servers, autoscaling, routing, etc - is entirely up to you.

To answer your question though; to deploy a docker-compose.yml file you do so the same as you would on any other server.

docker-compose is a tool made for development and is not made to be used in Production - you should deploy your services with:

docker stack deploy -c your-compose-file.yml your_stack_name

It sounds like this is new to you though; so I should state that there are various options that are available with docker-compose that are not available with docker stack deploy. Often times you can't just use the same compose file as you're using in development.


问:
Add element to sublist of a list
I have the following code:

```<code>let numbers = [[1],[2],[3],[4]]
</code>```

I want to append "3" to the sublist at index 2 of the list ([3]), like this:

```<code>(numbers !! 2) ++ [3]
</code>```

to get this:

```<code>numbers = [[1],[2],[3,3],[4]]
</code>```

But Im very confused :P Any idea?

答:
other way is by take and drop

```<code>take 2 numbers ++[(numbers !! 2) ++ [3]]++drop 3 numbers
</code>```

take the first 2 array --> [[1],[2]]

find the target array and [3] to it --> [[3]++[3]] returns [[3,3]]

drop 3 first array --> [[4]]

[[1],[2]] ++ [[3]++[3]] ++ [[4]] = [[1],[2],[3,3],[4]]

Title: Add element to sublist of a list

Body:
I have the following code:

let numbers = [[1],[2],[3],[4]]

I want to append "3" to the sublist at index 2 of the list ([3]), like this:

(numbers !! 2) ++ [3]

to get this:

numbers = [[1],[2],[3,3],[4]]

But Im very confused :P Any idea?

Body:
other way is by take and drop

take 2 numbers ++[(numbers !! 2) ++ [3]]++drop 3 numbers

take the first 2 array --> [[1],[2]]

find the target array and [3] to it --> [[3]++[3]] returns [[3,3]]

drop 3 first array --> [[4]]

[[1],[2]] ++ [[3]++[3]] ++ [[4]] = [[1],[2],[3,3],[4]]


问:
Returning Value When Object Property Doesn't Exist
Running a test on my code. It should return 0 if the property passed into the function does not exist. But its not returning anything. Did I make a typo?</p>

```<code>var obj = {
  key: [1, 2, 3]
};

function getAverageOfElementsAtProperty(obj, key) {
  if (obj[key].length === 0 || Array.isArray(obj[key]) === false || obj.hasOwnProperty(key) === false) {
    return 0;
  }
  var average = 0;
  for (var i = 0; i < obj[key].length; i++) {
    average += obj[key][i];
  }
  average /= obj[key].length;
  return average;
}

console.log(getAverageOfElementsAtProperty(obj, 'notKey'));
</code>```

答:
If you don't pass an array to your function, it fails when it tries to get the length of the object that was passed, so that shouldn't be how you test initially. You just need to see if the property exists and that is done by simply attempting to access the property in an if condition.

Now, if you are going to add tests to see if the property does exist and that it is an array, then you have to add more tests to check the items in the array to see if they are numbers, otherwise trying to get a numerical average will fail.

Since there are really two things to do (check if the property is there and get math average), I would break this into two functions:

var obj1 = {
  key: [1, 2, 3]
};

var obj2 = {
  key: [1, "test", 3]
};

function getAverageOfElementsAtProperty(obj, key) {
  if (obj[key] && Array.isArray(obj[key])) {
    // Ok, we have the right property and there is an array there,
    // now we have to test that each item in the array is a number
    var numbers = obj[key].every(function (currentValue) {
      return typeof currentValue === "number";
    });

    // Return the average if we have all numbers or 0 if not
    return numbers ? getAverage(obj[key]) : 0;
  } else {
    return 0;
  }
}

function getAverage(arr){
  var average = 0;
  // Array.forEach() is much simpler than counting loops
  arr.forEach(function(item) {
    average += item;
  });
  return average / arr.length;
}

console.log(getAverageOfElementsAtProperty(obj1, 'notkey'));  // 0
console.log(getAverageOfElementsAtProperty(obj1, 'key'));     // 2
console.log(getAverageOfElementsAtProperty(obj2, 'key'));     // 0 - obj2 does not contain all numbers```

Body:
Running a test on my code. It should return 0 if the property passed into the function does not exist. But its not returning anything. Did I make a typo?

var obj = {
  key: [1, 2, 3]
};

function getAverageOfElementsAtProperty(obj, key) {
  if (obj[key].length === 0 || Array.isArray(obj[key]) === false || obj.hasOwnProperty(key) === false) {
    return 0;
  }
  var average = 0;
  for (var i = 0; i < obj[key].length; i++) {
    average += obj[key][i];
  }
  average /= obj[key].length;
  return average;
}

console.log(getAverageOfElementsAtProperty(obj, 'notKey'));


问:
How to configure jboss application server with eclipse IDE?
I did the following steps.

To enable Eclipse to manage JBoss Application Server, you need to install the JBoss AS tools in Eclipse:

Start an instance of Eclipse.
Click Window > Preferences.
Expand the Server list, and click Runtime Environments.
In the Server Runtime Environments view, click Add.
In the New Server Runtime Environment dialog, click Download additional server adapters.
In the Install New Extension dialog, wait until the alphabetic list of server adapters is populated, then scroll down the list, and locate JBossAS Tools.
Click on this entry to select it, and click Next.
In the Review Licenses view, accept the license agreement, and click Finish.
Click OK to accept the restart warning.
The server adapter download is initiated, which may take a few moments. If you are presented with a security warning about unsigned content, ignore it by clicking OK. Once the server adapter is installed, click OK to restart Eclipse.

But still i'm getting this error while adding JbossAS tool

Cannot complete the install because one or more required items could not be found.
  Software being installed: JBossAS Tools 3.0.3.Final-v20150325-0035-B129 (org.jboss.ide.eclipse.as.feature.feature.group 3.0.3.Final-v20150325-0035-B129)
  Missing requirement: JBossAS Tools Server / JMX Integration 3.0.3.Final-v20150325-0035-B129 (org.jboss.ide.eclipse.as.jmx.integration.feature.feature.group 3.0.3.Final-v20150325-0035-B129) requires 'org.eclipse.rse.core 3.1.200' but it could not be found
  Cannot satisfy dependency:
    From: JBossAS Tools 3.0.3.Final-v20150325-0035-B129 (org.jboss.ide.eclipse.as.feature.feature.group 3.0.3.Final-v20150325-0035-B129)
    To: org.jboss.ide.eclipse.as.jmx.integration.feature.feature.group [3.0.3.Final-v20150325-0035-B129]

can anyone help me on this? i'm newbie to java world. using  Luna Service Release 2 (4.4.2)

答:
Looks like you need org.eclipse.rse.core 3.1.200:

Software being installed: JBossAS Tools 3.0.3.Final-v20150325-0035-B129 (org.jboss.ide.eclipse.as.feature.feature.group
  3.0.3.Final-v20150325-0035-B129)

Missing requirement: JBossAS Tools Server / JMX Integration 3.0.3.Final-v20150325-0035-B129 (org.jboss.ide.eclipse.as.jmx.integration.feature.feature.group
  3.0.3.Final-v20150325-0035-B129) requires 'org.eclipse.rse.core 3.1.200' but it could not be found Cannot satisfy dependency

I had a similar error where I was missing a TM Terminal dependency. I downloaded the latest jbosstoolstarget zip from JBoss Tools and installed the dependency from there. Looks like you can do the same in your case. Install the RSE dependency from the jbosstoolstarget zip using Eclipse.

This stackoverflow answer explains how to manually install software from a zip using Eclipse.

Once that dependency is installed, you should be able to install and configure JBoss Tools for JBoss application servers in Eclipse.


问:
Reshape matrix using Matlab
I work using Matlab and I have a matrix in 400x400x3x3 shape. I need to reshape it into 1200x1200. How do I do that?

I know there's a command called reshape and I've tried using it, but I'm missing something that I'm not seeing it.

答:
Not sure what you are missing. Please provide more information.

From what you have said so far, it's just

```<code>reshapedA=reshape(A, [1200,1200]);
</code>```

Title: Reshape matrix using Matlab

Body:
Not sure what you are missing. Please provide more information.

From what you have said so far, it's just

reshapedA=reshape(A, [1200,1200]);


答:
```<code>x = randn(400,400,3,3);
xr = reshape(x,1200,1200);
</code>```

For an official reference, nomen omen. This is the most straightforward answer, but actually there are different approaches depending on how you want to structure your data.

Title: Reshape matrix using Matlab

Body:
I work using Matlab and I have a matrix in 400x400x3x3 shape. I need to reshape it into 1200x1200. How do I do that?

I know there's a command called reshape and I've tried using it, but I'm missing something that I'm not seeing it.

Body:
x = randn(400,400,3,3);
xr = reshape(x,1200,1200);

For an official reference, nomen omen. This is the most straightforward answer, but actually there are different approaches depending on how you want to structure your data.


问:
One lane bridge using monitor
In the University I'm given this canonical parallel programming problem from "Gregory R. Andrews-Foundations of Multithreaded .... programming": (though I have a newer and Russian edition of the book I found an old English variant and try to convey everything properly)

I was also given task to solve this problem but with m consequently moving cars possible using semaphores To solve that task I was told by the tutor to mimic Reader's behavior from readers-writers task

 The One-Lane Bridge. Cars coming from the north and the south arrive at a one-
lane bridge. Cars heading in the same direction can cross the bridge at the same
time, but cars heading in opposite directions cannot.
Develop a solution to this problem. Model the cars as processes, and use a
monitor for synchronization. First specify the monitor invariant, then develop the
body of the monitor.Ensure fairness. (Have cars take tums)

I googled and found solution for analogous task (http://www.cs.cornell.edu/courses/cs4410/2008fa/homework/hw3_soln.pdf) but lecturer said most of it is useless and incorrect I ended up with the following solution:

```<code>monitor onelanebridge{
    int nb=0,sb=0; //Invar:(nb==0 and sb<=1)or(sb=0 and nb<=1)
    cond nbfreetogo,sbfreetogo; //conditional variables
    procedure enter_n(){
        if(sb!=0andnb==0) wait(nbfreetogo);
        nb++;
    }
    procedure enter_s(){
        if(nb!=0andsb==0) wait(sbfreetogo);
        sb++;
    }
    procedure leave_n(){
        nb--;
        if(nb==0) signal(sbfreetogo);
    }
    procedure leave_s(){
        sb--;
        if(sb==0) signal(nbfreetogo);
    }
}
</code>```

I was asked the question "What ensures that no more than one car at a time can cross the bridge?".. And am not even sure whether it's even so... Please help me solve the task correctly. I must use only constructions from the above mentioned book...
Example of readers-writers problem solution from the book:

```<code>monitor RW_Controller {
    int nr = 0, nw =0;  //Invar:  (nr == 0 or nw ==  0) and nw  <= 1
    cond oktoread; # recieves signal, when  nw == 0
    cond oktowrite; # recieves signal, when  nr == 0  и nw  == 0
    procedure request_read() {
        while (nw > 0) wait(oktoread);
        nr = nr + 1;
    }
    procedure release_read() {
    nr = nr - 1;
    if (nr == 0) signal(oktowrite);
        # run one writer-process
    }
    procedure request_write()  {
        while (nr > 0 || nw > 0) wait(oktowrite);
            nw = nw + 1 ;
        }
    procedure release_ write() {
        nw = nw - 1;
        signal(oktowrite); # run one writer-process and
        signal_all(oktoread); # all reader-processes
    }
}
</code>```

Of course my solution is just a random try. Halp me please to solve the task properly

Note: A variable of "conditional variable" type according to the book is a "wait queue" which has these methods:

```<code>wait(cv)//wait at end of queue
wait(cv,rank)//wait in order of increasing value of rank
signal(cv)//awaken process at end of queue then continue
signal_all(cv)//awaken all processes at end of queue then continue
empty(cv) //true if wait queue is  empty; false otherwise
minrank(cv) //value of rank of process at front of wait queue
</code>```

And so I should solve the task probably using some of these

答:
Your monitor onelanebridge is not far off the mark, but it has no notion of fairness.   If there was a steady stream of northbound traffic, nothing would trigger a switch to southbound.   You need to separate the count of waiting and ‘active’.

A simple fairness would be to alternate, so you could limit the ‘active’ counter at 1; and check whether to switch when it becomes zero.
To avoid inciting road rage, you might choose a limit based on the transit time of the single lane section.

You would now have vehicles waiting in enter_[ns] which had the right direction, but have to wait because of the limit, so your if (cond) wait needs to become while (more complex cond) wait.

Concurrent programming is not natural, but with practise can become ingrained.  Try and think of the problem at hand rather than how can I employ these mechanisms.

Title: One lane bridge using monitor

Body:
In the University I'm given this canonical parallel programming problem from "Gregory R. Andrews-Foundations of Multithreaded .... programming": (though I have a newer and Russian edition of the book I found an old English variant and try to convey everything properly)

I was also given task to solve this problem but with m consequently moving cars possible using semaphores To solve that task I was told by the tutor to mimic Reader's behavior from readers-writers task

 The One-Lane Bridge. Cars coming from the north and the south arrive at a one-
lane bridge. Cars heading in the same direction can cross the bridge at the same
time, but cars heading in opposite directions cannot.
Develop a solution to this problem. Model the cars as processes, and use a
monitor for synchronization. First specify the monitor invariant, then develop the
body of the monitor.Ensure fairness. (Have cars take tums)

I googled and found solution for analogous task (http://www.cs.cornell.edu/courses/cs4410/2008fa/homework/hw3_soln.pdf) but lecturer said most of it is useless and incorrect I ended up with the following solution:

monitor onelanebridge{
    int nb=0,sb=0; //Invar:(nb==0 and sb<=1)or(sb=0 and nb<=1)
    cond nbfreetogo,sbfreetogo; //conditional variables
    procedure enter_n(){
        if(sb!=0andnb==0) wait(nbfreetogo);
        nb++;
    }
    procedure enter_s(){
        if(nb!=0andsb==0) wait(sbfreetogo);
        sb++;
    }
    procedure leave_n(){
        nb--;
        if(nb==0) signal(sbfreetogo);
    }
    procedure leave_s(){
        sb--;
        if(sb==0) signal(nbfreetogo);
    }
}

I was asked the question "What ensures that no more than one car at a time can cross the bridge?".. And am not even sure whether it's even so... Please help me solve the task correctly. I must use only constructions from the above mentioned book...
Example of readers-writers problem solution from the book:

monitor RW_Controller {
    int nr = 0, nw =0;  //Invar:  (nr == 0 or nw ==  0) and nw  <= 1
    cond oktoread; # recieves signal, when  nw == 0
    cond oktowrite; # recieves signal, when  nr == 0  и nw  == 0
    procedure request_read() {
        while (nw > 0) wait(oktoread);
        nr = nr + 1;
    }
    procedure release_read() {
    nr = nr - 1;
    if (nr == 0) signal(oktowrite);
        # run one writer-process
    }
    procedure request_write()  {
        while (nr > 0 || nw > 0) wait(oktowrite);
            nw = nw + 1 ;
        }
    procedure release_ write() {
        nw = nw - 1;
        signal(oktowrite); # run one writer-process and
        signal_all(oktoread); # all reader-processes
    }
}

Of course my solution is just a random try. Halp me please to solve the task properly

Note: A variable of "conditional variable" type according to the book is a "wait queue" which has these methods:

wait(cv)//wait at end of queue
wait(cv,rank)//wait in order of increasing value of rank
signal(cv)//awaken process at end of queue then continue
signal_all(cv)//awaken all processes at end of queue then continue
empty(cv) //true if wait queue is  empty; false otherwise
minrank(cv) //value of rank of process at front of wait queue

And so I should solve the task probably using some of these


问:
How to INSERT INTO [temp table] FROM [Stored Procedure] and Select * FROM [temp table]
I have something like

```<code>Create TABLE #members
(
    [member_id] [bigint] NOT NULL,
    [registration_id] [int] NOT NULL,
    [date_modified] [datetime] NULL,
    [date_created] [datetime] NULL
)
INSERT #members
(
    [member_id],
    [registration_id],
    [date_modified],
    [date_created]
)
EXEC
dbo._roster_member_GetMemberContacts_byMember_id @Member_id = 1000
Select * from #members
</code>```

when I run it in query analyzer window:
There is already an object named '#members' in the database.

答:
Use the following idiom:

```<code>if object_id('tempdb..#temptable', 'U') is not null
    drop table #temptable
create table #temptable ( ... )
... rest of SQL ...
</code>```

Obviously substituting the name of your temp table.

Body:
I have something like

Create TABLE #members
(
    [member_id] [bigint] NOT NULL,
    [registration_id] [int] NOT NULL,
    [date_modified] [datetime] NULL,
    [date_created] [datetime] NULL
)
INSERT #members
(
    [member_id],
    [registration_id],
    [date_modified],
    [date_created]
)
EXEC
dbo._roster_member_GetMemberContacts_byMember_id @Member_id = 1000
Select * from #members

when I run it in query analyzer window:
There is already an object named '#members' in the database.

Body:
Use the following idiom:

if object_id('tempdb..#temptable', 'U') is not null
    drop table #temptable
create table #temptable ( ... )
... rest of SQL ...

Obviously substituting the name of your temp table.


问:
Decimal to binary in C language
I wrote simple code in C language (without libraries), but the result is good only when you read it from right to left, how to reverse it? I want the most simplified code as it is possible. My code below:</p>

```<code>#include <stdio.h>

int main() {
    int number;

    printf("Changes from decimal to binary\n");
    printf("Enter the number: ");

    scanf("%d",&number);

    do{
        if(number % 2 == 1){
            printf("1");
        }else{
            printf("0");
        }
        number = number / 2;
    }
     while(number>0);

  return 0;
}
</code>```

答:
You could store the binary number in an array and then print it backwards. So you would have for example int binaryDigits[1024]; and then instead of printing you will store the number in the array with a counter. Before the loop: int i = 0; and after that instead of printf("1"); and printf("0");, binaryDigits[i++] = 1 and binaryDigits[i++] = 0 respectively. Finally you could print the number in order with a for loop:

```<code>    for (i = i - 1; i >= 0; i--)
        printf("%d", binaryDigits[i])
</code>```

Title: Decimal to binary in C language

Body:
I wrote simple code in C language (without libraries), but the result is good only when you read it from right to left, how to reverse it? I want the most simplified code as it is possible. My code below:

#include <stdio.h>

int main() {
    int number;

    printf("Changes from decimal to binary\n");
    printf("Enter the number: ");

    scanf("%d",&number);

    do{
        if(number % 2 == 1){
            printf("1");
        }else{
            printf("0");
        }
        number = number / 2;
    }
     while(number>0);

  return 0;
}

Body:
You could store the binary number in an array and then print it backwards. So you would have for example int binaryDigits[1024]; and then instead of printing you will store the number in the array with a counter. Before the loop: int i = 0; and after that instead of printf("1"); and printf("0");, binaryDigits[i++] = 1 and binaryDigits[i++] = 0 respectively. Finally you could print the number in order with a for loop:

    for (i = i - 1; i >= 0; i--)
        printf("%d", binaryDigits[i])


问:
Is it possible to fetch a cursor into a record using rowtype?
I'm always getting

```<code>PLS-00597: expression 'V_EMP_REC' in the INTO list is of wrong type
</code>```

Here's the package, i'm using default HR schema

```<code>CREATE OR REPLACE PACKAGE EMP_PKG AS
  TYPE T_EMP_REC IS RECORD (
    V_EMP_TAB EMPLOYEES%ROWTYPE,
    V_DEPT_NAME DEPARTMENTS.DEPARTMENT_NAME%TYPE
  );

  FUNCTION GET_EMP (P_EMP_ID EMPLOYEES.EMPLOYEE_ID%TYPE) RETURN T_EMP_REC;
END EMP_PKG;
/
CREATE OR REPLACE PACKAGE BODY EMP_PKG AS
  FUNCTION GET_EMP (P_EMP_ID EMPLOYEES.EMPLOYEE_ID%TYPE)
  RETURN T_EMP_REC
  AS
    CURSOR V_EMP_CUR IS
      SELECT E.*, D.DEPARTMENT_NAME
      FROM EMPLOYEES E, DEPARTMENTS D
      WHERE E.EMPLOYEE_ID = P_EMP_ID
      AND E.DEPARTMENT_ID = D.DEPARTMENT_ID;

  V_EMP_REC T_EMP_REC;
  BEGIN
    OPEN V_EMP_CUR;
    FETCH V_EMP_CUR INTO V_EMP_REC;
    CLOSE V_EMP_CUR;

  RETURN V_EMP_REC;
  END GET_EMP;
END EMP_PKG;
</code>```

The number of columns matches and I'm always using the same types as the table. I don't know if this approach is possible instead of declaring every column in the record type.

答:
You have to explicitly declare all the columns of employees and departments in your collection:

```<code>TYPE t_emp_rec IS RECORD (employees_col1 employees.employees_col1%TYPE,
                          employees_col2 employees.employees_col2%TYPE,
                          ...
                          departments_col1 departments.departments_col1%TYPE,
                          departments_col2 departments.departments_col2%TYPE
                          ...
                          );
</code>```

In your code you get an error because you'are trying to assign a column type (NUMBER, VARCHAR2, DATE, ...) to a RECORD collection.

Body:
I'm always getting

PLS-00597: expression 'V_EMP_REC' in the INTO list is of wrong type

Here's the package, i'm using default HR schema

CREATE OR REPLACE PACKAGE EMP_PKG AS
  TYPE T_EMP_REC IS RECORD (
    V_EMP_TAB EMPLOYEES%ROWTYPE,
    V_DEPT_NAME DEPARTMENTS.DEPARTMENT_NAME%TYPE
  );

  FUNCTION GET_EMP (P_EMP_ID EMPLOYEES.EMPLOYEE_ID%TYPE) RETURN T_EMP_REC;
END EMP_PKG;
/
CREATE OR REPLACE PACKAGE BODY EMP_PKG AS
  FUNCTION GET_EMP (P_EMP_ID EMPLOYEES.EMPLOYEE_ID%TYPE)
  RETURN T_EMP_REC
  AS
    CURSOR V_EMP_CUR IS
      SELECT E.*, D.DEPARTMENT_NAME
      FROM EMPLOYEES E, DEPARTMENTS D
      WHERE E.EMPLOYEE_ID = P_EMP_ID
      AND E.DEPARTMENT_ID = D.DEPARTMENT_ID;

  V_EMP_REC T_EMP_REC;
  BEGIN
    OPEN V_EMP_CUR;
    FETCH V_EMP_CUR INTO V_EMP_REC;
    CLOSE V_EMP_CUR;

  RETURN V_EMP_REC;
  END GET_EMP;
END EMP_PKG;

The number of columns matches and I'm always using the same types as the table. I don't know if this approach is possible instead of declaring every column in the record type.

Body:
You have to explicitly declare all the columns of employees and departments in your collection:

TYPE t_emp_rec IS RECORD (employees_col1 employees.employees_col1%TYPE,
                          employees_col2 employees.employees_col2%TYPE,
                          ...
                          departments_col1 departments.departments_col1%TYPE,
                          departments_col2 departments.departments_col2%TYPE
                          ...
                          );

In your code you get an error because you'are trying to assign a column type (NUMBER, VARCHAR2, DATE, ...) to a RECORD collection.


问:
How to color table rows according to a specific input dynamically?
I am just starting to learn about javascript, jquery , and ajax.

I really need help knowing the logic or how I should approach this problem:

I have a table of " expenses" that could be monthly :

```<code>      Type     Cost     Monthly/yearly
      Laundry    2000$     Monthly
      Groceries    300$    Monthly
      Clothes    100$    Monthly
</code>```

I have an input budget . What I need is that say the user inputted 200$ , the rows whose cost is greater than the budget AND that are monthly should be coloured in red:

```<code> Type     Cost     Monthly/yearly
  Laundry    2000$     Monthly (colored in red)
  Groceries    300$    Monthly (colored in red)
  Clothes    100$    Monthly
</code>```

But then the user can input another budget , and then the colors in the table should update automatically. Now he inputs 1000$ :

```<code>Type     Cost     Monthly/yearly
      Laundry    2000$     Monthly ( only one colored in red)
      Groceries    300$    Monthly
      Clothes    100$    Monthly
</code>```

How can I achieve that? I just need to know how to approach this logic wise. I'm using Node.Js

答:
I will try and give you a bit of very weird pseudocode. Hope it helps
 I will give you the explanation of two possible approaches a client side and a server side version. There is also some notes on what you might use.

It might be in your best interest to try both approaches wich may come in handy down the road.

CLIENT SIDE VERSION:

CSS

Create a CSS class that styles your background and font color, lets say danger, works for either approach. You should also style the td inside the rows

HTML

Create your input and put a name on it lets say the name is budget
Create your table with all the data

JS

Lets say you want to change the coloring whenever the input field changes
First you will need to capture the changes on the field input. You can use the on() function of jquery

When you capture the change event    Remove the danger class from
all of the rows

Get the value of the input

Iterate through each row

Get the numeric value of the cost cell. Use parseInt or
parseFloat to get the numeric value.If needed remove commas or $
sign using replace()

Get the text value of the the
Monthly/Yearly

check if your cost numeric values is bigger than budget and that the text value is equals to Monthly

If the condition is true add the class danger to the current row using addClass()

SERVER SIDE VERSION:

Since you are working server side I assume you have the data in variables or ina an array. Lets say you have an array of objects, along the lines of

```<code>var array = [
    {type: 'laundry',cost: 200, repetition: 'monthly'},
    {type: 'food',cost: 100, repetition: 'monthly'},
    ...
]
</code>```

and your budget

```<code>var budget = 200;
</code>```

CSS

Create a CSS class that styles your background and font color, lets say danger, works for either approach. You should also style the td inside the rows.

SERVER GENERATED VIEW

You will need to iterate through every element of array

in each iteration you will create a row with the following data

if cost < budget and repetition == 'monthly' then you should add the danger
class to the row

add the type cell to the row

add the cost cell to the row

add the repetition cell to the row

Body:
I am just starting to learn about javascript, jquery , and ajax.

I really need help knowing the logic or how I should approach this problem:

I have a table of " expenses" that could be monthly :

      Type     Cost     Monthly/yearly
      Laundry    2000$     Monthly
      Groceries    300$    Monthly
      Clothes    100$    Monthly

I have an input budget . What I need is that say the user inputted 200$ , the rows whose cost is greater than the budget AND that are monthly should be coloured in red:

 Type     Cost     Monthly/yearly
  Laundry    2000$     Monthly (colored in red)
  Groceries    300$    Monthly (colored in red)
  Clothes    100$    Monthly

But then the user can input another budget , and then the colors in the table should update automatically. Now he inputs 1000$ :

Type     Cost     Monthly/yearly
      Laundry    2000$     Monthly ( only one colored in red)
      Groceries    300$    Monthly
      Clothes    100$    Monthly

How can I achieve that? I just need to know how to approach this logic wise. I'm using Node.Js

Body:
I will try and give you a bit of very weird pseudocode. Hope it helps
 I will give you the explanation of two possible approaches a client side and a server side version. There is also some notes on what you might use.

It might be in your best interest to try both approaches wich may come in handy down the road.

CLIENT SIDE VERSION:

CSS

Create a CSS class that styles your background and font color, lets say danger, works for either approach. You should also style the td inside the rows

HTML

Create your input and put a name on it lets say the name is budget
Create your table with all the data

JS

Lets say you want to change the coloring whenever the input field changes
First you will need to capture the changes on the field input. You can use the on() function of jquery

When you capture the change event    Remove the danger class from
all of the rows

Get the value of the input

Iterate through each row

Get the numeric value of the cost cell. Use parseInt or
parseFloat to get the numeric value.If needed remove commas or $
sign using replace()

Get the text value of the the
Monthly/Yearly

check if your cost numeric values is bigger than budget and that the text value is equals to Monthly

If the condition is true add the class danger to the current row using addClass()

SERVER SIDE VERSION:

Since you are working server side I assume you have the data in variables or ina an array. Lets say you have an array of objects, along the lines of

var array = [
    {type: 'laundry',cost: 200, repetition: 'monthly'},
    {type: 'food',cost: 100, repetition: 'monthly'},
    ...
]

and your budget

var budget = 200;

CSS

Create a CSS class that styles your background and font color, lets say danger, works for either approach. You should also style the td inside the rows.

SERVER GENERATED VIEW

You will need to iterate through every element of array

in each iteration you will create a row with the following data

if cost < budget and repetition == 'monthly' then you should add the danger
class to the row

add the type cell to the row

add the cost cell to the row

add the repetition cell to the row


问:
Combined nodes to a single one based on a common property
I'm trying to learn more about Neo4j. Is there a way to group nodes that have the same name/number/etc.?

In standard RDBMS one can use the "Group by" clause to combine specific values into one.  Have a look at the picture for a better understanding.

I'd like to combine these two nodes ("EE", "EE") into one, which has both sub-nodes.

Code for the image output:

```<code>match (A:Place)-[:`->`]-(B:Typ)
where A.name ='City1'
return A, B
</code>```

答:
When you created your Place nodes, you should have used a MERGE operation instead of CREATE. For example, no matter how many times you execute the following, it will not create a duplicate Place node if one already existed with the same name:

```<code>MERGE (a:Place {name: 'City1'})
...
</code>```

Also, before you use the MERGE operation, you should make it work optimally by first creating an index on :Place(name) (or a uniqueness constraint on the same node label and property).

Body:
I'm trying to learn more about Neo4j. Is there a way to group nodes that have the same name/number/etc.?

In standard RDBMS one can use the "Group by" clause to combine specific values into one.  Have a look at the picture for a better understanding.

I'd like to combine these two nodes ("EE", "EE") into one, which has both sub-nodes.

Code for the image output:

match (A:Place)-[:`->`]-(B:Typ)
where A.name ='City1'
return A, B

Body:
When you created your Place nodes, you should have used a MERGE operation instead of CREATE. For example, no matter how many times you execute the following, it will not create a duplicate Place node if one already existed with the same name:

MERGE (a:Place {name: 'City1'})
...

Also, before you use the MERGE operation, you should make it work optimally by first creating an index on :Place(name) (or a uniqueness constraint on the same node label and property).


问:
Get JSON list embeded another object with Retrofit
I have an server rest, that provides JSON. I can get an user, but not a user list using Retrofit.

User JSON example (server/users/2):

```<code>{
  "id": 2,
  "firstName": "name",
  "lastName": "name"
}
</code>```

User list example (server/users):

```<code>{
  "_embedded": {
    "users": [
      {
        "id": 2,
        "firstName": "name",
        "lastName": "name"
      },
      {
        "id": 3,
        "firstName": "Ime",
        "lastName": "Léonide"
      }
    ]
  }
}
</code>```

I guess that is caused by "_embedded". I don't think I can change this.

Java code:

```<code>@GET("users/")
Call<List<User>> usersList();
</code>```

答:
Try:</p>

```<code>@GET("users/")
Call<UserResponse> usersList();

class UserResponse {
    @SerializedName("_embedded")
    UserList embedded;
}

class UserList {
    @SerializedName("users")
    List<User> userList;
}
</code>```

Body:
I have an server rest, that provides JSON. I can get an user, but not a user list using Retrofit.

User JSON example (server/users/2):

{
  "id": 2,
  "firstName": "name",
  "lastName": "name"
}

User list example (server/users):

{
  "_embedded": {
    "users": [
      {
        "id": 2,
        "firstName": "name",
        "lastName": "name"
      },
      {
        "id": 3,
        "firstName": "Ime",
        "lastName": "Léonide"
      }
    ]
  }
}

I guess that is caused by "_embedded". I don't think I can change this.

Java code:

@GET("users/")
Call<List<User>> usersList();

Body:
Try:

@GET("users/")
Call<UserResponse> usersList();

class UserResponse {
    @SerializedName("_embedded")
    UserList embedded;
}

class UserList {
    @SerializedName("users")
    List<User> userList;
}


问:
Regex expansion in powershell
I have to iterate over a large loop of IPs and I have been able to do this with ease in bash, but while attempting to do this in PowerShell I found that I have little idea how to do something similar.

In bash I have done the following:

```<code>for ip in 10.98.{7..65}.{0..255}; do
    echo "some text and a $ip";
done
</code>```

However, in PowerShell I have done the following:

```<code>$ipprefix='10.98';
For ($i=7; $i -le 65; $i++) {
    For ($j=0; $j -le 255; $j++) {
        Write-Host "some text and a $ipprefix.$i.$j";
    }
}
</code>```

Is there an easier way to do this in PowerShell?

答:
Ideally, the bash code has to unroll two loops, so the PowerShell you have is fundamentally the same.  That said, you could nest two ranges in Powershell to achieve the same.

For example:

```<code>1..3 | % {$c = $_; 4..6 | % {$d = $_; Write-Host "a.b.$c.$d"}}
</code>```

Gives:

```<code>a.b.1.4
a.b.1.5
a.b.1.6
a.b.2.4
a.b.2.5
a.b.2.6
a.b.3.4
a.b.3.5
a.b.3.6
</code>```

From this, you can adapt to your problem above.

You could shorten this a bit if you wanted, and lose some readability like:

```<code>1..3 | % {$c = $_; 4..6 | % {Write-Host "a.b.$c.$_"}}
</code>```

Title: Regex expansion in powershell

Body:
I have to iterate over a large loop of IPs and I have been able to do this with ease in bash, but while attempting to do this in PowerShell I found that I have little idea how to do something similar.

In bash I have done the following:

for ip in 10.98.{7..65}.{0..255}; do
    echo "some text and a $ip";
done

However, in PowerShell I have done the following:

$ipprefix='10.98';
For ($i=7; $i -le 65; $i++) {
    For ($j=0; $j -le 255; $j++) {
        Write-Host "some text and a $ipprefix.$i.$j";
    }
}

Is there an easier way to do this in PowerShell?

Body:
Ideally, the bash code has to unroll two loops, so the PowerShell you have is fundamentally the same.  That said, you could nest two ranges in Powershell to achieve the same.

For example:

1..3 | % {$c = $_; 4..6 | % {$d = $_; Write-Host "a.b.$c.$d"}}

Gives:

a.b.1.4
a.b.1.5
a.b.1.6
a.b.2.4
a.b.2.5
a.b.2.6
a.b.3.4
a.b.3.5
a.b.3.6

From this, you can adapt to your problem above.

You could shorten this a bit if you wanted, and lose some readability like:

1..3 | % {$c = $_; 4..6 | % {Write-Host "a.b.$c.$_"}}