问:
How to change part of files names using Sys and Subprocess modules and Linux Bash
I have Python script which reads files names from oldFiles.txt, iterate through files names which are files in a Linux directory, then update the files names using string.replace and finally run a subprocess to find those files (let's say in home directory to make the explanation and demo easier) and change their names using

```<code>subprocess.run(['mv', 'oldfile', 'newfile')]
</code>```

Let's suppose I have files names with string "jane" and I want to replace it with "jdoe", a file's name example would be: abcd_jane.csv modified into abcd_jdoe.csv

The sys.argv[1] is the argument which will be passed like the follow

```<code>./changeJane.py oldFiles.txt
</code>```

I am using those empty files for local training, their names are saved in oldFiles.txt

sdafsdfs_jane.doc 12fgdf-jane.csv files_jane.txt

Iterating and updating files names in oldFiles.txt is ok or maybe there is some mistakes also :-( but I still couldn't figure out how to run the subprocess to achieve my goal like described above. This is what I came in, thank you very much.

PS: I am forced to use sys and subprocess modules, and also forced to apply all the mentioned details, its a homework assessment.

```<code>#!/usr/bin/env python3
import sys
import subprocess
with open(sys.argv[1], 'r+') as f:
  for line in f.readlines():
    newline = line.strip()
    newtext = newline.replace("jane", "jdoe")
    subprocess.run(['mv', '~/newline', '~/newtext']) #I know its wrong but this is my limit!
</code>```

UPDATE

I modified the script to return list and comfortably iterate through its items, the script is successful but it is doing one iteration only which means it is applying only the first file name or the first iteration, any ideas to do all the iterations and finish the job. Thank you very much!!

```<code>#!/usr/bin/env python3
import sys
import subprocess
with open(sys.argv[1], 'r') as f:
    content1 = f.readlines()
    content2 = [x.strip() for x in content1]
    content3 = [item.replace("jane", "jdoe") for item in content2]
    for x in content2:
      for i in content3:
        subprocess.run(['mv', '/home/ninja-coder/'+x, '/home/ninja-coder/'+i])
</code>```

答:
<pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python3

import sys
import subprocess
impotr os

with open(sys.argv[1], 'r') as f:
    for line in f:
        newline = line.strip()
        newtext = newline.replace("jane", "jdoe")
        os.rename(newline, newtext)
</code>```

Body:
I have Python script which reads files names from oldFiles.txt, iterate through files names which are files in a Linux directory, then update the files names using string.replace and finally run a subprocess to find those files (let's say in home directory to make the explanation and demo easier) and change their names using

subprocess.run(['mv', 'oldfile', 'newfile')]

Let's suppose I have files names with string "jane" and I want to replace it with "jdoe", a file's name example would be: abcd_jane.csv modified into abcd_jdoe.csv

The sys.argv[1] is the argument which will be passed like the follow

./changeJane.py oldFiles.txt

I am using those empty files for local training, their names are saved in oldFiles.txt

sdafsdfs_jane.doc 12fgdf-jane.csv files_jane.txt

Iterating and updating files names in oldFiles.txt is ok or maybe there is some mistakes also :-( but I still couldn't figure out how to run the subprocess to achieve my goal like described above. This is what I came in, thank you very much.

PS: I am forced to use sys and subprocess modules, and also forced to apply all the mentioned details, its a homework assessment.

#!/usr/bin/env python3
import sys
import subprocess
with open(sys.argv[1], 'r+') as f:
  for line in f.readlines():
    newline = line.strip()
    newtext = newline.replace("jane", "jdoe")
    subprocess.run(['mv', '~/newline', '~/newtext']) #I know its wrong but this is my limit!

UPDATE

I modified the script to return list and comfortably iterate through its items, the script is successful but it is doing one iteration only which means it is applying only the first file name or the first iteration, any ideas to do all the iterations and finish the job. Thank you very much!!

#!/usr/bin/env python3
import sys
import subprocess
with open(sys.argv[1], 'r') as f:
    content1 = f.readlines()
    content2 = [x.strip() for x in content1]
    content3 = [item.replace("jane", "jdoe") for item in content2]
    for x in content2:
      for i in content3:
        subprocess.run(['mv', '/home/ninja-coder/'+x, '/home/ninja-coder/'+i])


来源: stackexchange

问:
How to display all print result in Pycharm?
Whenever I run a huge file that contains several observations (i.e, columns), Pycharm does not show all the observations. The below picture shows only 2 observations whereas I need to display all observations (in my case, there are 10 observations).

How do I solve this?

答:
As described here, you can increase the display width and the amount of columns:</p>
```<code>import pandas as pd
pd.set_option('display.width', 400)
pd.set_option('display.max_columns', 10)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
As described here, you can increase the display width and the amount of columns:

import pandas as pd
pd.set_option('display.width', 400)
pd.set_option('display.max_columns', 10)


问:
what event sets the dimensions of a swfloader?
I am trying to scale a swf that has been loaded via a swfloader.  When I get the complete event or the init event the dimensions of the swfloader are still zero. I don't see a value in the dimensions until I do a resize of the browser window.  The swf is just an animation.  Trying to resize the actual swf content gives inconsistent results.</p>

答:
For this kind of problem, it sometimes helps to simply poll the dimensions on enterFrame until you get some value. You could for example do this:

```<code>bool dimensionsSet = false
addEventListener("enterFrame", checkDimensions);

function checkDimensions(event:*):void {
    if (!dimensionsSet && width && height) {
        dimensionsSet = true;
        // Do initialization code
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
For this kind of problem, it sometimes helps to simply poll the dimensions on enterFrame until you get some value. You could for example do this:

bool dimensionsSet = false
addEventListener("enterFrame", checkDimensions);

function checkDimensions(event:*):void {
    if (!dimensionsSet && width && height) {
        dimensionsSet = true;
        // Do initialization code
    }
}


问:
View full page source after javascript has run ('view generated source') in Chrome?
We can see the source after the javascript has run for a single element by right clicking on that element and clicking 'inspect element'.

Firefox lets us see the full page source by through view source -> view generated source.

How can we do this in chrome? That is, how can we see the full page source after javascript has run in chrome?

答: This can't be done natively in Chrome, but the View Rendered Source extension does this and also compares the rendered source to the raw source. You can also access extension via right click.</p>


问:
content overflowing from css grid
Problem: I am having a problem with sizing images inside css grid column/rows. I essentially object-fit: contain the imagesinside their individual cells.

The image in "SPOT 4" is not filling the given space

If you uncomment the image in "SPOT 1", it will cover the entire grid and is not confined to its own css grid cell.

I have tried setting max-width, object-fit and others on the video level and .channel-container level with no success.

Background:  The .parent-trap css class is just an example height/width. This will vary, it may be the entire browser window, or it may be small so I cannot depend on any specific min/max dimensions. There are also other .display4 in the full version that sometimes shows a single video that fills the whole grid, side by side that only shows 2 at a time etc, so any specific dimensions also tend to break individual .display*

html,
body {
  border: 0;
  margin: 0;
  height: 100%;
}

.parent-trap {
  height: 540px;
  width: 960px;
}

/* container for player */
.video-player {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  max-height: 100%;
  max-width: 100%;
  min-height: 100%;
  min-width: 100%;
}

/* container for plaback control bar */
.container-controls {
  height: 50px;
  background-color: red;
}

/* contains all the .channel-container s */
.channel-layout-container {
  display: grid;
  background: #000;
  background-color: blue;
  flex: 1;
}

/****
**** FIX HERE
****/

.channel-container {}

img {}

/** THERE ARE OTHER DYNAMIC LAYOUTS, ISSUE IS SAME ON ALL */

/** display4 **/
.channel-layout-container.display4 {
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
}

.channel-layout-container.display4 .channel-container:nth-child(n+5) {
  flex: none;
  display: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- try restricting various sizes -->
<div class="parent-trap">

  <!-- the classcommes that need to be transferred back over-->
  <div class="video-player">
    <div class="channel-layout-container display4">
      <div class="channel-container" style="background-color: khaki;">
        <!-- <img src="https://w.wallhaven.cc/full/3z/wallhaven-3zgz2y.png" />-->

      </div>
      <div class="channel-container" style="background-color: lavender;">
        SPOT 2
      </div>
      <div class="channel-container" style="background-color: lightcoral;">
        SPOT 3
      </div>
      <div class="channel-container" style="background-color: lightseagreen;">
        <img src="https://www.google.com/favicon.ico" />
      </div>
    </div>
    <div class="container-controls">
      common controls and other info goes here
    </div>
  </div>
</div></code>```

答:
Your issue results from your grid template definition.

Replace 1fr 1fr with repeat(2, minmax(0, 1fr)).

The reason for your problem is that 1fr effectively means minmax(auto, 1fr). minmax works such that if the first argument is greater than the second, the whole minmax expression is replaced by the first argument, so your whole definition becomes

```<code>grid-template-columns: auto auto;
grid-template-rows: auto auto;
</code>```

Setting minmax(0, 1fr) prevents this and effectively sets what you did by setting min-width/-height to 0.

Title: content overflowing from css grid

Body:
Problem: I am having a problem with sizing images inside css grid column/rows. I essentially object-fit: contain the imagesinside their individual cells.

The image in "SPOT 4" is not filling the given space

If you uncomment the image in "SPOT 1", it will cover the entire grid and is not confined to its own css grid cell.

I have tried setting max-width, object-fit and others on the video level and .channel-container level with no success.

Background:  The .parent-trap css class is just an example height/width. This will vary, it may be the entire browser window, or it may be small so I cannot depend on any specific min/max dimensions. There are also other .display4 in the full version that sometimes shows a single video that fills the whole grid, side by side that only shows 2 at a time etc, so any specific dimensions also tend to break individual .display*

html,
body {
  border: 0;
  margin: 0;
  height: 100%;
}

.parent-trap {
  height: 540px;
  width: 960px;
}

/* container for player */
.video-player {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  max-height: 100%;
  max-width: 100%;
  min-height: 100%;
  min-width: 100%;
}

/* container for plaback control bar */
.container-controls {
  height: 50px;
  background-color: red;
}

/* contains all the .channel-container s */
.channel-layout-container {
  display: grid;
  background: #000;
  background-color: blue;
  flex: 1;
}

/****
**** FIX HERE
****/

.channel-container {}

img {}

/** THERE ARE OTHER DYNAMIC LAYOUTS, ISSUE IS SAME ON ALL */

/** display4 **/
.channel-layout-container.display4 {
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
}

.channel-layout-container.display4 .channel-container:nth-child(n+5) {
  flex: none;
  display: none;
}

        SPOT 2

        SPOT 3

      common controls and other info goes here

Body:
Your issue results from your grid template definition.

Replace 1fr 1fr with repeat(2, minmax(0, 1fr)).

The reason for your problem is that 1fr effectively means minmax(auto, 1fr). minmax works such that if the first argument is greater than the second, the whole minmax expression is replaced by the first argument, so your whole definition becomes

grid-template-columns: auto auto;
grid-template-rows: auto auto;

Setting minmax(0, 1fr) prevents this and effectively sets what you did by setting min-width/-height to 0.


问:
How to only print the first word of a string in c++
How do I set this up to only read the first word the user enters IF they enter to much info?

I do not want to use an if-else statement demanding they enter new info because their info was to much.

I just want it to basically ignore everything after the first word and only print the first word entered. Is this even possible?

```<code>const int SIZEB = 10;
char word[SIZEB];
cout << " Provide a word, up to 10 characters, no spaces. > " << endl;
cin.getline(word, SIZEB);
cout << " The word is: " << word << endl;
cout << endl;
</code>```

UPDATE

It HAS to be a cstring. This is something I am working on for school. I am asking a series of questions and storing the answers as cstring in the first round. Then there is a second round where I store them as string.

答:
you could also use this method :</p>
```<code>std::string str;
std::cin >> str;
std::string word;
int str_size = str.size();
for(int i = 0; i < str_size; i++){
    word.push_back(str[i]);
    if(str[i] == ' ') break;
}
std::cout << "\n" << word << std::endl;
</code>```

Body:
How do I set this up to only read the first word the user enters IF they enter to much info?

I do not want to use an if-else statement demanding they enter new info because their info was to much.

I just want it to basically ignore everything after the first word and only print the first word entered. Is this even possible?

const int SIZEB = 10;
char word[SIZEB];
cout << " Provide a word, up to 10 characters, no spaces. > " << endl;
cin.getline(word, SIZEB);
cout << " The word is: " << word << endl;
cout << endl;

UPDATE

It HAS to be a cstring. This is something I am working on for school. I am asking a series of questions and storing the answers as cstring in the first round. Then there is a second round where I store them as string.

Body:
you could also use this method :

std::string str;
std::cin >> str;
std::string word;
int str_size = str.size();
for(int i = 0; i < str_size; i++){
    word.push_back(str[i]);
    if(str[i] == ' ') break;
}
std::cout << "\n" << word << std::endl;


问:
What link will return an address when I pass latitude and longitude?
http://maps.google.com/maps/geo?q=address&output=csv

The above link gives the latitude and longitude from address.

I want a similar link to get address from latitude and longitude.

答:
Using
Below Api you can Get Address From Lat And Log
NSString *address = [NSString stringWithFormat:@"http://ws.geonames.org/findNearestAddress?lat=%f&lng=%f", newLocation.lattitude, newLocation.longitude]; NSURL *url = [NSURL URLFromString:address];</p>


问:
Get all parents ids from id list in nested object in javascript
So I have an array of objects which have all nested children property. It is in front-end a treeview, which should expand the nodes until selected ones, for each id in a list. To be able to do this, I have to get all the parents ids for each selected id from the list.

For example, my list of checkedKeys ids:

```<code>[16787217, 16787245, 16787266, 16787270, 16787272, 16787265, 16787264]
</code>```

All the checked items represents the ids from the list object:

My object list looks like this:

```<code>[
  {
    "id": 11,
    "name": "Forecast source",
    "value": null,
    "children": []
  },
  {
    "id": 2,
    "name": "Item Type",
    "value": null,
    "children": []
  },
  {
    "id": 16787217,
    "name": "Item@Cust",
    "value": null,
    "children": [
      {
        "id": 16787230,
        "name": "Customer",
        "value": null,
        "children": [
          {
            "id": 16787291,
            "name": "Commercial Network",
            "value": null,
            "children": []
          },
          {
            "id": 16787296,
            "name": "Distribution Site",
            "value": null,
            "children": []
          },
          {
            "id": 16787265,
            "name": "Site",
            "value": null,
            "children": []
          }
        ]
      },
      {
        "id": 16787254,
        "name": "Item",
        "value": null,
        "children": [
          {
            "id": 16787294,
            "name": "ABC (Regular)",
            "value": null,
            "children": []
          },
          {
            "id": 16787273,
            "name": "ABC (U)",
            "value": null,
            "children": []
          },
          {
            "id": 16787278,
            "name": "ABC (€)",
            "value": null,
            "children": []
          },
          {
            "id": 16787290,
            "name": "Class",
            "value": null,
            "children": []
          },
          {
            "id": 16787260,
            "name": "Family",
            "value": null,
            "children": [
              {
                "id": 16787264,
                "name": "Product line",
                "value": null,
                "children": []
              }
            ]
          },
          {
            "id": 16787263,
            "name": "Flavour",
            "value": null,
            "children": []
          },
          {
            "id": 16787262,
            "name": "Format",
            "value": null,
            "children": []
          },
          {
            "id": 16787261,
            "name": "Group 1",
            "value": null,
            "children": []
          },
          {
            "id": 16787292,
            "name": "ProdGroup",
            "value": null,
            "children": []
          },
          {
            "id": 16787293,
            "name": "Recipe",
            "value": null,
            "children": []
          },
          {
            "id": 16787288,
            "name": "Sale status",
            "value": null,
            "children": []
          }
        ]
      },
      {
        "id": 16787245,
        "name": "Item@Site",
        "value": null,
        "children": [
          {
            "id": 16787266,
            "name": "Family@Warehouse",
            "value": null,
            "children": []
          }
        ]
      }
    ]
  },
  {
    "id": 3,
    "name": "Lead Time",
    "value": null,
    "children": []
  },
  {
    "id": 5,
    "name": "Levels",
    "value": null,
    "children": []
  },
  {
    "id": 16787268,
    "name": "N1",
    "value": null,
    "children": [
      {
        "id": 16787269,
        "name": "N2",
        "value": null,
        "children": [
          {
            "id": 16787270,
            "name": "N3",
            "value": null,
            "children": [
              {
                "id": 16787271,
                "name": "N4",
                "value": null,
                "children": [
                  {
                    "id": 16787272,
                    "name": "N5",
                    "value": null,
                    "children": [
                      {
                        "id": 33564497,
                        "name": "N6",
                        "value": null,
                        "children": [
                          {
                            "id": 33564498,
                            "name": "N7",
                            "value": null,
                            "children": [
                              {
                                "id": 33564499,
                                "name": "N8",
                                "value": null,
                                "children": [
                                  {
                                    "id": 33564500,
                                    "name": "N9",
                                    "value": null,
                                    "children": []
                                  }
                                ]
                              }
                            ]
                          }
                        ]
                      }
                    ]
                  }
                ]
              }
            ]
          }
        ]
      }
    ]
  },
  {
    "id": 16787286,
    "name": "Op set",
    "value": null,
    "children": []
  }
]
</code>```

So my problem is that I can't figure out how to get all parents nodes ids recursively until the root level and push them into the expandedKeys array.

I tried to implement a function like this:

```<code>this.list.forEach(el => {
  this.setExpandedNodes(el);
});

setExpandedNodes(node: PropertyNode) {
        if (node.children) {
            node.children.forEach(chld => {
                this.checkedKeys.forEach(key => {
                    if (chld.id === key) {
                        this.expandedKeys.push(node.id);
                    } else if (chld.children) {
                        chld.children.forEach(grChld => {
                            this.setExpandedNodes(grChld);
                        });
                    }
                });
            });
        }
    }
</code>```

But I can't figure out how to get all parent ids starting from each selected id until the root level. Anyone have an idea?

答:
A function that returns an array of parent objects may look like this:

Using tree-model-js:

```<code>    const getParentsById = (id, data) => {
var TreeModel = require('tree-model')
const tree = new TreeModel()
let path
for (let item of data) {
    const root = tree.parse(item)
    root.walk(function (node) {
        // Halt the traversal by returning false
        if (node.model.id === id) {
            path = node.getPath()
            return false;
        }
    });
}
path.pop()
return path.map(item => item.model)
}
</code>```

Without using tree-model-js:

```<code>    const getParentsById = (id, data) => {
const isFoundChild = (id, data, parents) => {
    if (data.find(item => item.id == id)) {
        return true;
    }
    else {
        for (let item of data) {
            if (item.children.length)
                if (isFoundChild(id, item.children)) {
                    parents.push(item);
                    return true;
                }
        }
        return false;
    }
}

const parents = [];
if (data.find(item => item.id == id))
    return [];
else {
    for (let item of data) {
        if (item.children.length)
            if (isFoundChild(id, item.children, parents)) {
                parents.push(item);
                return parents;
            }
    }
}
}
</code>```

Next, it is enough to apply map() to the result:

```<code>let parentsId = getParentsById(16787296, data).map(item => item.id)
</code>```

Body:
So I have an array of objects which have all nested children property. It is in front-end a treeview, which should expand the nodes until selected ones, for each id in a list. To be able to do this, I have to get all the parents ids for each selected id from the list.

For example, my list of checkedKeys ids:

[16787217, 16787245, 16787266, 16787270, 16787272, 16787265, 16787264]

All the checked items represents the ids from the list object:

My object list looks like this:

[
  {
    "id": 11,
    "name": "Forecast source",
    "value": null,
    "children": []
  },
  {
    "id": 2,
    "name": "Item Type",
    "value": null,
    "children": []
  },
  {
    "id": 16787217,
    "name": "Item@Cust",
    "value": null,
    "children": [
      {
        "id": 16787230,
        "name": "Customer",
        "value": null,
        "children": [
          {
            "id": 16787291,
            "name": "Commercial Network",
            "value": null,
            "children": []
          },
          {
            "id": 16787296,
            "name": "Distribution Site",
            "value": null,
            "children": []
          },
          {
            "id": 16787265,
            "name": "Site",
            "value": null,
            "children": []
          }
        ]
      },
      {
        "id": 16787254,
        "name": "Item",
        "value": null,
        "children": [
          {
            "id": 16787294,
            "name": "ABC (Regular)",
            "value": null,
            "children": []
          },
          {
            "id": 16787273,
            "name": "ABC (U)",
            "value": null,
            "children": []
          },
          {
            "id": 16787278,
            "name": "ABC (€)",
            "value": null,
            "children": []
          },
          {
            "id": 16787290,
            "name": "Class",
            "value": null,
            "children": []
          },
          {
            "id": 16787260,
            "name": "Family",
            "value": null,
            "children": [
              {
                "id": 16787264,
                "name": "Product line",
                "value": null,
                "children": []
              }
            ]
          },
          {
            "id": 16787263,
            "name": "Flavour",
            "value": null,
            "children": []
          },
          {
            "id": 16787262,
            "name": "Format",
            "value": null,
            "children": []
          },
          {
            "id": 16787261,
            "name": "Group 1",
            "value": null,
            "children": []
          },
          {
            "id": 16787292,
            "name": "ProdGroup",
            "value": null,
            "children": []
          },
          {
            "id": 16787293,
            "name": "Recipe",
            "value": null,
            "children": []
          },
          {
            "id": 16787288,
            "name": "Sale status",
            "value": null,
            "children": []
          }
        ]
      },
      {
        "id": 16787245,
        "name": "Item@Site",
        "value": null,
        "children": [
          {
            "id": 16787266,
            "name": "Family@Warehouse",
            "value": null,
            "children": []
          }
        ]
      }
    ]
  },
  {
    "id": 3,
    "name": "Lead Time",
    "value": null,
    "children": []
  },
  {
    "id": 5,
    "name": "Levels",
    "value": null,
    "children": []
  },
  {
    "id": 16787268,
    "name": "N1",
    "value": null,
    "children": [
      {
        "id": 16787269,
        "name": "N2",
        "value": null,
        "children": [
          {
            "id": 16787270,
            "name": "N3",
            "value": null,
            "children": [
              {
                "id": 16787271,
                "name": "N4",
                "value": null,
                "children": [
                  {
                    "id": 16787272,
                    "name": "N5",
                    "value": null,
                    "children": [
                      {
                        "id": 33564497,
                        "name": "N6",
                        "value": null,
                        "children": [
                          {
                            "id": 33564498,
                            "name": "N7",
                            "value": null,
                            "children": [
                              {
                                "id": 33564499,
                                "name": "N8",
                                "value": null,
                                "children": [
                                  {
                                    "id": 33564500,
                                    "name": "N9",
                                    "value": null,
                                    "children": []
                                  }
                                ]
                              }
                            ]
                          }
                        ]
                      }
                    ]
                  }
                ]
              }
            ]
          }
        ]
      }
    ]
  },
  {
    "id": 16787286,
    "name": "Op set",
    "value": null,
    "children": []
  }
]

So my problem is that I can't figure out how to get all parents nodes ids recursively until the root level and push them into the expandedKeys array.

I tried to implement a function like this:

this.list.forEach(el => {
  this.setExpandedNodes(el);
});

setExpandedNodes(node: PropertyNode) {
        if (node.children) {
            node.children.forEach(chld => {
                this.checkedKeys.forEach(key => {
                    if (chld.id === key) {
                        this.expandedKeys.push(node.id);
                    } else if (chld.children) {
                        chld.children.forEach(grChld => {
                            this.setExpandedNodes(grChld);
                        });
                    }
                });
            });
        }
    }

But I can't figure out how to get all parent ids starting from each selected id until the root level. Anyone have an idea?

Body:
A function that returns an array of parent objects may look like this:

Using tree-model-js:

    const getParentsById = (id, data) => {
var TreeModel = require('tree-model')
const tree = new TreeModel()
let path
for (let item of data) {
    const root = tree.parse(item)
    root.walk(function (node) {
        // Halt the traversal by returning false
        if (node.model.id === id) {
            path = node.getPath()
            return false;
        }
    });
}
path.pop()
return path.map(item => item.model)
}

Without using tree-model-js:

    const getParentsById = (id, data) => {
const isFoundChild = (id, data, parents) => {
    if (data.find(item => item.id == id)) {
        return true;
    }
    else {
        for (let item of data) {
            if (item.children.length)
                if (isFoundChild(id, item.children)) {
                    parents.push(item);
                    return true;
                }
        }
        return false;
    }
}

const parents = [];
if (data.find(item => item.id == id))
    return [];
else {
    for (let item of data) {
        if (item.children.length)
            if (isFoundChild(id, item.children, parents)) {
                parents.push(item);
                return parents;
            }
    }
}
}

Next, it is enough to apply map() to the result:

let parentsId = getParentsById(16787296, data).map(item => item.id)


问:
calculate time intersect between 2 time ranges
I have a pandas dataset of time ranges and I want to calculate for each date the overlap of time in minutes between the range (FROM_TIME - TO_TIME) and (23:00 - 07:00)

```<code>   DATE     FROM_TIME   TO_TIME
2015-01-01    2354       0408
2015-01-02    0200       0741
2015-01-03    1800       0811
2015-01-04    0015       0756
2015-01-05    0024       0259
</code>```

so for example in the first date the overlap is 254m (4h and 14m) and for the second 300m (5h). The expected output would be :

```<code>   DATE     FROM_TIME   TO_TIME  intersection
2015-01-01    2354       0408       254.0
2015-01-02    0200       0741       300.0
2015-01-03    1800       0811       480.0
2015-01-04    0015       0756       405.0
2015-01-05    0024       0259       155.0
</code>```

I tried the following :

```<code>sample = {'Date': ['2015-01-01', '2015-01-02', '2015-01-03', '2015-01-04', '2015-01-05'],
          'FROM_TIME':['2354', '0200', '1800', '0015', '0024'],
          'TO_TIME':['0408', '0741', '0811', '0756', '0259']}

dftest = pd.DataFrame.from_dict(sample)

def get_intersection(x):

    a=pd.to_datetime(x['FROM_TIME'],format='%H%M',errors='coerce')
    b=pd.to_datetime(x['TO_TIME'],format='%H%M',errors='coerce')

    c=pd.to_datetime("2300",format='%H%M')
    d=pd.to_datetime("0700",format='%H%M')

    latest_start = max(a, c)
    earliest_end = min(b, d)
    delta = pd.Timedelta(earliest_end - latest_start).seconds/60

    overlap = max(0, delta)
    return overlap

dftest['intersection']=dftest.apply(get_intersection, axis=1)
dftest

    Date      FROM_TIME  TO_TIME  intersection
  2015-01-01    2354      0408      254.0
  2015-01-02    0200      0741      480.0
  2015-01-03    1800      0811      480.0
  2015-01-04    0015      0756      480.0
  2015-01-05    0024      0259      239.0
</code>```

But the output is not correct. I understand that this is because of the max and min functions that return wrong times in some cases but how can I calculate the intersection in python?

Edit

I have changed the function to

```<code>def get_intersection(x):

    departure_time=pd.to_datetime(x['DEPARTURE_TIME'],format='%H%M',errors='coerce')
    arrival_time=pd.to_datetime(x['ARRIVAL_TIME'],format='%H%M',errors='coerce')

    upper_time=pd.to_datetime("2300",format='%H%M')
    lower_time=pd.to_datetime("0700",format='%H%M')

    if departure_time > arrival_time:
        latest_start = max(departure_time, upper_time)
        earliest_end = min(arrival_time, lower_time)
    else:
        if departure_time > lower_time:
            latest_start = lower_time
            earliest_end = lower_time
        else:
            latest_start = min(departure_time, upper_time)
            earliest_end = min(arrival_time, lower_time)

    delta = (earliest_end - latest_start).seconds/60
    print(f'departure_time = {departure_time}, arrival_time = {arrival_time}\nlatest_start = {latest_start}, earliest_end ={earliest_end}, delta = {delta}')
    overlap = max(0, delta)
    return overlap
</code>```

and seems to calculate the result that I want although is very slow on the dataset i want to work as it has millions or rows.

答:
Assuming you want the difference between from and to and that to us always after from, you can convert to datetime and compute the difference. If it is negative, add one day. Then convert to seconds and divide by 60 to get minutes.

```<code>s = (pd.to_datetime(dftest['TO_TIME'], format='%H%M')
     -pd.to_datetime(dftest['FROM_TIME'], format='%H%M'))

dftest['intersection'] = s.mask(s.lt('0d'), pd.to_timedelta('1d')+s).dt.total_seconds()//60
</code>```

Output:

```<code>         Date FROM_TIME TO_TIME  intersection
0  2015-01-01      2354    0408         254.0
1  2015-01-02      0200    0741         341.0
2  2015-01-03      1800    0811         851.0
3  2015-01-04      0015    0756         461.0
4  2015-01-05      0024    0259         155.0
</code>```

Body:
I have a pandas dataset of time ranges and I want to calculate for each date the overlap of time in minutes between the range (FROM_TIME - TO_TIME) and (23:00 - 07:00)

   DATE     FROM_TIME   TO_TIME
2015-01-01    2354       0408
2015-01-02    0200       0741
2015-01-03    1800       0811
2015-01-04    0015       0756
2015-01-05    0024       0259

so for example in the first date the overlap is 254m (4h and 14m) and for the second 300m (5h). The expected output would be :

   DATE     FROM_TIME   TO_TIME  intersection
2015-01-01    2354       0408       254.0
2015-01-02    0200       0741       300.0
2015-01-03    1800       0811       480.0
2015-01-04    0015       0756       405.0
2015-01-05    0024       0259       155.0

I tried the following :

sample = {'Date': ['2015-01-01', '2015-01-02', '2015-01-03', '2015-01-04', '2015-01-05'],
          'FROM_TIME':['2354', '0200', '1800', '0015', '0024'],
          'TO_TIME':['0408', '0741', '0811', '0756', '0259']}

dftest = pd.DataFrame.from_dict(sample)

def get_intersection(x):

    a=pd.to_datetime(x['FROM_TIME'],format='%H%M',errors='coerce')
    b=pd.to_datetime(x['TO_TIME'],format='%H%M',errors='coerce')

    c=pd.to_datetime("2300",format='%H%M')
    d=pd.to_datetime("0700",format='%H%M')

    latest_start = max(a, c)
    earliest_end = min(b, d)
    delta = pd.Timedelta(earliest_end - latest_start).seconds/60

    overlap = max(0, delta)
    return overlap

dftest['intersection']=dftest.apply(get_intersection, axis=1)
dftest

    Date      FROM_TIME  TO_TIME  intersection
  2015-01-01    2354      0408      254.0
  2015-01-02    0200      0741      480.0
  2015-01-03    1800      0811      480.0
  2015-01-04    0015      0756      480.0
  2015-01-05    0024      0259      239.0

But the output is not correct. I understand that this is because of the max and min functions that return wrong times in some cases but how can I calculate the intersection in python?

Edit

I have changed the function to

def get_intersection(x):

    departure_time=pd.to_datetime(x['DEPARTURE_TIME'],format='%H%M',errors='coerce')
    arrival_time=pd.to_datetime(x['ARRIVAL_TIME'],format='%H%M',errors='coerce')

    upper_time=pd.to_datetime("2300",format='%H%M')
    lower_time=pd.to_datetime("0700",format='%H%M')

    if departure_time > arrival_time:
        latest_start = max(departure_time, upper_time)
        earliest_end = min(arrival_time, lower_time)
    else:
        if departure_time > lower_time:
            latest_start = lower_time
            earliest_end = lower_time
        else:
            latest_start = min(departure_time, upper_time)
            earliest_end = min(arrival_time, lower_time)

    delta = (earliest_end - latest_start).seconds/60
    print(f'departure_time = {departure_time}, arrival_time = {arrival_time}\nlatest_start = {latest_start}, earliest_end ={earliest_end}, delta = {delta}')
    overlap = max(0, delta)
    return overlap

and seems to calculate the result that I want although is very slow on the dataset i want to work as it has millions or rows.

Body:
Assuming you want the difference between from and to and that to us always after from, you can convert to datetime and compute the difference. If it is negative, add one day. Then convert to seconds and divide by 60 to get minutes.

s = (pd.to_datetime(dftest['TO_TIME'], format='%H%M')
     -pd.to_datetime(dftest['FROM_TIME'], format='%H%M'))

dftest['intersection'] = s.mask(s.lt('0d'), pd.to_timedelta('1d')+s).dt.total_seconds()//60

Output:

         Date FROM_TIME TO_TIME  intersection
0  2015-01-01      2354    0408         254.0
1  2015-01-02      0200    0741         341.0
2  2015-01-03      1800    0811         851.0
3  2015-01-04      0015    0756         461.0
4  2015-01-05      0024    0259         155.0


问:
Vagrant on Windows can't vagrant-up and ssh connect
So I've watch many videos on Vagrant and it seems so simple: with VirtualBox and Vargant installed, simply specify the VM box's name in the Vagrantfile, run $ vagrant up and you should be able to $ vagrant ssh to it directly.

However, a week-end later and many headaches/broken keyboards later, this still doesn't work.

```<code>PS C:\dev\web> vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'ubuntu/trusty32'...
==> default: Matching MAC address for NAT networking...
==> default: Checking if box 'ubuntu/trusty32' is up to date...
==> default: Setting the name of the VM: web_default_1468168716511_77856
==> default: Clearing any previously set forwarded ports...
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
    default: Adapter 2: hostonly
==> default: Forwarding ports...
    default: 22 (guest) => 2222 (host) (adapter 1)
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: vagrant
    default: SSH auth method: private key
Timed out while waiting for the machine to boot. This means that
Vagrant was unable to communicate with the guest machine within
the configured ("config.vm.boot_timeout" value) time period.

If you look above, you should be able to see the error(s) that
Vagrant had when attempting to connect to the machine. These errors
are usually good hints as to what may be wrong.

If you're using a custom box, make sure that networking is properly
working and you're able to connect to the machine. It is a common
problem that networking isn't setup properly in these boxes.
Verify that authentication configurations are also setup properly,
as well.

If the box appears to be booting properly, you may want to increase
the timeout ("config.vm.boot_timeout") value.
</code>```

In the meanwhile, if I open VirtualBox Manager and open the newly installed Box, I can completely connect to it using 'vargant' as a username and password and I can see that nothing is installed on it. I can not ssh to it through PuTTY or Cygwin.

Doing a $vagrant ssh-config outputs the following:

```<code>PS C:\dev\web> vagrant ssh-config
Host default
  HostName 127.0.0.1
  User vagrant
  Port 2222
  UserKnownHostsFile /dev/null
  StrictHostKeyChecking no
  PasswordAuthentication no
  IdentityFile C:/Users/User/.vagrant.d/insecure_private_key
  IdentitiesOnly yes
  LogLevel FATAL
</code>```

My Vagrantfile:

```<code>Vagrant.configure("2") do |config|

  config.vm.box = "ubuntu/trusty32"

   config.vm.provider "virtualbox" do |vb|

     vb.gui = true

   end

   config.vm.provision "shell", inline: <<-SHELL
     apt-get update
     apt-get install -y apache2
   SHELL
end
</code>```

I have tried everything listed on serverfault and stackoverflow, I don't see any video where people have that issue, all they do is just run vagrant and it just work...

Edit: I've tried this on a Windows Server and it worked perfectly out of the box. So this is most likely an issue related to Windows 10 or something.

答: Just had the same issue on Windows 10 and installing VirtualBox Oracle VM VirtualBox Extension Pack helped</p>

Body:
So I've watch many videos on Vagrant and it seems so simple: with VirtualBox and Vargant installed, simply specify the VM box's name in the Vagrantfile, run $ vagrant up and you should be able to $ vagrant ssh to it directly.

However, a week-end later and many headaches/broken keyboards later, this still doesn't work.

PS C:\dev\web> vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'ubuntu/trusty32'...
==> default: Matching MAC address for NAT networking...
==> default: Checking if box 'ubuntu/trusty32' is up to date...
==> default: Setting the name of the VM: web_default_1468168716511_77856
==> default: Clearing any previously set forwarded ports...
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
    default: Adapter 2: hostonly
==> default: Forwarding ports...
    default: 22 (guest) => 2222 (host) (adapter 1)
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: vagrant
    default: SSH auth method: private key
Timed out while waiting for the machine to boot. This means that
Vagrant was unable to communicate with the guest machine within
the configured ("config.vm.boot_timeout" value) time period.

If you look above, you should be able to see the error(s) that
Vagrant had when attempting to connect to the machine. These errors
are usually good hints as to what may be wrong.

If you're using a custom box, make sure that networking is properly
working and you're able to connect to the machine. It is a common
problem that networking isn't setup properly in these boxes.
Verify that authentication configurations are also setup properly,
as well.

If the box appears to be booting properly, you may want to increase
the timeout ("config.vm.boot_timeout") value.

In the meanwhile, if I open VirtualBox Manager and open the newly installed Box, I can completely connect to it using 'vargant' as a username and password and I can see that nothing is installed on it. I can not ssh to it through PuTTY or Cygwin.

Doing a $vagrant ssh-config outputs the following:

PS C:\dev\web> vagrant ssh-config
Host default
  HostName 127.0.0.1
  User vagrant
  Port 2222
  UserKnownHostsFile /dev/null
  StrictHostKeyChecking no
  PasswordAuthentication no
  IdentityFile C:/Users/User/.vagrant.d/insecure_private_key
  IdentitiesOnly yes
  LogLevel FATAL

My Vagrantfile:

Vagrant.configure("2") do |config|

  config.vm.box = "ubuntu/trusty32"

   config.vm.provider "virtualbox" do |vb|

     vb.gui = true

   end

   config.vm.provision "shell", inline: <<-SHELL
     apt-get update
     apt-get install -y apache2
   SHELL
end

I have tried everything listed on serverfault and stackoverflow, I don't see any video where people have that issue, all they do is just run vagrant and it just work...

Edit: I've tried this on a Windows Server and it worked perfectly out of the box. So this is most likely an issue related to Windows 10 or something.


问:
Store Image in Room Database using typeconverter to convert bitmap into bytearray. What to write in last parameter of the model class
I don't know how to pass the bitmap as byteArray in the code below. I have added the parameter in the note model class and it is of type byte array. Now how do I use the typeConverter to convert the bitmap to bytearray and pass it? Please help.

The lines in which the parameter is to be added are in "EditActivity", under savebutton.onClicklistener, where I fill the parameters for the modelClass.

Here's my TypeConverter :

```<code>class ImageConverter {

    @TypeConverter
    fun getStringFromBitmap(bitmap: Bitmap): ByteArray {
        val outputStream = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)
        return outputStream.toByteArray()
    }

    @TypeConverter
    fun getBitmapFromString(byteArray: ByteArray): Bitmap{
        return BitmapFactory.decodeByteArray(byteArray, 0, byteArray.size)
    }
}
</code>```

And here's my "EditActivity" that adds image from gallery to the activity:

```<code>class AddEditNoteActivity : AppCompatActivity() {
    lateinit var backButton: FloatingActionButton
    lateinit var editTitle: EditText
    lateinit var editDesc: EditText
    lateinit var saveButton: FloatingActionButton
    lateinit var viewModel: JourViewModel
    lateinit var addImageButton: FloatingActionButton
    lateinit var theimage: ImageView
    lateinit var ImageURI: Uri
    lateinit var bitmap: Bitmap

    var noteID= -1

    companion object{
        const val IMAGE_REQ_CODE=100

    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_add_edit_note)
        editTitle = findViewById(R.id.editNoteTitle)
        editDesc = findViewById(R.id.editNoteDescription)
        saveButton=findViewById(R.id.jourSaveButton)
        backButton=findViewById(R.id.backButton)
        addImageButton=findViewById(R.id.jourAddImgButton)
        theimage=findViewById(R.id.imageView1)

        viewModel= ViewModelProvider(
            this,
            ViewModelProvider.AndroidViewModelFactory.getInstance(application)
        ).get(JourViewModel::class.java)

        val noteType = intent.getStringExtra("noteType")
        if(noteType.equals("Edit")){
            val noteTitle = intent.getStringExtra("noteTitle")
            val noteDesc = intent.getStringExtra("noteDescription")
            noteID= intent.getIntExtra("noteID",-1)
            editTitle.setText(noteTitle)
            editDesc.setText(noteDesc)
        }

        saveButton.setOnClickListener{
            val noteTitle= editTitle.text.toString()
            val noteDesc= editDesc.text.toString()
            val storebyte=

            if(noteType.equals("Edit")){
                if(noteTitle.isNotEmpty() && noteDesc.isNotEmpty()){
                    val sdf= SimpleDateFormat("MMM, dd,yyyy")
                    val currentDate:String= sdf.format(Date())
                    val updateNote = Note(noteTitle, noteDesc, currentDate, )
                    updateNote.id=noteID
                    viewModel.updateNote(updateNote)
                    Toast.makeText(this,"Updated!",Toast.LENGTH_SHORT).show()
                    startActivity(Intent(applicationContext,MainActivity::class.java))
                    this.finish()
                }else{
                    Toast.makeText(this,"Please fill both the columns!",Toast.LENGTH_SHORT).show()
                }
            }else{
                if(noteTitle.isNotEmpty() && noteDesc.isNotEmpty()){
                    val sdf= SimpleDateFormat("MMM dd,yyyy")
                    val currentDate:String= sdf.format(Date())
                    viewModel.addNote(Note(noteTitle,noteDesc,currentDate,))
                    Toast.makeText(this,"Added!",Toast.LENGTH_SHORT).show()
                    startActivity(Intent(applicationContext,MainActivity::class.java))
                    this.finish()
                }else{
                    Toast.makeText(this,"Please fill both the columns!",Toast.LENGTH_SHORT).show()
                }
            }

        }

        backButton.setOnClickListener{
            val intent = Intent(this@AddEditNoteActivity,MainActivity::class.java)
            startActivity(intent)
            this.finish()
        }

        addImageButton.setOnClickListener{
            pickImageGallery()

        }
    }

    private fun pickImageGallery() {
        val intent = Intent(Intent.ACTION_PICK)
        intent.type = "image/"
        startActivityForResult(intent, IMAGE_REQ_CODE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?){
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode== IMAGE_REQ_CODE && resultCode==RESULT_OK){

             ImageURI  = data?.data!!

            if (ImageURI!=null){
                theimage.setImageURI(data?.data)

                try {
                    bitmap =MediaStore.Images.Media.getBitmap(contentResolver, ImageURI)
                    theimage.setImageBitmap(bitmap)
                }catch(exception: IOException){
                    exception.printStackTrace()

                }

            }

        }

    }

}
</code>```

ModelClass:

```<code>@Entity(tableName = "jourTable")
class Note(
    @ColumnInfo(name = "title") val jourTitle:String,
    @ColumnInfo(name = "description") val jourDescription:String,
    @ColumnInfo(name = "date") val jourDate:String,
    @ColumnInfo(name = "image", typeAffinity = ColumnInfo.BLOB) val jourImage: ByteArray
) {
    @PrimaryKey(autoGenerate = true)var id=0
}
</code>```

答:
Now how do I use the typeConverter to convert the bitmap to bytearray and pass it?

Typically you don't use the Type Converter, you let Room know about it and Room then uses it.

So taking getStringFromBitmap(bitmap: Bitmap): ByteArray (should really be getByteArrayFromBitmap)

Then in the class annotaed with @Database ADD an @TypeConverters annotation (NOTE the plural not singular) that defines the class where the Type Converters are located e.g :-

```<code>@TypeConverters(ImageConverter::class) //<<<<< ADDED
@Database(entities = [Note::class], version = 1, exportSchema = false)
abstract class TheDatabase: RoomDatabase() {
    ....
</code>```

Now this will convert a BitMap to a ByteArray as such you don't code the type as ByteArray but instead as Bitmap.

You can use the type converter and bypass Room's automatic use of it.

Let's say you have (uses both) :-

```<code>@Entity(tableName = "jourTable")
class Note(
    @ColumnInfo(name = "title") val jourTitle:String,
    @ColumnInfo(name = "description") val jourDescription:String,
    @ColumnInfo(name = "date") val jourDate:String,
    @ColumnInfo(name = "image", typeAffinity = ColumnInfo.BLOB) val jourImage: Bitmap, //<<<<< will use the TypeConverter
    @ColumnInfo(name = "altImage") val jourAltImage: ByteArray //<<<<< will not use the TypeConverter
) {
    @PrimaryKey(autoGenerate = true)var id=0
}
</code>```

And then have an @Dao annotated interface or abstract class such as :-

```<code>@Dao
abstract class AllDao {
    @Insert
    abstract fun insert(note: Note): Long
}
</code>```

Then in an activity you could use:-

```<code>    dao.insert(
        Note
            ("Title1","Description1","2021-02-08",
            bm, /*<<<<< ROOM will know to get the ByteArray from the Bitmap and utilise the TypeConverter */
            ImageConverter().getStringFromBitmap(bm) /* use the TypeConverter to get a ByteArray (not needed)*/
        )
    )
</code>```

As a working example consider the following :-

```<code>    val bm = BitmapFactory.decodeByteArray(ByteArray(0),0,0) // results in null Bitmap
    val db = TheDatabase.getInstance(this);
    val dao = db.getAllDao()

    dao.insert(
        Note
            ("Title1","Description1","2021-02-08",
            bm, /*<<<<< ROOM will know to get the ByteArray from the Bitmap and utilise the TypeConverter */
            ImageConverter().getStringFromBitmap(bm) /* use the TypeConverter to get a ByteArray (not needed)*/
        )
    )
</code>```

and a modified TypeConverter which handles the null Bitmap by returning a ByteArray of 10 0 bytes i.e. :-

```<code>@TypeConverter
fun getStringFromBitmap(bitmap: Bitmap?): ByteArray {
    if (bitmap == null) {
        return ByteArray(10)
    }
    val outputStream = ByteArrayOutputStream()
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)
    return outputStream.toByteArray()
}
</code>```

Then, when run, the result as per App Inspection is :-

i.e The image column is the 10 0 bytes as produced by the TypeConverter automatically invoked by Room. The altimage column likewise is 10 0 bytes but via the TyoeConverter manually invoked.

When extracting data again Room will automatically invoke the 2nd TypeConverter for the image column/field the altImage column/field would be returned as a ByteArray.

Body:
I don't know how to pass the bitmap as byteArray in the code below. I have added the parameter in the note model class and it is of type byte array. Now how do I use the typeConverter to convert the bitmap to bytearray and pass it? Please help.

The lines in which the parameter is to be added are in "EditActivity", under savebutton.onClicklistener, where I fill the parameters for the modelClass.

Here's my TypeConverter :

class ImageConverter {

    @TypeConverter
    fun getStringFromBitmap(bitmap: Bitmap): ByteArray {
        val outputStream = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)
        return outputStream.toByteArray()
    }

    @TypeConverter
    fun getBitmapFromString(byteArray: ByteArray): Bitmap{
        return BitmapFactory.decodeByteArray(byteArray, 0, byteArray.size)
    }
}

And here's my "EditActivity" that adds image from gallery to the activity:

class AddEditNoteActivity : AppCompatActivity() {
    lateinit var backButton: FloatingActionButton
    lateinit var editTitle: EditText
    lateinit var editDesc: EditText
    lateinit var saveButton: FloatingActionButton
    lateinit var viewModel: JourViewModel
    lateinit var addImageButton: FloatingActionButton
    lateinit var theimage: ImageView
    lateinit var ImageURI: Uri
    lateinit var bitmap: Bitmap

    var noteID= -1

    companion object{
        const val IMAGE_REQ_CODE=100

    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_add_edit_note)
        editTitle = findViewById(R.id.editNoteTitle)
        editDesc = findViewById(R.id.editNoteDescription)
        saveButton=findViewById(R.id.jourSaveButton)
        backButton=findViewById(R.id.backButton)
        addImageButton=findViewById(R.id.jourAddImgButton)
        theimage=findViewById(R.id.imageView1)

        viewModel= ViewModelProvider(
            this,
            ViewModelProvider.AndroidViewModelFactory.getInstance(application)
        ).get(JourViewModel::class.java)

        val noteType = intent.getStringExtra("noteType")
        if(noteType.equals("Edit")){
            val noteTitle = intent.getStringExtra("noteTitle")
            val noteDesc = intent.getStringExtra("noteDescription")
            noteID= intent.getIntExtra("noteID",-1)
            editTitle.setText(noteTitle)
            editDesc.setText(noteDesc)
        }

        saveButton.setOnClickListener{
            val noteTitle= editTitle.text.toString()
            val noteDesc= editDesc.text.toString()
            val storebyte=

            if(noteType.equals("Edit")){
                if(noteTitle.isNotEmpty() && noteDesc.isNotEmpty()){
                    val sdf= SimpleDateFormat("MMM, dd,yyyy")
                    val currentDate:String= sdf.format(Date())
                    val updateNote = Note(noteTitle, noteDesc, currentDate, )
                    updateNote.id=noteID
                    viewModel.updateNote(updateNote)
                    Toast.makeText(this,"Updated!",Toast.LENGTH_SHORT).show()
                    startActivity(Intent(applicationContext,MainActivity::class.java))
                    this.finish()
                }else{
                    Toast.makeText(this,"Please fill both the columns!",Toast.LENGTH_SHORT).show()
                }
            }else{
                if(noteTitle.isNotEmpty() && noteDesc.isNotEmpty()){
                    val sdf= SimpleDateFormat("MMM dd,yyyy")
                    val currentDate:String= sdf.format(Date())
                    viewModel.addNote(Note(noteTitle,noteDesc,currentDate,))
                    Toast.makeText(this,"Added!",Toast.LENGTH_SHORT).show()
                    startActivity(Intent(applicationContext,MainActivity::class.java))
                    this.finish()
                }else{
                    Toast.makeText(this,"Please fill both the columns!",Toast.LENGTH_SHORT).show()
                }
            }

        }

        backButton.setOnClickListener{
            val intent = Intent(this@AddEditNoteActivity,MainActivity::class.java)
            startActivity(intent)
            this.finish()
        }

        addImageButton.setOnClickListener{
            pickImageGallery()

        }
    }

    private fun pickImageGallery() {
        val intent = Intent(Intent.ACTION_PICK)
        intent.type = "image/"
        startActivityForResult(intent, IMAGE_REQ_CODE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?){
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode== IMAGE_REQ_CODE && resultCode==RESULT_OK){

             ImageURI  = data?.data!!

            if (ImageURI!=null){
                theimage.setImageURI(data?.data)

                try {
                    bitmap =MediaStore.Images.Media.getBitmap(contentResolver, ImageURI)
                    theimage.setImageBitmap(bitmap)
                }catch(exception: IOException){
                    exception.printStackTrace()

                }

            }

        }

    }

}

ModelClass:

@Entity(tableName = "jourTable")
class Note(
    @ColumnInfo(name = "title") val jourTitle:String,
    @ColumnInfo(name = "description") val jourDescription:String,
    @ColumnInfo(name = "date") val jourDate:String,
    @ColumnInfo(name = "image", typeAffinity = ColumnInfo.BLOB) val jourImage: ByteArray
) {
    @PrimaryKey(autoGenerate = true)var id=0
}

Body:
Now how do I use the typeConverter to convert the bitmap to bytearray and pass it?

Typically you don't use the Type Converter, you let Room know about it and Room then uses it.

So taking getStringFromBitmap(bitmap: Bitmap): ByteArray (should really be getByteArrayFromBitmap)

Then in the class annotaed with @Database ADD an @TypeConverters annotation (NOTE the plural not singular) that defines the class where the Type Converters are located e.g :-

@TypeConverters(ImageConverter::class) //<<<<< ADDED
@Database(entities = [Note::class], version = 1, exportSchema = false)
abstract class TheDatabase: RoomDatabase() {
    ....

Now this will convert a BitMap to a ByteArray as such you don't code the type as ByteArray but instead as Bitmap.

You can use the type converter and bypass Room's automatic use of it.

Let's say you have (uses both) :-

@Entity(tableName = "jourTable")
class Note(
    @ColumnInfo(name = "title") val jourTitle:String,
    @ColumnInfo(name = "description") val jourDescription:String,
    @ColumnInfo(name = "date") val jourDate:String,
    @ColumnInfo(name = "image", typeAffinity = ColumnInfo.BLOB) val jourImage: Bitmap, //<<<<< will use the TypeConverter
    @ColumnInfo(name = "altImage") val jourAltImage: ByteArray //<<<<< will not use the TypeConverter
) {
    @PrimaryKey(autoGenerate = true)var id=0
}

And then have an @Dao annotated interface or abstract class such as :-

@Dao
abstract class AllDao {
    @Insert
    abstract fun insert(note: Note): Long
}

Then in an activity you could use:-

    dao.insert(
        Note
            ("Title1","Description1","2021-02-08",
            bm, /*<<<<< ROOM will know to get the ByteArray from the Bitmap and utilise the TypeConverter */
            ImageConverter().getStringFromBitmap(bm) /* use the TypeConverter to get a ByteArray (not needed)*/
        )
    )

As a working example consider the following :-

    val bm = BitmapFactory.decodeByteArray(ByteArray(0),0,0) // results in null Bitmap
    val db = TheDatabase.getInstance(this);
    val dao = db.getAllDao()

    dao.insert(
        Note
            ("Title1","Description1","2021-02-08",
            bm, /*<<<<< ROOM will know to get the ByteArray from the Bitmap and utilise the TypeConverter */
            ImageConverter().getStringFromBitmap(bm) /* use the TypeConverter to get a ByteArray (not needed)*/
        )
    )

and a modified TypeConverter which handles the null Bitmap by returning a ByteArray of 10 0 bytes i.e. :-

@TypeConverter
fun getStringFromBitmap(bitmap: Bitmap?): ByteArray {
    if (bitmap == null) {
        return ByteArray(10)
    }
    val outputStream = ByteArrayOutputStream()
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)
    return outputStream.toByteArray()
}

Then, when run, the result as per App Inspection is :-

i.e The image column is the 10 0 bytes as produced by the TypeConverter automatically invoked by Room. The altimage column likewise is 10 0 bytes but via the TyoeConverter manually invoked.

When extracting data again Room will automatically invoke the 2nd TypeConverter for the image column/field the altImage column/field would be returned as a ByteArray.


问:
i18next bold text in the middle of a translation
I have a static file called translations.json which includes my translations:

```<code>{
  "common": {
    "greeting": "We will see you at NEW YORK in the morning!"
  }
}
</code>```

Within my react code, ive been use doing somethign along the lines of:

```<code><p>{translate('common.greeting')}</p>
</code>```

However, I want the word "NEW YORK" to be bold. Ive been doing some research and I see the the Trans component might be what im looking for but im having no luck. Im about to just split the translation into 3 parts... greetingIntro, grettingBold, and grettingEnd...

Can someone point me in the right direction?

答:
Since v11.6 they have an alternate style which lists components:

They're example:

```<code><Trans
  i18nKey="myKey" // optional -> fallbacks to defaults if not provided
  defaults="hello <italic>beautiful</italic> <bold>{{what}}</bold>" // optional defaultValue
  values={{ what: 'world'}}
  components={{ italic: <i />, bold: <strong /> }}
/>
</code>```

This would come out something like:

```<code><Trans
  i18nkey='common.greeting'
  defaults="We will see you at <bold>{{city}}</bold> in the morning!"
  values={{ city: 'NEW YORK' }}>
  components={{ bold: <strong /> }}
/>
</code>```

Body:
I have a static file called translations.json which includes my translations:

{
  "common": {
    "greeting": "We will see you at NEW YORK in the morning!"
  }
}

Within my react code, ive been use doing somethign along the lines of:

{translate('common.greeting')}

However, I want the word "NEW YORK" to be bold. Ive been doing some research and I see the the Trans component might be what im looking for but im having no luck. Im about to just split the translation into 3 parts... greetingIntro, grettingBold, and grettingEnd...

Can someone point me in the right direction?

Body:
Since v11.6 they have an alternate style which lists components:

They're example:

<Trans
  i18nKey="myKey" // optional -> fallbacks to defaults if not provided
  defaults="hello <italic>beautiful</italic> <bold>{{what}}</bold>" // optional defaultValue
  values={{ what: 'world'}}
  components={{ italic: <i />, bold: <strong /> }}
/>

This would come out something like:

<Trans
  i18nkey='common.greeting'
  defaults="We will see you at <bold>{{city}}</bold> in the morning!"
  values={{ city: 'NEW YORK' }}>
  components={{ bold: <strong /> }}
/>


问:
How do I parameterize test cases in TypeScript unit tests?
I have a simple passing unit test:

```<code>describe("Example", () => {
    it("Return digits or empty string", () => {
        let actual = SmokeTest.ProblemOne("1");
        assert.equal(actual, "1");
    })
})
</code>```

I now wish to test many other cases (empty string, more complex inputs and edge-cases). I have read about how to implement fixtures in TypeScript but this seems like overkill for an array of test-input, expected-output values.

What is the idiomatic way to define such an array in TypeScript / Mocha?

答:
From the Mocha documentation:

No special syntax is required... to parameterize tests [you can] generate them with a closure.

describe("Example", () => {

    // define a closure that calls the method we are testing
    const testProblemOne = ({arg, expected}) =>
        function () {
            const actual = SmokeTest.ProblemOne(arg);
            assert.equal(actual, expected);
        }

    // invoke the closure for each test case
    it("Empty returns empty", testProblemOne({arg: "", expected: ""}));
    it("Single digit identity", testProblemOne({arg: "1", expected: "1"}));
    // additional test cases here...
})
```

This technique avoids using foreach in favor of readability and broader IDE integration.

Body:
I have a simple passing unit test:

describe("Example", () => {
    it("Return digits or empty string", () => {
        let actual = SmokeTest.ProblemOne("1");
        assert.equal(actual, "1");
    })
})

I now wish to test many other cases (empty string, more complex inputs and edge-cases). I have read about how to implement fixtures in TypeScript but this seems like overkill for an array of test-input, expected-output values.

What is the idiomatic way to define such an array in TypeScript / Mocha?

Body:
From the Mocha documentation:

No special syntax is required... to parameterize tests [you can] generate them with a closure.

describe("Example", () => {

    // define a closure that calls the method we are testing
    const testProblemOne = ({arg, expected}) =>
        function () {
            const actual = SmokeTest.ProblemOne(arg);
            assert.equal(actual, expected);
        }

    // invoke the closure for each test case
    it("Empty returns empty", testProblemOne({arg: "", expected: ""}));
    it("Single digit identity", testProblemOne({arg: "1", expected: "1"}));
    // additional test cases here...
})

This technique avoids using foreach in favor of readability and broader IDE integration.


问:
C# linq how to build expandoobjects into a list?
I am trying to select expandoobjects (qs_ll[0][0]) from List<dynamic> and build them into a new list.

I have managed to use GetRange() and .concat() to select and combine sublists. It does work, but it is rather verbose. I would fancy the index method as it looks tidy.

I currently trying like Enumerable.Concat(qs_ll[0][0],qs_ll[0][1]). However, the result turn out to be a series of objects [column name,value] and it does not have ToList(). I would like it keep the structure of expandoobjects{value1,value2,value3,...}.

I assume it can be done with the use of certain functions.

答:
Alright, I find the most straightforward way by myself (it is just there all the time).

new List<dynamic>{qs_ll[0][0], qs_ll[0][1]};

I have been thinking of it in a merging lists manner, forgetting the fact that those variables are just elements which would just build a list. To build elements into a list, how could it be done easier by just new List<>{ele1,ele2,...};?..


问:
How to build header only C++ library within Bazel workspace?
I'm working on a C++ project and I need Numpy like arrays and functionalities in C++. I found some alternatives like xtensor, NumCpp etc. These are header only libraries. The problem is I'm experimenting with Bazel for the first time so, I don't have any idea about how do I add header only library to Bazel workspace. There are some suggestions like genrule-environment, rules-foreign-cc suggested on other questions around Bazel. I've added http_archive to WORKSPACE file, but I'm not sure what to add in BUILD file.

WORKSPACE file

```<code>load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")

all_content = """filegroup(name = "all", srcs = glob(["**"]), visibility = ["//visibility:public"])"""

http_archive(
    name = "xtensor",
    build_file_content = all_content,
    strip_prefix = "xtensor-master",
    urls = ["https://github.com/xtensor-stack/xtensor/archive/refs/heads/master.zip"],
)

http_archive(
    name = "NumCpp",
    build_file_content = all_content,
    strip_prefix = "NumCpp-master",
    urls = ["https://github.com/dpilger26/NumCpp/archive/refs/heads/master.zip"],
)

http_archive(
    name = "rules_foreign_cc",
    sha256 = "c2cdcf55ffaf49366725639e45dedd449b8c3fe22b54e31625eb80ce3a240f1e",
    strip_prefix = "rules_foreign_cc-0.1.0",
    url = "https://github.com/bazelbuild/rules_foreign_cc/archive/0.1.0.zip",
)

load("@rules_foreign_cc//:workspace_definitions.bzl", "rules_foreign_cc_dependencies")

rules_foreign_cc_dependencies()
</code>```

I've tried to follow documentation, but failed every time. Some help would be appreciated.

答:
For simple things like header-only libraries, I would write BUILD files yourself, without using rules_foreign_cc. Just write a cc_library with no srcs. Something like this:

http_archive(
    name = "xtensor",
    build_file_content = all_content,
    strip_prefix = "xtensor-master",
    urls = ["https://github.com/xtensor-stack/xtensor/archive/refs/heads/master.zip"],
    build_file_content = """
cc_library(
    name = "xtensor",
    visibility = ["//visibility:public"],
    hdrs = glob(["xtensor/*.hpp"]),
    defines = [
        "XTENSOR_ENABLE_ASSERT",
    ],
    deps = [
        "@tbb",
    ],
)
""",
)
```
<p><code>@xtensor</code> will be your Bazel repository. The <code>build_file_content</code> will be used to create a <code>BUILD.bazel</code> file in it. That means your code can depend on it via <code>@xtensor//:xtensor</code>, which can be shortened to just <code>@xtensor</code>. You can also put that in a separate file (say <code>build/BUILD.xtensor.bazel</code>) and then use <code>build_file = "@build//:BUILD.xtensor.bazel"</code> instead of putting it inline in <code>WORKSPACE</code> via <code>build_file_content</code>.</p>
<p>rules_foreign_cc is going to generate something equivalent if you get it set up, but that seems like a lot more trouble to me than just writing it yourself. I set <code>defines</code> and <code>deps</code> based on a scan through the CMakeLists.txt, you'll want to customize based on how you want it configured.</p>
<p>The only other thing I see that CMakeLists doing (beyond finding dependencies and setting some <code>-D</code> flags, which translate as shown above) is generating a single file that #includes all the others. If you want to do that, I'd do something like this (in the BUILD file for <code>@xtensor</code>):</p>
<pre class="lang-py prettyprint-override"><code>genrule(
    name = "gen_single_include",
    outs = ["xtensor.hpp"],
    cmd = "\n".join([
        "cat > $@ <<'END'",
        "#ifndef XTENSOR",
        "#define XTENSOR",
    ] + ["#include \"%s\"" % h[len("xtensor/"):]
         for h in glob(["xtensor/*.hpp"])
         if h not in [
             "xtensor/xexpression_holder.hpp",
             "xtensor/xjson.hpp",
             "xtensor/xmime.hpp",
             "xtensor/xnpy.hpp",
          ]] + [
        "#endif",
        "END",
    ]),
</code>```

I may not have gotten everything perfect here, but the idea is to build up the file using cat to copy stdin to it, a bash here document to feed the content in, and Python-style list comprehensions to actually build up the content.

Body:
I'm working on a C++ project and I need Numpy like arrays and functionalities in C++. I found some alternatives like xtensor, NumCpp etc. These are header only libraries. The problem is I'm experimenting with Bazel for the first time so, I don't have any idea about how do I add header only library to Bazel workspace. There are some suggestions like genrule-environment, rules-foreign-cc suggested on other questions around Bazel. I've added http_archive to WORKSPACE file, but I'm not sure what to add in BUILD file.

WORKSPACE file

load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")

all_content = """filegroup(name = "all", srcs = glob(["**"]), visibility = ["//visibility:public"])"""

http_archive(
    name = "xtensor",
    build_file_content = all_content,
    strip_prefix = "xtensor-master",
    urls = ["https://github.com/xtensor-stack/xtensor/archive/refs/heads/master.zip"],
)

http_archive(
    name = "NumCpp",
    build_file_content = all_content,
    strip_prefix = "NumCpp-master",
    urls = ["https://github.com/dpilger26/NumCpp/archive/refs/heads/master.zip"],
)

http_archive(
    name = "rules_foreign_cc",
    sha256 = "c2cdcf55ffaf49366725639e45dedd449b8c3fe22b54e31625eb80ce3a240f1e",
    strip_prefix = "rules_foreign_cc-0.1.0",
    url = "https://github.com/bazelbuild/rules_foreign_cc/archive/0.1.0.zip",
)

load("@rules_foreign_cc//:workspace_definitions.bzl", "rules_foreign_cc_dependencies")

rules_foreign_cc_dependencies()

I've tried to follow documentation, but failed every time. Some help would be appreciated.

Body:
For simple things like header-only libraries, I would write BUILD files yourself, without using rules_foreign_cc. Just write a cc_library with no srcs. Something like this:

http_archive(
    name = "xtensor",
    build_file_content = all_content,
    strip_prefix = "xtensor-master",
    urls = ["https://github.com/xtensor-stack/xtensor/archive/refs/heads/master.zip"],
    build_file_content = """
cc_library(
    name = "xtensor",
    visibility = ["//visibility:public"],
    hdrs = glob(["xtensor/*.hpp"]),
    defines = [
        "XTENSOR_ENABLE_ASSERT",
    ],
    deps = [
        "@tbb",
    ],
)
""",
)

@xtensor will be your Bazel repository. The build_file_content will be used to create a BUILD.bazel file in it. That means your code can depend on it via @xtensor//:xtensor, which can be shortened to just @xtensor. You can also put that in a separate file (say build/BUILD.xtensor.bazel) and then use build_file = "@build//:BUILD.xtensor.bazel" instead of putting it inline in WORKSPACE via build_file_content.

rules_foreign_cc is going to generate something equivalent if you get it set up, but that seems like a lot more trouble to me than just writing it yourself. I set defines and deps based on a scan through the CMakeLists.txt, you'll want to customize based on how you want it configured.

The only other thing I see that CMakeLists doing (beyond finding dependencies and setting some -D flags, which translate as shown above) is generating a single file that #includes all the others. If you want to do that, I'd do something like this (in the BUILD file for @xtensor):

genrule(
    name = "gen_single_include",
    outs = ["xtensor.hpp"],
    cmd = "\n".join([
        "cat > $@ <<'END'",
        "#ifndef XTENSOR",
        "#define XTENSOR",
    ] + ["#include \"%s\"" % h[len("xtensor/"):]
         for h in glob(["xtensor/*.hpp"])
         if h not in [
             "xtensor/xexpression_holder.hpp",
             "xtensor/xjson.hpp",
             "xtensor/xmime.hpp",
             "xtensor/xnpy.hpp",
          ]] + [
        "#endif",
        "END",
    ]),

I may not have gotten everything perfect here, but the idea is to build up the file using cat to copy stdin to it, a bash here document to feed the content in, and Python-style list comprehensions to actually build up the content.


问:
If a variable is created within the scope of a function that returns a function that uses that variable. Is it possible to acces that variable outside
```<code>function creatPrintNumFunction()
{
  var num= 12;
  return function printNum()
  {
     console.log(num);
  }
}

 var printer = creatPrintNumFunction();
printer.num =13; //this part doesn't work but is there a way to access this Num variable Outside the creatPrintNumFunction, The printer function must be finding the num variable from somewhere.
printer();

</code>```

So how can I get this code to print 13 instead of 12 most importantly with out changing any of the code of the createPrintNumFunction().

For more context on what I really need to use this theory for. I'm using an external module express-sessions in node.js that I don't want to change. There is this 'store' variable where all the sessions are stored that I need to access only problem is that it's created within a function.There is another way i could access it but it's not really convenient

答:
So, the comment you wrote about printNum() function being able to access the num variable somehow is due to JavaScript closures. Closures are an important JavaScript topic which I would recommend looking at some online resources or this stackoverflow post JavaScript closures to learn about. Essentially when you return the printNum function from createPrintNumFunction, the printNum function will remember the num variable that was declared in createPrintNumFunction. But to answer your question of whether you can access the variable outside of the scope it was declared in, then the answer is no. An outer scope cannot access variables from an inner scope. Inner scopes can access variables from outer scopes. So, unless you are keeping track of the num variable from outside of the scope that it was declared in, you won't be able to access the value num holds outside of the scope it was declared in.

So, here you can change the value of num inside of the printNum function itself like this:

function creatPrintNumFunction() {
  var num = 12;
  return function printNum() {
    num = 13;
    console.log(num);
  };
}

var printer = creatPrintNumFunction();
printer.num = 13; //this part doesn't work but is there a way to access this Num variable Outside the creatPrintNumFunction, The printer function must be finding the num variable from somewhere.
printer();```
</div>
</div>
</p>
<p>You could define a global variable that keeps track of the <code>num</code> variable. Then through the scope chain the value used inside of the printNum function for the <code>num</code> variable will resolve to the value your global variable currently contains like so:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var num = 12;

function creatPrintNumFunction() {
  return function printNum() {
    console.log(num);
  };
}

var printer = creatPrintNumFunction();
num = 13; //this part doesn't work but is there a way to access this Num variable Outside the creatPrintNumFunction, The printer function must be finding the num variable from somewhere.
printer();</code>```

I'm sure there are other methods to go about this as well but I hope that one of the above methods fits your need.

Body:
function creatPrintNumFunction()
{
  var num= 12;
  return function printNum()
  {
     console.log(num);
  }
}

 var printer = creatPrintNumFunction();
printer.num =13; //this part doesn't work but is there a way to access this Num variable Outside the creatPrintNumFunction, The printer function must be finding the num variable from somewhere.
printer();

So how can I get this code to print 13 instead of 12 most importantly with out changing any of the code of the createPrintNumFunction().

For more context on what I really need to use this theory for. I'm using an external module express-sessions in node.js that I don't want to change. There is this 'store' variable where all the sessions are stored that I need to access only problem is that it's created within a function.There is another way i could access it but it's not really convenient

Body:
So, the comment you wrote about printNum() function being able to access the num variable somehow is due to JavaScript closures. Closures are an important JavaScript topic which I would recommend looking at some online resources or this stackoverflow post JavaScript closures to learn about. Essentially when you return the printNum function from createPrintNumFunction, the printNum function will remember the num variable that was declared in createPrintNumFunction. But to answer your question of whether you can access the variable outside of the scope it was declared in, then the answer is no. An outer scope cannot access variables from an inner scope. Inner scopes can access variables from outer scopes. So, unless you are keeping track of the num variable from outside of the scope that it was declared in, you won't be able to access the value num holds outside of the scope it was declared in.

So, here you can change the value of num inside of the printNum function itself like this:

function creatPrintNumFunction() {
  var num = 12;
  return function printNum() {
    num = 13;
    console.log(num);
  };
}

var printer = creatPrintNumFunction();
printer.num = 13; //this part doesn't work but is there a way to access this Num variable Outside the creatPrintNumFunction, The printer function must be finding the num variable from somewhere.
printer();

You could define a global variable that keeps track of the num variable. Then through the scope chain the value used inside of the printNum function for the num variable will resolve to the value your global variable currently contains like so:

var num = 12;

function creatPrintNumFunction() {
  return function printNum() {
    console.log(num);
  };
}

var printer = creatPrintNumFunction();
num = 13; //this part doesn't work but is there a way to access this Num variable Outside the creatPrintNumFunction, The printer function must be finding the num variable from somewhere.
printer();

I'm sure there are other methods to go about this as well but I hope that one of the above methods fits your need.


问:
python (confused in code, need explanation)
```<code>list1 = ["xyz", "zara", "Pynative"]
print(max(list1))
</code>```

the output will be zara on the terminal in py charm

please I am having difficulties reading this code, someone should please explain to me

答:
The max value of the list is not the last one alphabetically and 'z' is not necessarily the highest (as the other answers and comments have said.

The max function evaluates the ord() of the first character so 'z' is the highest in this case, but 'Z'(capital) is not higher than 'x' for example so:

```<code>list1 = ["xyz", "Zara", "Pynative"]
print(max(list1))
</code>```

gives:

```<code>xyz
</code>```

hence it's not alphabetical.

Another example for futher clarification:

```<code>lst = ['test', 'ack', 'Zzzzzck']
print(max(lst))
</code>```

gives:

```<code>test
</code>```

Because:

```<code>print(ord('t'))
print(ord('Z'))
print(ord('a'))
</code>```

gives:

```<code>116 #t is highest
90
97
</code>```

Lastly:

```<code>lst = ['za3', '{!9zb4']
print(max(lst))
</code>```

gives:

```<code>{!9zb4
</code>```

because:

```<code>print(ord('z'))
print(ord('{'))
</code>```

gives:

```<code>122
123 #{ is higher
</code>```

If the firs character is the same it evaluates the second, and so on.

Body:
list1 = ["xyz", "zara", "Pynative"]
print(max(list1))

the output will be zara on the terminal in py charm

please I am having difficulties reading this code, someone should please explain to me

Body:
The max value of the list is not the last one alphabetically and 'z' is not necessarily the highest (as the other answers and comments have said.

The max function evaluates the ord() of the first character so 'z' is the highest in this case, but 'Z'(capital) is not higher than 'x' for example so:

list1 = ["xyz", "Zara", "Pynative"]
print(max(list1))

gives:

xyz

hence it's not alphabetical.

Another example for futher clarification:

lst = ['test', 'ack', 'Zzzzzck']
print(max(lst))

gives:

test

Because:

print(ord('t'))
print(ord('Z'))
print(ord('a'))

gives:

116 #t is highest
90
97

Lastly:

lst = ['za3', '{!9zb4']
print(max(lst))

gives:

{!9zb4

because:

print(ord('z'))
print(ord('{'))

gives:

122
123 #{ is higher

If the firs character is the same it evaluates the second, and so on.