问:
SQL request : how to make a particular select with multi tables and calcul?
Here's my problem. I've 4 tables on an Oracle Database:

Team(teamID, teamName)

TeamMembers(membersID, teamID, membersStatusID)

Members(membersID, membersName)

Status(membersStatusID, statusName)

I need to gets the teamName, the numbers of teamMembers in these teams and the name of the members who have the status "Captain"... all of this in one SELECT in SQL.

Many hours on this and no solution... any idea?

Edit: I need to see all teams, even if there's no members in it.

答:
I'm a bit rusty on my oracle, so there may be some slight syntax issues here, but I'll give it a shot:

```<code>SELECT t.teamName,
  count(*) AS teamMembers,
  c.membersName as teamCaptain
FROM team t
  INNER JOIN TeamMembers tm ON tm.teamID = t.teamID
  LEFT JOIN Members m ON m.membersID = tm.membersID
  LEFT JOIN TeamMembers tmc ON tmc.teamID = t.teamID AND tmc.memberStatusID = "Captain"
  LEFT JOIN Members c ON c.membersID = tmc.membersID
  GROUP BY t.teamName, c.membersName
</code>```

Edit: Forgot the GROUP BY line!

Body:
I'm a bit rusty on my oracle, so there may be some slight syntax issues here, but I'll give it a shot:

SELECT t.teamName,
  count(*) AS teamMembers,
  c.membersName as teamCaptain
FROM team t
  INNER JOIN TeamMembers tm ON tm.teamID = t.teamID
  LEFT JOIN Members m ON m.membersID = tm.membersID
  LEFT JOIN TeamMembers tmc ON tmc.teamID = t.teamID AND tmc.memberStatusID = "Captain"
  LEFT JOIN Members c ON c.membersID = tmc.membersID
  GROUP BY t.teamName, c.membersName

Edit: Forgot the GROUP BY line!


来源: stackexchange

问:
Found .NET SDK, but did not find dotnet.dll
I recently installed Visual Studio 2022 preview.

Today I was in a workshop and there was some feature that didn't work, and it turned out it was because I had the preview version of .NET 6 installed.

So I then uninstalled Visual Studio 2022 preview.

Now, when I type dotnet --version (or other command like dotnet --info) in a command window, I get the following message:

Found .NET SDK, but did not find dotnet.dll at [C:\Program Files\dotnet\sdk\6.0.100-preview.7.21379.14\dotnet.dll]

I have tried to repair, and then reinstall DotNet SDK 5.0.400. Restarted machine a few times as well, to no avail.

I am guessing the uninstaller removed the files, but failed to restore the registry to the previous version.

How do I fix this?

答:
I also ran into the same problem recently. I had to go to the below path in Windows and delete all 6.*.* folders.

```<code>C:\Program Files\dotnet
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I also ran into the same problem recently. I had to go to the below path in Windows and delete all 6.*.* folders.

C:\Program Files\dotnet


答:
You can use the sort_array function. refer to here

```<code>df.groupBy($"name")
  .agg(sort_array(collect_list(struct($"food", $"price"))).as("foods"))
  .show(false)
</code>```

Title: How to sort a struct array in a spark dataframe?

Body:
I have the following code and output from Aggregating multiple columns with custom function in Spark.

import org.apache.spark.sql.functions.{collect_list, struct}
import sqlContext.implicits._

val df = Seq(
  ("john", "tomato", 1.99),
  ("john", "carrot", 0.45),
  ("bill", "apple", 0.99),
  ("john", "banana", 1.29),
  ("bill", "taco", 2.59)
).toDF("name", "food", "price")

df.groupBy($"name")
  .agg(collect_list(struct($"food", $"price")).as("foods"))
  .show(false)

df.printSchema

Output and Schema:

+----+---------------------------------------------+
|name|foods                                        |
+----+---------------------------------------------+
|john|[[tomato,1.99], [carrot,0.45], [banana,1.29]]|
|bill|[[apple,0.99], [taco,2.59]]                  |
+----+---------------------------------------------+

root
 |-- name: string (nullable = true)
 |-- foods: array (nullable = false)
 |    |-- element: struct (containsNull = false)
 |    |    |-- food: string (nullable = true)
 |    |    |-- price: double (nullable = false)

I want to sort based on df("foods.food"). How do I sort this to get the output below?

+----+---------------------------------------------+
|name|foods                                        |
+----+---------------------------------------------+
|john|[[banana,1.29], [carrot,0.45], [tomato,1.99]]|
|bill|[[apple,0.99], [taco,2.59]]                  |
+----+---------------------------------------------+

Edit: I want to be able to choose which attribute to sort on. For example, if I want to sort on the price, I want an output like this:

+----+---------------------------------------------+
|name|foods                                        |
+----+---------------------------------------------+
|john|[[carrot,0.45], [banana,1.29], [tomato,1.99]]|
|bill|[[apple,0.99], [taco,2.59]]                  |
+----+---------------------------------------------+

Body:
You can use the sort_array function. refer to here

df.groupBy($"name")
  .agg(sort_array(collect_list(struct($"food", $"price"))).as("foods"))
  .show(false)


问:
How to access state from a component in React - TypeScript?
How can I access my state from the component GamePieceSquares since GamePieceSquares is declared before the state is created?

Here is the code:

```<code>const GamePieceSquares = ({text, id} : {text:any, id:any}) => (
  <View style={styles.gamePieceSquares}>
    <Text style={styles.text} onPress={() => {console.log('You tapped the button!: ' + text);}}>{text}</Text>
  </View>
);

export default function TabTwoScreen() {

  const [pieceSelectedID, setPieceSelectedID] = useState(0);

  return (
        <Card containerStyle={styles.container}>
            <Card.Title>CARD WITH DIVIDER</Card.Title>
            <View style={styles.gamePiecesRow}>
              <GamePieceSquares text="B" /><Text>{"\n"}</Text>
              <GamePieceSquares text="D" /><Text>{"\n"}</Text>
              <GamePieceSquares text="F" /><Text>{"\n"}</Text>
              <GamePieceSquares text="G" /><Text>{"\n"}</Text>
              <GamePieceSquares text="I" /><Text>{"\n"}</Text>
              <GamePieceSquares text="O" /><Text>{"\n"}</Text>
              <GamePieceSquares text="P" /><Text>{"\n"}</Text>
              <GamePieceSquares text="L" /><Text>{"\n"}</Text>
            </View>
            <Card.Divider />
        </Card>
      <View style={styles.container}><Text >Keyboard</Text></View>
  </View>
  );
}
</code>```

Currently, when I click any of the GamePieceSquares, the text value of the component gets printed to the console.

My goal is this: when the GamePieceSquares get clicked, then set the pieceSelectedID to be the value of the id of the GamePieceSquares and then highlight the GamePieceSquare.

Long story short, I wanted to access the state so that I can correctly highlight the GamePieceSquare that was last clicked.

答:
The answer:

A react component's state is private, not accessible outside of itself, the way you can "inform" parent that there was a state change by passing a function, you can review the docs for reference.

Therefore, to achieve what you ask, you should have something like this:

```<code>
\\ Notice I am adding two properties,
\\ onClick -> a function to be executed when the text is pressed
\\ isSelected -> a boolean to indicate when the GamePieceSquare is selected

const GamePieceSquares = ({text, id, onClick, isSelected} : {text:any, id:any, onClick: (event) => void}, isSelected: boolean) => (
    <View style={styles.gamePieceSquares}>
      <Text style={styles.text} onPress={onClick}>{text}</Text>
    </View>
);

export default function TabTwoScreen() {

    \\ link to hooks at the bottom
    const [selectedSquareId, setSelectedSquareId] = useState(null)

    \\ internal function to execute when a GamePieceSquare is clicked on
    const _onClick = (event) => {
        \\ how to determine if something was selected with the event or
HINT: the id
    };

    return (
        <Card containerStyle={styles.container}>
            <Card.Title>CARD WITH DIVIDER</Card.Title>
            <View style={styles.gamePiecesRow}>
                { // Notice I am providing both properties here }
                <GamePieceSquares
                    text="L"
                    onClick={_onClick}
                    isSelected={
                        \\ You need to figure out how to determine if a square is selected
                    }
                />
                <Text>{"\n"}</Text>
            </View>
            <Card.Divider />
        </Card>
        <View style={styles.container}><Text >Keyboard</Text></View>
    );
}
</code>```

Some concepts that will help a lot with this are:

State hook

Again this doc

Not directly related but very important

Body:
How can I access my state from the component GamePieceSquares since GamePieceSquares is declared before the state is created?

Here is the code:

const GamePieceSquares = ({text, id} : {text:any, id:any}) => (
  <View style={styles.gamePieceSquares}>
    <Text style={styles.text} onPress={() => {console.log('You tapped the button!: ' + text);}}>{text}</Text>
  </View>
);

export default function TabTwoScreen() {

  const [pieceSelectedID, setPieceSelectedID] = useState(0);

  return (
        <Card containerStyle={styles.container}>
            <Card.Title>CARD WITH DIVIDER</Card.Title>
            <View style={styles.gamePiecesRow}>
              <GamePieceSquares text="B" /><Text>{"\n"}</Text>
              <GamePieceSquares text="D" /><Text>{"\n"}</Text>
              <GamePieceSquares text="F" /><Text>{"\n"}</Text>
              <GamePieceSquares text="G" /><Text>{"\n"}</Text>
              <GamePieceSquares text="I" /><Text>{"\n"}</Text>
              <GamePieceSquares text="O" /><Text>{"\n"}</Text>
              <GamePieceSquares text="P" /><Text>{"\n"}</Text>
              <GamePieceSquares text="L" /><Text>{"\n"}</Text>
            </View>
            <Card.Divider />
        </Card>
      <View style={styles.container}><Text >Keyboard</Text></View>
  </View>
  );
}

Currently, when I click any of the GamePieceSquares, the text value of the component gets printed to the console.

My goal is this: when the GamePieceSquares get clicked, then set the pieceSelectedID to be the value of the id of the GamePieceSquares and then highlight the GamePieceSquare.

Long story short, I wanted to access the state so that I can correctly highlight the GamePieceSquare that was last clicked.

Body:
The answer:

A react component's state is private, not accessible outside of itself, the way you can "inform" parent that there was a state change by passing a function, you can review the docs for reference.

Therefore, to achieve what you ask, you should have something like this:

\\ Notice I am adding two properties,
\\ onClick -> a function to be executed when the text is pressed
\\ isSelected -> a boolean to indicate when the GamePieceSquare is selected

const GamePieceSquares = ({text, id, onClick, isSelected} : {text:any, id:any, onClick: (event) => void}, isSelected: boolean) => (
    <View style={styles.gamePieceSquares}>
      <Text style={styles.text} onPress={onClick}>{text}</Text>
    </View>
);

export default function TabTwoScreen() {

    \\ link to hooks at the bottom
    const [selectedSquareId, setSelectedSquareId] = useState(null)

    \\ internal function to execute when a GamePieceSquare is clicked on
    const _onClick = (event) => {
        \\ how to determine if something was selected with the event or
HINT: the id
    };

    return (
        <Card containerStyle={styles.container}>
            <Card.Title>CARD WITH DIVIDER</Card.Title>
            <View style={styles.gamePiecesRow}>
                { // Notice I am providing both properties here }
                <GamePieceSquares
                    text="L"
                    onClick={_onClick}
                    isSelected={
                        \\ You need to figure out how to determine if a square is selected
                    }
                />
                <Text>{"\n"}</Text>
            </View>
            <Card.Divider />
        </Card>
        <View style={styles.container}><Text >Keyboard</Text></View>
    );
}

Some concepts that will help a lot with this are:

State hook

Again this doc

Not directly related but very important


问:
Spring @Value FileNotFound when running on azure pipeline
In my spring project I have a unit test like this:

@ExtendWith(SpringExtension.class)
@WebMvcTest(BuildingController.class)
class BuildingControllerTest {

    @Value("classpath:building/CreateBuildingRequest.json")
    Resource createBuildingRequest;
...
}
```
<p>I load a test input file using @value annotation, and running <code>mvn clean verify</code> run the test case successfully on my IDE.</p>
<p>But when I run the test case in azure pipeline I get fileNotFoundException, saying file does not exist<img src="https://i.stack.imgur.com/LM7Ow.png" alt="enter image description here" /></p>
<p>Here is my azure-pipelines.yaml</p>
<pre class="lang-xml prettyprint-override"><code>trigger:
  - main

pool:
  vmImage: ubuntu-latest

steps:
  - task: Maven@3
    displayName: 'Package Maven'
    inputs:
      mavenPomFile: 'pom.xml'
      goals: 'verify'
</code>```

Observation: replacing @value with

Resource createBuildingRequest = new ClassPathResource("Building/CreateBuildingRequest.json");
```
<p>also produce the same problem
BUT, if load like this:</p>
<pre class="lang-java prettyprint-override"><code>    public static InputStream loadFileAsStream(String path){
        return Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
    }
</code>```

Work on both IDE and azure pipeline,

Why?

答:
I just change my test file folder name from "Building" to building and it works

However, when I had the folder as "Building", and I changed @value to @Value("classpath:Building/CreateBuildingRequest.json") it didn't work.

Leaving this post up to document this problem.

Body:
In my spring project I have a unit test like this:

@ExtendWith(SpringExtension.class)
@WebMvcTest(BuildingController.class)
class BuildingControllerTest {

    @Value("classpath:building/CreateBuildingRequest.json")
    Resource createBuildingRequest;
...
}

I load a test input file using @value annotation, and running mvn clean verify run the test case successfully on my IDE.

But when I run the test case in azure pipeline I get fileNotFoundException, saying file does not exist

Here is my azure-pipelines.yaml

trigger:
  - main

pool:
  vmImage: ubuntu-latest

steps:
  - task: Maven@3
    displayName: 'Package Maven'
    inputs:
      mavenPomFile: 'pom.xml'
      goals: 'verify'

Observation: replacing @value with

Resource createBuildingRequest = new ClassPathResource("Building/CreateBuildingRequest.json");

also produce the same problem
BUT, if load like this:

    public static InputStream loadFileAsStream(String path){
        return Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
    }

Work on both IDE and azure pipeline,

Why?


问:
How can unrar a file with python
How can I extract a .zip or .rar file using Python?

答:
This method only requires having 7zip installed.

Works flawlessly on every system 7zip does.

No python packages needed at all.

```<code>import subprocess
subprocess.run('7z x -oOutdir archive.rar')
</code>```

The subprocess module is comes with python.

Title: How can unrar a file with python

Body:
This method only requires having 7zip installed.

Works flawlessly on every system 7zip does.

No python packages needed at all.

import subprocess
subprocess.run('7z x -oOutdir archive.rar')

The subprocess module is comes with python.


问:
How to re-export global.d.ts typings for a third-party javascript project?
Although I can create typings that allow my typescript modules to consume function definitions from a third-party javascript module, this seems to create problems in turn for packages importing my module.

I populated a global.d.ts file to add the following typings for my typescript project since pouchdb-collate is a pure javascript project with no @types package...

// global.d.ts
declare module "pouchdb-collate" {
  export function toIndexableString(item: any): string;
  export function parseIndexableString(indexableString: string): any;
}
```
<p>This works well in my monorepo within project A which uses pouchdb-collate and has the <code>global.d.ts</code> in its <code>src/</code>. However, whenever I import project A into project B in monorepo, the typings of pouchdb-collate are then unavailable to the project B, which results in an error like...</p>
```    ../collate/src/index.ts:4:8 - error TS7016: Could not find a declaration file for module 'pouchdb-collate'. '/project/blabla/node_modules/.pnpm/pouchdb-collate@7.2.2/node_modules/pouchdb-collate/lib/index.js' implicitly has an 'any' type.
      Try `npm i --save-dev @types/pouchdb-collate` if it exists or add a new declaration (.d.ts) file containing `declare module 'pouchdb-collate';`
```
<p>That is even though there is already a global.d.ts file in the <code>collate/src</code> folder containing exactly that syntax, and which provided the correct types when running scripts from within the folder!</p>
<p>I can only fix this by placing another copy of <code>global.d.ts</code> in project B as well.</p>
<p>As an alternative I have tried to create a package C within the monorepo that contains a <code>global.d.ts</code> and reexports the symbols from <code>pouchdb-collate</code> via an <code>index.ts</code> file like...</p>
<pre class="lang-js prettyprint-override"><code>// modules/collate/src/index.ts
export { parseIndexableString, toIndexableString } from "pouchdb-collate";
</code>```

The benefit of this approach (aliasing via a package) would be to eventually replace those functions with versions vendored in, rewritten and tested in typescript. However, this approach suffers from the same issue.

What is the way for package C to re-export the symbols AND suitable typings for this third-party package so that projects importing package C can consume them?

答:
For my case I succeeded at re-exporting the third-party module with typings as below.

First I created a new module in my monorepo called @blabla/collate that imported and re-exported in pure javascript like...

// src/index.js
module.exports = require("pouchdb-collate");
```
<p>Next to it I placed a file called <code>index.d.ts</code> declaring types for my new package...</p>
<pre class="lang-js prettyprint-override"><code>// src/index.d.ts
declare module "@blabla/collate" {
  export function toIndexableString(item: any): string;
  export function parseIndexableString(indexableString: string): any;
}
</code>```

As recommended by the typescript docs, I then added values to the package.json of @blabla/collate as follows...

  "main": "src/index.js",
  "types": "src/index.d.ts",
```

So this doesn't directly type the pouchdb-collate package, but it does re-export via normal javascript mechanisms, then exports declarations for the new javascript source file.

Feels like there should be a more elegant approach so I won't mark this as the answer yet in case anyone has a contribution to make.

Body:
Although I can create typings that allow my typescript modules to consume function definitions from a third-party javascript module, this seems to create problems in turn for packages importing my module.

I populated a global.d.ts file to add the following typings for my typescript project since pouchdb-collate is a pure javascript project with no @types package...

// global.d.ts
declare module "pouchdb-collate" {
  export function toIndexableString(item: any): string;
  export function parseIndexableString(indexableString: string): any;
}

This works well in my monorepo within project A which uses pouchdb-collate and has the global.d.ts in its src/. However, whenever I import project A into project B in monorepo, the typings of pouchdb-collate are then unavailable to the project B, which results in an error like...

    ../collate/src/index.ts:4:8 - error TS7016: Could not find a declaration file for module 'pouchdb-collate'. '/project/blabla/node_modules/.pnpm/pouchdb-collate@7.2.2/node_modules/pouchdb-collate/lib/index.js' implicitly has an 'any' type.
      Try `npm i --save-dev @types/pouchdb-collate` if it exists or add a new declaration (.d.ts) file containing `declare module 'pouchdb-collate';`

That is even though there is already a global.d.ts file in the collate/src folder containing exactly that syntax, and which provided the correct types when running scripts from within the folder!

I can only fix this by placing another copy of global.d.ts in project B as well.

As an alternative I have tried to create a package C within the monorepo that contains a global.d.ts and reexports the symbols from pouchdb-collate via an index.ts file like...

// modules/collate/src/index.ts
export { parseIndexableString, toIndexableString } from "pouchdb-collate";

The benefit of this approach (aliasing via a package) would be to eventually replace those functions with versions vendored in, rewritten and tested in typescript. However, this approach suffers from the same issue.

What is the way for package C to re-export the symbols AND suitable typings for this third-party package so that projects importing package C can consume them?

Body:
For my case I succeeded at re-exporting the third-party module with typings as below.

First I created a new module in my monorepo called @blabla/collate that imported and re-exported in pure javascript like...

// src/index.js
module.exports = require("pouchdb-collate");

Next to it I placed a file called index.d.ts declaring types for my new package...

// src/index.d.ts
declare module "@blabla/collate" {
  export function toIndexableString(item: any): string;
  export function parseIndexableString(indexableString: string): any;
}

As recommended by the typescript docs, I then added values to the package.json of @blabla/collate as follows...

  "main": "src/index.js",
  "types": "src/index.d.ts",

So this doesn't directly type the pouchdb-collate package, but it does re-export via normal javascript mechanisms, then exports declarations for the new javascript source file.

Feels like there should be a more elegant approach so I won't mark this as the answer yet in case anyone has a contribution to make.


问:
How do I delete an Eclipse perspective for a plugin I uninstalled?
I was evaluating the Enterprise IDE plugin for Eclipse, and ultimately decided not to purchase it.  After I uninstalled the plugin, I was left with a bunch of perspective buttons (the ones in the far upper-right-hand corner) which I can't remove.  How do I get rid of the manually, without nuking my workspace?

Edit: To be clear, right-clicking and going to "close" does nothing.  Not even an error message.

答: <your workspace folder>/.metadata/.plugins/org.eclipse.ui.workbench/workbench.xml contains a <perspectives> element with <perspective> child elements.  You can delete <perspective> elements and they will no longer appear in the toolbar.  Eclipse writes to this file when it exits so your changes will be overwritten if you don't quit Eclipse first.</p>

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Training Yolact on Google Colab+ without timing out
I want to train Yolact on a custom dataset using Google Colab+.
Is it possible to train on Colab+ or does it time out to easily?
Thank you!</p>

答:
Yes, you can train your model on Colab+. The problem is that Colab has a relatively short lifecycle compared with other cloud platforms such as AWS SageMaker or Google Cloud. I run the code below to extend a bit more such time.</p>
```<code>%%javascript
function ClickConnect(){
console.log("Working");
document.querySelector("colab-toolbar-button#connect").click()
}setInterval(ClickConnect,50000)
</code>```

Body:
Yes, you can train your model on Colab+. The problem is that Colab has a relatively short lifecycle compared with other cloud platforms such as AWS SageMaker or Google Cloud. I run the code below to extend a bit more such time.

%%javascript
function ClickConnect(){
console.log("Working");
document.querySelector("colab-toolbar-button#connect").click()
}setInterval(ClickConnect,50000)


问:
Stripping the leading zeros but leave a single 0
So let me start of by saying that I'm new to bash so I would appreciate a simple explanation on the answers you give.

I've got the following block of code:

name="Chapter 0000 (sub s2).cbz "

s=$(echo $name | grep -Eo '[0-9]+([.][0-9]+)?' | tr '\n' ' ' | sed 's/^0*//')

echo $s

readarray -d " " -t myarr <<< "$s"

if [[ $(echo "${myarr[0]} < 100 && ${myarr[0]} >= 10" | bc) -ne 0 ]]; then
    myarr[0]="0${myarr[0]}"
elif [[ $(echo "${myarr[0]} < 10" | bc) -ne 0 ]]; then
    myarr[0]="00${myarr[0]}"
fi

newName="Chapter ${myarr[0]}.cbz"

echo $newName
```
<p>which (in this case) would end up spitting out:</p>
``` 2
(standard_in) 1: syntax error
(standard_in) 1: syntax error
Chapter .cbz
```
<p>(I'm fairly certain that the syntax errors are because <code>${myarr[0]}</code> is null when doing the comparisons)</p>
<p>This is not the output I want. I want the code to strip leading 0's but leave a single 0 if its all 0.</p>
<p>So the code to really change would be <code>sed 's/^0*//')</code> but I'm not sure how to change it.</p>
<p>(expected outputs:</p>
```              in   --->   out
1) chapter 8.cbz   ---> Chapter 008.cbz
2) chapter 1.3.cbz   ---> Chapter 001.3.cbz
3) _23 (sec 2).cbz   ---> Chapter 023.cbz
4) chapter 00009.cbz   ---> Chapter 009.cbz
5) chap 0000112.5.cbz   ---> Chapter 112.5.cbz
6) Chapter 0000 (sub s2).cbz   ---> Chapter 000.cbz
```

so far the code I got works for 1- 3 but not the leading 0 cases (4-6))

答:
I think you could implement the table of results by sed alone:

```<code>sed '
    s/^[^0-9]*/000/
    s/[^0-9.].*$//
    s/\.*$/.cbz/
    s/^0*\([0-9]\{3\}\)/Chapter \1/
' <<'EOD'
chapter 8.cbz
chapter 1.3.cbz
_23 (sec 2).cbz
chapter 00009.cbz
chap 0000112.5.cbz
chap 04567.cbz
EOD
</code>```

The first command strips everything before the first number and prepends zeros to ensure there are at least three digits.

The second command strips off everything after the number. (This may leave a trailing period that is not part of the number as the code defines a number to be any sequence of digits and periods).

The third command deletes any trailing periods and adds the desired suffix.

The final command removes the longest run of leading zeroes that leaves (at least) three digits (I added an extra test case to demonstrate) and adds the desired prefix.

Result of running this would be:

```<code>Chapter 008.cbz
Chapter 001.3.cbz
Chapter 023.cbz
Chapter 009.cbz
Chapter 112.5.cbz
Chapter 4567.cbz
</code>```

Body:
So let me start of by saying that I'm new to bash so I would appreciate a simple explanation on the answers you give.

I've got the following block of code:

name="Chapter 0000 (sub s2).cbz "

s=$(echo $name | grep -Eo '[0-9]+([.][0-9]+)?' | tr '\n' ' ' | sed 's/^0*//')

echo $s

readarray -d " " -t myarr <<< "$s"

if [[ $(echo "${myarr[0]} < 100 && ${myarr[0]} >= 10" | bc) -ne 0 ]]; then
    myarr[0]="0${myarr[0]}"
elif [[ $(echo "${myarr[0]} < 10" | bc) -ne 0 ]]; then
    myarr[0]="00${myarr[0]}"
fi

newName="Chapter ${myarr[0]}.cbz"

echo $newName

which (in this case) would end up spitting out:

 2
(standard_in) 1: syntax error
(standard_in) 1: syntax error
Chapter .cbz

(I'm fairly certain that the syntax errors are because ${myarr[0]} is null when doing the comparisons)

This is not the output I want. I want the code to strip leading 0's but leave a single 0 if its all 0.

So the code to really change would be sed 's/^0*//') but I'm not sure how to change it.

(expected outputs:

              in   --->   out
1) chapter 8.cbz   ---> Chapter 008.cbz
2) chapter 1.3.cbz   ---> Chapter 001.3.cbz
3) _23 (sec 2).cbz   ---> Chapter 023.cbz
4) chapter 00009.cbz   ---> Chapter 009.cbz
5) chap 0000112.5.cbz   ---> Chapter 112.5.cbz
6) Chapter 0000 (sub s2).cbz   ---> Chapter 000.cbz

so far the code I got works for 1- 3 but not the leading 0 cases (4-6))

Body:
I think you could implement the table of results by sed alone:

sed '
    s/^[^0-9]*/000/
    s/[^0-9.].*$//
    s/\.*$/.cbz/
    s/^0*\([0-9]\{3\}\)/Chapter \1/
' <<'EOD'
chapter 8.cbz
chapter 1.3.cbz
_23 (sec 2).cbz
chapter 00009.cbz
chap 0000112.5.cbz
chap 04567.cbz
EOD

The first command strips everything before the first number and prepends zeros to ensure there are at least three digits.

The second command strips off everything after the number. (This may leave a trailing period that is not part of the number as the code defines a number to be any sequence of digits and periods).

The third command deletes any trailing periods and adds the desired suffix.

The final command removes the longest run of leading zeroes that leaves (at least) three digits (I added an extra test case to demonstrate) and adds the desired prefix.

Result of running this would be:

Chapter 008.cbz
Chapter 001.3.cbz
Chapter 023.cbz
Chapter 009.cbz
Chapter 112.5.cbz
Chapter 4567.cbz


问:
os.environ doesn't show some variables
I have an environment variable that I set (on Centos 6) using profile.d, as follows:

```<code>[bankap@tnt-integration-test ~]$ cat /etc/profile.d/tnt.sh
TNT_SERVER_URL=http://tnt-integration-test:8000/
</code>```

and when I log in, I see the variable:

```<code>[bankap@tnt-integration-test ~]$ echo $TNT_SERVER_URL
http://tnt-integration-test:8000/
</code>```

But when I access the thing with Python, the environment variable doesn't show up!

```<code>[bankap@tnt-integration-test ~]$ python -c 'import os;os.environ.get("TNT_SERVER_URL")'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
NameError: name 'TNT_SERVER_URL' is not defined
</code>```

I've even tried using the ctypes library with the same results:

```<code>>>> os.getenv('TNT_SERVER_URL')
>>> from ctypes import CDLL, c_char_p
>>> getenv = CDLL('libc.so.6').getenv
>>> getenv('TNT_SERVER_URL')
0
>>>
</code>```

But other variables come through just fine...

os.environ
         {'SSH_ASKPASS': '/usr/libexec/openssh/gnome-ssh-askpass', 'LESSOPEN': '|/usr/bin/lesspipe.sh %s', 'SSH_CLIENT': '139.126.176.137 56535 22', 'SELINUX_USE_CURRENT_RANGE': '', 'LOGNAME': 'bankap', 'USER': 'bankap', 'QTDIR': '/usr/lib64/qt-3.3', 'PATH': '/usr/lib64/qt-3.3/bin:/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/home/bankap/bin',

Anybody have any ideas? I've never seen this before!

答:
You have a quoting problem:

change

```<code>python -c 'import os;os.environ.get('TNT_SERVER_URL')'
</code>```

into

```<code>python -c 'import os;os.environ.get("TNT_SERVER_URL")'
                                    ^              ^
</code>```

You also (probably) need to export the variable:

```<code>export TNT_SERVER_URL; python -c 'import os;os.environ.get("TNT_SERVER_URL")'
</code>```

Title: os.environ doesn't show some variables

Body:
I have an environment variable that I set (on Centos 6) using profile.d, as follows:

[bankap@tnt-integration-test ~]$ cat /etc/profile.d/tnt.sh
TNT_SERVER_URL=http://tnt-integration-test:8000/

and when I log in, I see the variable:

[bankap@tnt-integration-test ~]$ echo $TNT_SERVER_URL
http://tnt-integration-test:8000/

But when I access the thing with Python, the environment variable doesn't show up!

[bankap@tnt-integration-test ~]$ python -c 'import os;os.environ.get("TNT_SERVER_URL")'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
NameError: name 'TNT_SERVER_URL' is not defined

I've even tried using the ctypes library with the same results:

>>> os.getenv('TNT_SERVER_URL')
>>> from ctypes import CDLL, c_char_p
>>> getenv = CDLL('libc.so.6').getenv
>>> getenv('TNT_SERVER_URL')
0
>>>

But other variables come through just fine...

os.environ
         {'SSH_ASKPASS': '/usr/libexec/openssh/gnome-ssh-askpass', 'LESSOPEN': '|/usr/bin/lesspipe.sh %s', 'SSH_CLIENT': '139.126.176.137 56535 22', 'SELINUX_USE_CURRENT_RANGE': '', 'LOGNAME': 'bankap', 'USER': 'bankap', 'QTDIR': '/usr/lib64/qt-3.3', 'PATH': '/usr/lib64/qt-3.3/bin:/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/home/bankap/bin',

Anybody have any ideas? I've never seen this before!

Body:
You have a quoting problem:

change

python -c 'import os;os.environ.get('TNT_SERVER_URL')'

into

python -c 'import os;os.environ.get("TNT_SERVER_URL")'
                                    ^              ^

You also (probably) need to export the variable:

export TNT_SERVER_URL; python -c 'import os;os.environ.get("TNT_SERVER_URL")'


问:
Python - adding pictures and commands behind dynamic buttons
I am quite new to python and RPi. I am trying to generate dynamic buttons based on a MySQL Query. I found this thread in the forum: How to create a self resizing grid of buttons in tkinter?

It was helpful to understand how to generate dynamic buttons in a grid. Nevertheless, I am having issues putting commands for each dynamic button and picture.

This is my code:

```<code>from __future__ import division
import tkinter  as tk
from tkinter import *

import MySQLdb
db = MySQLdb.connect("localhost", "User...", "SecurePW", "myCoolDB")
curs=db.cursor()

PhotoImageFolder='/home/pi/App/CocktailPic/'

root = Tk()
Grid.rowconfigure(root, 0, weight=1)
Grid.columnconfigure(root, 0, weight=1)

#Create & Configure frame
frame=Frame(root)
frame.grid(row=0, column=0, sticky=N+S+E+W)

curs.execute("SELECT * FROM `CockRec` WHERE `IsACTIVE`=1")

max_col_index=10
col_index=0
row_index=0

def CocktailBtnCmd(Cocktail_ID):
    messagebox.showinfo(title='Informatio', message=Cocktail_ID)
    #print("Cocktail ID: ",Cocktail_ID)

for entry in curs.fetchall():
    if col_index>=max_col_index:
        row_index=row_index+1
        col_index=0
    CocktailID=entry[0]
    Cocktail=entry[1]
    CocktailPicturePath=entry[3]
    btn_image=PhotoImage(file = PhotoImageFolder + CocktailPicturePath)
    photoImage = btn_image.subsample(10, 10)
    Grid.rowconfigure(frame, row_index, weight=1)
    Grid.columnconfigure(frame, col_index, weight=1)
    btn = Button(frame, text = Cocktail, image=photoImage, command = CocktailBtnCmd(CocktailID)) #create a button
    btn.grid(row=row_index, column=col_index, sticky=N+S+E+W)
    col_index=col_index+1
</code>```

The issue is, when I run the code, it shows the picture only on the last Button, and also the command behind the buttons does not work.

If I define the picture before the For LOOP, it works at least with all the same pictures on each button.

Any idea, what I am doing wrong?

答:
command=CocktailBtnCmd(CocktailID) will execute CocktailBtnCmd(...) immediately and assign the result (which is None) to command option.  That is why the button does not work later.

You need to use lambda using argument with default value instead:

```<code>command=lambda CocktailID=CocktailID: CocktailBtnCmd(CocktailID)
</code>```

For the image issue, it is because you have used same variable to hold the reference of the images in the for loop:

```<code>photoImage = btn_image.subsample(2, 2)
</code>```

So after the for loop, only the last image has reference to it and the previous ones will be garbage collected.

You can keep references of all the images using attribute of the related buttons:

for entry in curs.fetchall():
    ...
    photoImage = btn_image.subsample(2, 2)
    ...
    btn = Button(frame, text = Cocktail, image=photoImage, command=lambda: CocktailID=CocktailID: CocktailBtnCmd(CocktailID))
    btn.image = photoImage # use an attribute to keep the reference of image
    ...
```

Also I would recommend to use the official mysql.connector module instead of MySQLdb.

Body:
I am quite new to python and RPi. I am trying to generate dynamic buttons based on a MySQL Query. I found this thread in the forum: How to create a self resizing grid of buttons in tkinter?

It was helpful to understand how to generate dynamic buttons in a grid. Nevertheless, I am having issues putting commands for each dynamic button and picture.

This is my code:

from __future__ import division
import tkinter  as tk
from tkinter import *

import MySQLdb
db = MySQLdb.connect("localhost", "User...", "SecurePW", "myCoolDB")
curs=db.cursor()

PhotoImageFolder='/home/pi/App/CocktailPic/'

root = Tk()
Grid.rowconfigure(root, 0, weight=1)
Grid.columnconfigure(root, 0, weight=1)

#Create & Configure frame
frame=Frame(root)
frame.grid(row=0, column=0, sticky=N+S+E+W)

curs.execute("SELECT * FROM `CockRec` WHERE `IsACTIVE`=1")

max_col_index=10
col_index=0
row_index=0

def CocktailBtnCmd(Cocktail_ID):
    messagebox.showinfo(title='Informatio', message=Cocktail_ID)
    #print("Cocktail ID: ",Cocktail_ID)

for entry in curs.fetchall():
    if col_index>=max_col_index:
        row_index=row_index+1
        col_index=0
    CocktailID=entry[0]
    Cocktail=entry[1]
    CocktailPicturePath=entry[3]
    btn_image=PhotoImage(file = PhotoImageFolder + CocktailPicturePath)
    photoImage = btn_image.subsample(10, 10)
    Grid.rowconfigure(frame, row_index, weight=1)
    Grid.columnconfigure(frame, col_index, weight=1)
    btn = Button(frame, text = Cocktail, image=photoImage, command = CocktailBtnCmd(CocktailID)) #create a button
    btn.grid(row=row_index, column=col_index, sticky=N+S+E+W)
    col_index=col_index+1

The issue is, when I run the code, it shows the picture only on the last Button, and also the command behind the buttons does not work.

If I define the picture before the For LOOP, it works at least with all the same pictures on each button.

Any idea, what I am doing wrong?

Body:
command=CocktailBtnCmd(CocktailID) will execute CocktailBtnCmd(...) immediately and assign the result (which is None) to command option.  That is why the button does not work later.

You need to use lambda using argument with default value instead:

command=lambda CocktailID=CocktailID: CocktailBtnCmd(CocktailID)

For the image issue, it is because you have used same variable to hold the reference of the images in the for loop:

photoImage = btn_image.subsample(2, 2)

So after the for loop, only the last image has reference to it and the previous ones will be garbage collected.

You can keep references of all the images using attribute of the related buttons:

for entry in curs.fetchall():
    ...
    photoImage = btn_image.subsample(2, 2)
    ...
    btn = Button(frame, text = Cocktail, image=photoImage, command=lambda: CocktailID=CocktailID: CocktailBtnCmd(CocktailID))
    btn.image = photoImage # use an attribute to keep the reference of image
    ...

Also I would recommend to use the official mysql.connector module instead of MySQLdb.


问:
Flutter video player seekTo beginning of a video, takes time to play again in Android, works as expected in iOS
I'm developing a video app, using video_player package. I want to repeat the videos n times. I'm doing this by adding listener and when video reaches the end, if the current repetition is not equal to the N, I simply call the _videoPlayerController.seekTo(Duration.zero), it works as expected in iOS, but in Android it takes some time to play it again, because of the buffer I guess. I have some logs. When I call the seekTo, first log is:

D/AudioTrack(26148): stop(59): called with 194560 frames delivered

After some time(3-4 seconds) the other logs come and video plays after these logs:

D/AudioTrack(26148): getTimestamp_l(60): device stall time corrected using current time 21442303047753
D/AudioTrack(26148): getTimestamp_l(60): stale timestamp time corrected, currentTimeNanos: 21440694441753 < limitNs: 21442169902753 < mStartNs: 21442230902753
W/AudioTrack(26148): getTimestamp_l(60): retrograde timestamp time corrected, 21442169902753 < 21442303047753

I'm not sure the problem in here is the buffering but if so, is there anyway to prevent buffering while using seekTo in android or is there any other way to achieve this functionality?

答:
I'm thinking this problem come from the initial thread so if you call your first seek initial code in did dependencies method or you can try to wrap initial code to addpostframe call back with binding.

```<code> WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
    _playController(index: 0, durationInSeconds: 5);
  });
</code>```

or try to call didChangeDepencies after the initState initialize.

```<code>  @override
  void didChangeDependencies() {
  super.didChangeDependencies();
  }
</code>```

Body:
I'm thinking this problem come from the initial thread so if you call your first seek initial code in did dependencies method or you can try to wrap initial code to addpostframe call back with binding.

 WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
    _playController(index: 0, durationInSeconds: 5);
  });

or try to call didChangeDepencies after the initState initialize.

  @override
  void didChangeDependencies() {
  super.didChangeDependencies();
  }


问:
how to dismiss dropdown when click outside?
i am learning react+typescript. i want to implement a control like fluentui dropdown:

basically I draw a div and set its position 'relative' then use absolute layout on the dropdown panel. but there is a problem:

how to dismiss the dropdown when click outside area?

Can you share good practices?

答:
Let's assume dropdown is dom node of your dropdown area
and dismissDropdown function to dismiss it.
Then your code could look like this:

window.addEventListener("click", function (e) {
    // if outside of dropdown
    if (!dropdown.contains(e.target)) {
        dismissDropdown()
    }
});
```

contains: https://developer.mozilla.org/en-US/docs/Web/API/Node/contains

Basically we check if element on which user clicked is inside dropdown or dropdown itself, and if not then dismiss it.

Body:
Let's assume dropdown is dom node of your dropdown area
and dismissDropdown function to dismiss it.
Then your code could look like this:

window.addEventListener("click", function (e) {
    // if outside of dropdown
    if (!dropdown.contains(e.target)) {
        dismissDropdown()
    }
});

contains: https://developer.mozilla.org/en-US/docs/Web/API/Node/contains

Basically we check if element on which user clicked is inside dropdown or dropdown itself, and if not then dismiss it.


问:
gcloud auth login throwing error: gcloud crashed (ConnectionError): HTTPSConnectionPool(host='oauth2.googleapis.com', port=443): Max retries exceeded

gcloud builds submit failed for me yesterday.

Then I tried gcloud config set project, that also failed.

So I thought login might have expired so tried gcloud auth login.

In all cases, it always throws following error:

```<code>ERROR: gcloud crashed (ConnectionError): HTTPSConnectionPool(host='oauth2.googleapis.com', port=443): Max retries exceeded with url: /token (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x00000198B0B26970>: Failed to establish a new connection: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond'))

If you would like to report this issue, please run the following command:
  gcloud feedback

To check gcloud for common problems, please run the following command:
  gcloud info --run-diagnostics
</code>```

On running diagnostics as suggested, everything seems fine.

```<code>>  gcloud info --run-diagnostics
Network diagnostic detects and fixes local network connection issues.
Checking network connection...done.
Reachability Check passed.
Network diagnostic passed (1/1 checks passed).

Property diagnostic detects issues that may be caused by properties.
Checking hidden properties...done.
Hidden Property Check passed.
Property diagnostic passed (1/1 checks passed).
</code>```

I have also tried with my other google account, threw same error. It was working fine 1 day before. Have tried all Stackoverflow solutions, nothing seems to work.

答: This problem is with Airtel India ISP and not Google Cloud CLI. Use a VPN, and it will work.</p>

Body:
gcloud builds submit failed for me yesterday.

Then I tried gcloud config set project, that also failed.

So I thought login might have expired so tried gcloud auth login.

In all cases, it always throws following error:

ERROR: gcloud crashed (ConnectionError): HTTPSConnectionPool(host='oauth2.googleapis.com', port=443): Max retries exceeded with url: /token (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x00000198B0B26970>: Failed to establish a new connection: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond'))

If you would like to report this issue, please run the following command:
  gcloud feedback

To check gcloud for common problems, please run the following command:
  gcloud info --run-diagnostics

On running diagnostics as suggested, everything seems fine.

>  gcloud info --run-diagnostics
Network diagnostic detects and fixes local network connection issues.
Checking network connection...done.
Reachability Check passed.
Network diagnostic passed (1/1 checks passed).

Property diagnostic detects issues that may be caused by properties.
Checking hidden properties...done.
Hidden Property Check passed.
Property diagnostic passed (1/1 checks passed).

I have also tried with my other google account, threw same error. It was working fine 1 day before. Have tried all Stackoverflow solutions, nothing seems to work.


问:
Two C/C++ libraries calling each others extern functions
I'm trying to connect two c/c++ projects that depend on each other and this is how I'm doing so far.

Project A: I included some header files from project B. The project compiles into libA.so library.

project B: I included some headers files from project A and added the libA.so library. So this one can call extern functions from project A. The project compiles into libB.a library.

Then a user program adds libB.a library from project B and starts running the code.

The problem is I need to call some of the project B functions from project A. But project B is compiled after project A so I can't include libB.a. Both projects are large and use different build systems, So I can't compile them together.

Is there any way that I can call functions from project B? Or is there any better way to connect the two projects?

答:
When I read and understand your question, it seems that Projects A and B depend on each other, right? This structure is not good.

For overlapping functions, it is recommended to create a new library and refer to it in Projects A and B.


问:
How to remove canvas image on a onmouseout?
I am trying to change the image in canvas ID 'A' with mouseout on canvas ID 'e' I have been able to get the mousover to work and add a image to canvas 'A', but not remove it.</p>

```<code>    <script>
            function init() {
                setImageOne();
            }

            function setImageOne() { setImage('images/paul01.jpg'); }

            <!--function setImageTwo() { setImage('images/paul02.jpg'); }-->

            function unsetImageOne() { largeImage('images/full/cartoonPaul02.jpg'); }

            function setImageTwo() { largeImage('images/full/cartoonPaul01.jpg'); }

            function setImage(src) {
                var canvas = document.getElementById("l");
                var context = canvas.getContext("2d");
                if (context == null) return;
                var img = new Image();
                img.src = src;
                context.drawImage(img, 0, 0, 166, 276);
            }

            function largeImage(src){
                var canvas = document.getElementById("A");
                var context = canvas.getContext("2d");
                if (context == null) return;
                var img = new Image();
                img.src = src;
                context.drawImage(img, 0, 0, 300, 400);
            }
    </script>
        <div id="container">
            <header>
            <a href='../../'><h3>Everything else</h3></a>

</header>
        <div id="main" role="main">
        <body onload="init()">

            <div class="canvas">
                <canvas id="l" width="166" height="276" onmouseover="setImageTwo()" onmouseout="unsetImageOne()"></canvas>
            </div>

            <div class="canvas">
                <canvas id="A" width="300" height="400"></canvas>
            </div>
</code>```

答:
Removing something from a canvas is impossible in such that when you draw something, only pixels are saved. There is therefore no concept of an image anymore after drawing.

What you can do, however, is clearing the full canvas before drawing another image. This code might be appropriate for largeImage. The same goes for smallImage. I also advise you to use image.onload to make sure the image is only drawn when it is fully loaded.

```<code>function largeImage(src){
    var canvas = document.getElementById("A");
    var context = canvas.getContext("2d");
    var canvas2 = document.getElementById("l");
    var context2 = canvas.getContext("2d");
    if (context == null) return;
    var img = new Image();
    img.src = src;
    context2.clearRect(0, 0, 166, 276);
    img.onload = function() {
        context.drawImage(img, 0, 0, 300, 400);
    }
}
</code>```

Body:
I am trying to change the image in canvas ID 'A' with mouseout on canvas ID 'e' I have been able to get the mousover to work and add a image to canvas 'A', but not remove it.

Everything else

                <canvas id="l" width="166" height="276" onmouseover="setImageTwo()" onmouseout="unsetImageOne()"></canvas>

                <canvas id="A" width="300" height="400"></canvas>

Body:
Removing something from a canvas is impossible in such that when you draw something, only pixels are saved. There is therefore no concept of an image anymore after drawing.

What you can do, however, is clearing the full canvas before drawing another image. This code might be appropriate for largeImage. The same goes for smallImage. I also advise you to use image.onload to make sure the image is only drawn when it is fully loaded.

function largeImage(src){
    var canvas = document.getElementById("A");
    var context = canvas.getContext("2d");
    var canvas2 = document.getElementById("l");
    var context2 = canvas.getContext("2d");
    if (context == null) return;
    var img = new Image();
    img.src = src;
    context2.clearRect(0, 0, 166, 276);
    img.onload = function() {
        context.drawImage(img, 0, 0, 300, 400);
    }
}


问:
How to fix the error (TypeError: Cannot assign to read only property 'map' of object '#<QueryCursor>')
I am sending my data to MongoDB via Mongoose. Now, during the fetch of API route for it, an error is thrown.

Code

const addChoice = async (e) => {
    try {
        e.preventDefault();
        const res = await fetch("/api/sendChoice", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                choiceSeq: choice,
                checkSubmit: true,
            }),
        });
        console.log(res);
        router.push("/home");
    } catch (error) {
        console.log(error);
    }
};
```
<p>The error is happening at <code>const res = await fetch("/api/sendChoice" ,{</code></p>
<p>In terminal server the error</p>
<blockquote>
<p>error - TypeError: Cannot assign to read only property 'map' of object
'#<QueryCursor>'</p>
</blockquote>
<p>In the inspect element the error is as<br />
<img src="https://i.stack.imgur.com/15p7J.png" alt="this" /></p>
<p>I can't find anything related to fix this issue, I don't even understand what the error means to try to resolve it myself.</p>
<p>Some other related code from my project:</p>
<p>api/sendChoice</p>
<pre class="lang-js prettyprint-override"><code>import { getSession } from "next-auth/client";
import dbConnect from "../../helpers/dbConnect";
import Choice from "../../models/Choice";

export default async function sendChoice(req, res) {
    try {
        const session = await getSession({ req });
        await dbConnect();
        if (!session) {
            res.status(401).send("You are not signed in");
            return;
        }
        if (req.method === "POST") {
            console.log(req.body);
            const { choiceSeq, checkSubmit } = req.body;
            console.log(choiceSeq, checkSubmit);
            const userId = session.user.id;
            const nameP = session.user.name;
            const choice = new Choice({
                user: userId,
                name: nameP,
                choiceSeq,
                checkSubmit,
            });
            await choice.save();
            res.status(200).send("Choice saved");
        } else {
            res.status(400).send("Bad request");
        }
    }
    catch (error) {
        console.log(error);
    }
}
</code>```

The MongoDB schema

import mongoose, { Schema } from 'mongoose';

const ChoiceSchema = new Schema({
    user: {
        type: Schema.Types.ObjectId,
        ref: 'User',
    },
    name: {
        type: String,
    },
    choiceSeq: {
        type: Array,
        default: [],
    },
    checkSubmit: {
        type: Boolean,
    }
});

mongoose.models = {};

export default mongoose.model('Choice', ChoiceSchema);
```

答: In My case eslint 8.9.0 was the culprit. Rollback fixed it.</p>

Body:
I am sending my data to MongoDB via Mongoose. Now, during the fetch of API route for it, an error is thrown.

Code

const addChoice = async (e) => {
    try {
        e.preventDefault();
        const res = await fetch("/api/sendChoice", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                choiceSeq: choice,
                checkSubmit: true,
            }),
        });
        console.log(res);
        router.push("/home");
    } catch (error) {
        console.log(error);
    }
};

The error is happening at const res = await fetch("/api/sendChoice" ,{

In terminal server the error

error - TypeError: Cannot assign to read only property 'map' of object
'#<QueryCursor>'

In the inspect element the error is as

I can't find anything related to fix this issue, I don't even understand what the error means to try to resolve it myself.

Some other related code from my project:

api/sendChoice

import { getSession } from "next-auth/client";
import dbConnect from "../../helpers/dbConnect";
import Choice from "../../models/Choice";

export default async function sendChoice(req, res) {
    try {
        const session = await getSession({ req });
        await dbConnect();
        if (!session) {
            res.status(401).send("You are not signed in");
            return;
        }
        if (req.method === "POST") {
            console.log(req.body);
            const { choiceSeq, checkSubmit } = req.body;
            console.log(choiceSeq, checkSubmit);
            const userId = session.user.id;
            const nameP = session.user.name;
            const choice = new Choice({
                user: userId,
                name: nameP,
                choiceSeq,
                checkSubmit,
            });
            await choice.save();
            res.status(200).send("Choice saved");
        } else {
            res.status(400).send("Bad request");
        }
    }
    catch (error) {
        console.log(error);
    }
}

The MongoDB schema

import mongoose, { Schema } from 'mongoose';

const ChoiceSchema = new Schema({
    user: {
        type: Schema.Types.ObjectId,
        ref: 'User',
    },
    name: {
        type: String,
    },
    choiceSeq: {
        type: Array,
        default: [],
    },
    checkSubmit: {
        type: Boolean,
    }
});

mongoose.models = {};

export default mongoose.model('Choice', ChoiceSchema);


问:
How do I iterate through only the objects I have loaded into an array without iterating through the entire array?
I'm minoring in computer science at university, and need to write a program with three components:

A "Circle" class that defines methods for creating and working with a Circle object that has a radius and color as defined attributes in the object.

A "CircleMgr" class that manages an array of circle objects.

A "CircleApp" class that produces output for the program.

An issue I'm having (which is causing a runtime error) has been identified by my professor as lying inside the CircleApp class at line 53, which is a for loop iterating through the list--the code is as follows*:

```<code>for(int i = 0; i < mainList.length; i++){
        System.out.println("Circle " + i);
        System.out.println(mainList[i].getRadius());
        System.out.println(mainList[i].getColor());
    }
</code>```

Earlier in the program, I load the list created and managed by CircleMgr into mainList, which is contained in CircleApp. According to my professor, I need to iterate through only the objects that have been loaded into mainList (which will never be completely filled because we were told to create the object array at a size much larger than what the input file takes in). Unfortunately, I'm not certain how I could iterate through the array in a different manner; is anyone able to provide guidance to this effect?

*(the println statements are there to ensure that the output is correct before I format it, once I am able to move past the runtime error and actually produce output).

答:
If your array can never be full, then you can stop iterating when you reach a null item.

```<code>for(int i = 0; mainList[i] != null; i++){
    System.out.println("Circle " + i);
    System.out.println(mainList[i].getRadius());
    System.out.println(mainList[i].getColor());
}
</code>```

Later in your studies, you will learn about Lists, which can grow and shrink with your data.

Body:
I'm minoring in computer science at university, and need to write a program with three components:

A "Circle" class that defines methods for creating and working with a Circle object that has a radius and color as defined attributes in the object.

A "CircleMgr" class that manages an array of circle objects.

A "CircleApp" class that produces output for the program.

An issue I'm having (which is causing a runtime error) has been identified by my professor as lying inside the CircleApp class at line 53, which is a for loop iterating through the list--the code is as follows*:

for(int i = 0; i < mainList.length; i++){
        System.out.println("Circle " + i);
        System.out.println(mainList[i].getRadius());
        System.out.println(mainList[i].getColor());
    }

Earlier in the program, I load the list created and managed by CircleMgr into mainList, which is contained in CircleApp. According to my professor, I need to iterate through only the objects that have been loaded into mainList (which will never be completely filled because we were told to create the object array at a size much larger than what the input file takes in). Unfortunately, I'm not certain how I could iterate through the array in a different manner; is anyone able to provide guidance to this effect?

*(the println statements are there to ensure that the output is correct before I format it, once I am able to move past the runtime error and actually produce output).

Body:
If your array can never be full, then you can stop iterating when you reach a null item.

for(int i = 0; mainList[i] != null; i++){
    System.out.println("Circle " + i);
    System.out.println(mainList[i].getRadius());
    System.out.println(mainList[i].getColor());
}

Later in your studies, you will learn about Lists, which can grow and shrink with your data.


问:
Fastest way to check occurrence of a set of substrings in a large collection of documents using R
I have a large collection of documents, dc, (with several million rows) with the following data.frame structure

```<code>doc_id    body
  1       'sdfadfs...'
  2       'dfadf...'
  3       'sadf....'
</code>```

I also have about 10,000 terms (or substrings) stored in terms (terms=c('sfa','adfa','dfad',...)).

I want to find the occurrence of each term for each document of dc. In the end, I want the result to be something like this

```<code>doc_id term
  1    'sfa'
  1    'dfad'
  2    'adfa'
  3    'sfa'
  3    'dfad'
</code>```

Currently, I'm using the following code (with the help of stri_detect_fixed)

```<code>res_all=lapply(terms,function(term_i){ #loop over each term
    res=stri_detect_fixed(dc$body,term_i) #check occurrence of one term in each document

    data.frame(doc_id=which(res),term=term_i)

  })

bind_rows(res_all)
</code>```

However, the above code is quite slow. Is there anything I can do to speed up the code?

答:
Collapse the term values in one pattern and use it in stringr::str_extract_all which will return a list. Use unnest to get each term as separate row.

```<code>library(dplyr)

terms=c('sfa','adfa','dfad', ...)
pat <- sprintf('\\b(%s)\\b', paste0(terms, collapse = '|'))

df %>%
  mutate(term = stringr::str_extract_all(body, pat)) %>%
  tidyr::unnest(term)
</code>```

Word boundaries (\\b) are added to the pattern so that 'sfa' does not match with terms like 'asfa' or 'sfad' etc.

Body:
I have a large collection of documents, dc, (with several million rows) with the following data.frame structure

doc_id    body
  1       'sdfadfs...'
  2       'dfadf...'
  3       'sadf....'

I also have about 10,000 terms (or substrings) stored in terms (terms=c('sfa','adfa','dfad',...)).

I want to find the occurrence of each term for each document of dc. In the end, I want the result to be something like this

doc_id term
  1    'sfa'
  1    'dfad'
  2    'adfa'
  3    'sfa'
  3    'dfad'

Currently, I'm using the following code (with the help of stri_detect_fixed)

res_all=lapply(terms,function(term_i){ #loop over each term
    res=stri_detect_fixed(dc$body,term_i) #check occurrence of one term in each document

    data.frame(doc_id=which(res),term=term_i)

  })

bind_rows(res_all)

However, the above code is quite slow. Is there anything I can do to speed up the code?

Body:
Collapse the term values in one pattern and use it in stringr::str_extract_all which will return a list. Use unnest to get each term as separate row.

library(dplyr)

terms=c('sfa','adfa','dfad', ...)
pat <- sprintf('\\b(%s)\\b', paste0(terms, collapse = '|'))

df %>%
  mutate(term = stringr::str_extract_all(body, pat)) %>%
  tidyr::unnest(term)

Word boundaries (\\b) are added to the pattern so that 'sfa' does not match with terms like 'asfa' or 'sfad' etc.


问:
MPI Scatter with Recv blocking code execution
What is wrong with my code? MPI_Recv is blocking the code, should I use MPI_Gather to bring all values to master process? Not sure if I'm allowed to use MPI_Scatter with MPI_Recv.</p>
```<code>int rank;
int size;

MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);

if (rank == 0)
{
    int matrix[size];
    // Filling matrix here
    ...

    int value;
    MPI_Scatter(matrix, 1, MPI_INT, &value, 1, MPI_INT, 0, MPI_COMM_WORLD);
    printf("%d\n", value);
}
else
{
    int value;
    MPI_Recv(&value, 1, MPI_INT, 0, MPI_ANY_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
    printf("%d\n", value);
}

MPI_Finalize();
</code>```

答:
The MPI_Scatter routine is a so-called "collective", meaning that all processes should call it. While you are right that after a scatter from process zero every other process "receives" data in a metaphorical sense, technically they receive it in the receive buffer of the scatter call.

So you should delete the whole conditional, and replace it by only the MPI_Scatter line. Life is much simpler than you thought.

Body:
What is wrong with my code? MPI_Recv is blocking the code, should I use MPI_Gather to bring all values to master process? Not sure if I'm allowed to use MPI_Scatter with MPI_Recv.

int rank;
int size;

MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);

if (rank == 0)
{
    int matrix[size];
    // Filling matrix here
    ...

    int value;
    MPI_Scatter(matrix, 1, MPI_INT, &value, 1, MPI_INT, 0, MPI_COMM_WORLD);
    printf("%d\n", value);
}
else
{
    int value;
    MPI_Recv(&value, 1, MPI_INT, 0, MPI_ANY_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
    printf("%d\n", value);
}

MPI_Finalize();


问:
How to control number of processes and threads in OpenVINO
I want to know how to control the number of processes and threads in OpenVINO.

I executed following command referring to document.

```<code>docker run --name [my_server_name] --network [my_network] -d -u $(id -u):$(id -g)  -p 9000:9000 -p 8000:8000 \
[my_repository_name] --model_path /models/model1 --model_name models --port 9000 --rest_port 8000 \
--plugin_config '{"CPU_THROUGHPUT_STREAMS": "2","CPU_BIND_THREAD": "NUMA","CPU_THREADS_NUM": "3"}' --shape "(1,3,704,576)"
</code>```

Although I specified the '--plugin_config' no parameters are adopted and 1 process and 80 threads show up in the result of 'ps -efL' command.

Does anyone know the cause of this result?

答:
The plugin config parameters can define the number of threads used by the inference engine. Those are the threads dedicated to the inference execution. OpenVINO™ Model Server process will use more threads because some of them are related to gRPC and REST API servers.

They will use the number of threads dependent on the number of available CPU cores and for the number of REST server threads. They can be tuned with the parameter --rest_workers.

gRPC threads are not configurable now. They are set to the number of cpu cores, but it is possible to pass --grpc_channel_arguments to tune grpc server behavior.

Body:
I want to know how to control the number of processes and threads in OpenVINO.

I executed following command referring to document.

docker run --name [my_server_name] --network [my_network] -d -u $(id -u):$(id -g)  -p 9000:9000 -p 8000:8000 \
[my_repository_name] --model_path /models/model1 --model_name models --port 9000 --rest_port 8000 \
--plugin_config '{"CPU_THROUGHPUT_STREAMS": "2","CPU_BIND_THREAD": "NUMA","CPU_THREADS_NUM": "3"}' --shape "(1,3,704,576)"

Although I specified the '--plugin_config' no parameters are adopted and 1 process and 80 threads show up in the result of 'ps -efL' command.

Does anyone know the cause of this result?


问:
Get the span class name using BeautifulSoup
I am using BeautifulSoup to scrape a website. The retrieved resultset looks like this:

```<code><td><span class="I_Want_This_Class_Name"></span><span class="other_name">Text Is Here</span></td>
</code>```

From here, I want to retrieve the class name "I_Want_This_Class_Name". I can get the "Text Is Here" part no problem, but the class name itself is proving to be difficult.

Is there a way to do this using BeautifulSoup resultset or do I need to convert to a dictionary?

Thank you

答:
If you are trying to get the class name for this one result, then I would use the select method on your soup object, calling the class key:

```<code>foo_class = soup.select('td>span.I_Want_This_Class_Name')[0]['class'][0]
</code>```

Note here that the select method does return a list, hence the indexing before the key.

Body:
I am using BeautifulSoup to scrape a website. The retrieved resultset looks like this:

Text Is Here

From here, I want to retrieve the class name "I_Want_This_Class_Name". I can get the "Text Is Here" part no problem, but the class name itself is proving to be difficult.

Is there a way to do this using BeautifulSoup resultset or do I need to convert to a dictionary?

Thank you

Body:
If you are trying to get the class name for this one result, then I would use the select method on your soup object, calling the class key:

foo_class = soup.select('td>span.I_Want_This_Class_Name')[0]['class'][0]

Note here that the select method does return a list, hence the indexing before the key.


问:
What is the differences between the term SSTable and LSM Tree
Are these two terms used interchangeably?

I have read about how SSTable works, and usually, articles just start mentioning LSM Tree.
However, they seem to be the same thing.

When should I use one term over the other?

答:
Probably one of the best explanations of SSTables and LSM-Trees for mortals is given by Martin Kleppmann in his "Designing Data-Intensive Applications" book. These data structures are explained in chapter 3, "Storage and Retrieval", pages 69 through 79. It's a really great read, I would recommend the whole book!

Impatient ones could find my synopsis of the topic below

Everything starts with a very dumb key-value database implemented as just two Bash functions:

db_set () {
    echo "$1,$2" >> database
}

db_get () {
   grep "^$1," database | sed -e "s/^$1,//" | tail -n 1
}
```
<p>The idea is to store the data in a CSV-like file:</p>
<pre class="lang-sh prettyprint-override"><code>$ source database.sh

$ db_set 1 'Anakin Skywalker'
$ db_set 2 'Luke Skywalker'
$ db_set 1 'Darth Vader'

$ cat database
1,Anakin Skywalker
2,Luke Skywalker
1,Darth Vader

$ db_get 1
Darth Vader
</code>```

Note that the first value for the key 1 is overridden by the subsequent write.

This database has pretty good write performance: db_set just appends the data to a file, which is generally fast. But reads are inefficient, especially on huge data sets: db_get scans the entire file. Thus, writes are O(1) and reads are O(n).

Next, indices are introduced. An index is a data structure derived from the data itself. Maintaining an index always incurs additional costs, thus, indices always degrade write performance with the benefit of improving the reads.

One of the simplest possible indices is a hash index. This index is nothing more than a dictionary holding bytes offsets of the records in a database. Continuing previous example, assuming every char is one byte, the hash index would look like this:

Whenever you write data into the database, you also update the index. When you want to read a value for a given key, you could quickly look up an offset in the database file. Having the offset, you could use a "seek" operation to jump straight to the data location. Depending on the particular index implementation you could expect a logarithmic complexity for both reads and writes.

Next, Martin deals with the storage efficiency. Appending data to a database file exhausts disk space quickly. The fewer distinct keys you have — the more inefficient this append-only storage engine is. The solution to this problem is compaction:

When a database file grows to a certain size, you stop appending to it, create a new file (called segment) and redirect all the writes to this new file.

Segments are immutable in that sense that they are never used to append any new data. The only way to modify a segment is to write it's content into a new file, possibly with some transformations in between.

So, the compaction creates new segments containing only the most recent records for each key. Another possible enhancement at this step is merging multiple segments into a single one. Compaction and merging could be done, of course, in background. Old segments are just thrown away.

Every segment, including the one being written to, has its own index. So, when you want to find the value for a given key, you search those indices in reverse chronological order: from the most recent, to the oldest.

So far we have a data structure having these pros:

✔ Sequential writes are generally faster than random ones

✔ Concurrency is easy to control having a single writer process

✔ Crash recovery is easy to implement: just read all the segments sequentially, and store the offsets in the in-memory index

✔ Merging and compaction help to avoid data fragmentation

However, there are some limitations as well:

❗ Crash recovery could be time-consuming if segments are large and numerous

❗ Hash index must fit in memory. Implementing on-disk hash tables is much more difficult

❗ Range queries (BETWEEN) are virtually impossible

Now, with this background, let's move to the SSTables and LSM-trees. By the way, these abbreviations mean "Sorted String Tables" and "Log-Structured Merge Trees" accordingly.

SSTables are very similar to the "database" that we've seen previously. The only improvement is that we require records in segments to be sorted by key. This might seem to break the ability to use append-only writes, but that's what LSM-Trees for. We'll see in a moment!

SSTables have some advantages over those simple segments we had previously:

✔ Merging segments is more efficient due to the records being pre-sorted. All you have to do is to compare segment "heads" on each iteration and choose the lowest one. If multiple segments contain the same key, the value from the most recent segment wins. This compact & merge process also holds the sorting of the keys.

✔ With keys sorted, you don't need to have every single key in the index anymore. If the key B is known to be somewhere between keys A and C you could just do a scan. This also means that range queries are possible!

The final question is: how do you you get the data sorted by key?

The idea, described by Patrick O’Neil et al. in their "The Log-Structured Merge-Tree (LSM-Tree)", is simple: there are in-memory data structures, such as red-black trees or AVL-trees, that are good at sorting data. So, you split writes into two stages. First, you write the data into the in-memory balanced tree. Second, you flush that tree on the disk. Actually, there may be more than two stages, with deeper ones being bigger and "slower" then the upper (as shown in the other answer).

When a write comes, you add it to the in-memory balanced tree, called memtable.

When the memtable grows big, it is flushed to the disk. It is already sorted, so it naturally creates an SSTable segment.

Meanwhile, writes are processed by a fresh memtable.

Reads are first being looked up in the memtable, then in the segments, starting from the most recent one to the oldest.

Segments are compacted and merged from time to time in background as described previously.

The scheme is not perfect, it could suffer from sudden crashes: the memtable, being an in-memory data structure, is lost. This issue could be solved by maintaining another append-only file that basically duplicates the contents of the memtable. The database only needs to read it after a crash to re-create the memtable.

And that's it! Note that all the issues of a simple append-only storage, described above, are now solved:

✔ Now there is only one file to read in a case of a crash: the memtable backup

✔ Indices could be sparse, thus fitting the RAM is easier

✔ Range queries are now possible

TLDR: An SSTable is a key-sorted append-only key-value storage. An LSM-tree is a layered data structure, based on a balanced tree, that allows SSTables to exist without the controversy of being both sorted and append-only at the same time.

Congrats, you've finished this long read! If you enjoyed the explanation, make sure not only upvote this post, but some of the Martin's answers here as well. Remember: all credits go to him!

Body:
Probably one of the best explanations of SSTables and LSM-Trees for mortals is given by Martin Kleppmann in his "Designing Data-Intensive Applications" book. These data structures are explained in chapter 3, "Storage and Retrieval", pages 69 through 79. It's a really great read, I would recommend the whole book!

Impatient ones could find my synopsis of the topic below

Everything starts with a very dumb key-value database implemented as just two Bash functions:

db_set () {
    echo "$1,$2" >> database
}

db_get () {
   grep "^$1," database | sed -e "s/^$1,//" | tail -n 1
}

The idea is to store the data in a CSV-like file:

$ source database.sh

$ db_set 1 'Anakin Skywalker'
$ db_set 2 'Luke Skywalker'
$ db_set 1 'Darth Vader'

$ cat database
1,Anakin Skywalker
2,Luke Skywalker
1,Darth Vader

$ db_get 1
Darth Vader

Note that the first value for the key 1 is overridden by the subsequent write.

This database has pretty good write performance: db_set just appends the data to a file, which is generally fast. But reads are inefficient, especially on huge data sets: db_get scans the entire file. Thus, writes are O(1) and reads are O(n).

Next, indices are introduced. An index is a data structure derived from the data itself. Maintaining an index always incurs additional costs, thus, indices always degrade write performance with the benefit of improving the reads.

One of the simplest possible indices is a hash index. This index is nothing more than a dictionary holding bytes offsets of the records in a database. Continuing previous example, assuming every char is one byte, the hash index would look like this:

Whenever you write data into the database, you also update the index. When you want to read a value for a given key, you could quickly look up an offset in the database file. Having the offset, you could use a "seek" operation to jump straight to the data location. Depending on the particular index implementation you could expect a logarithmic complexity for both reads and writes.

Next, Martin deals with the storage efficiency. Appending data to a database file exhausts disk space quickly. The fewer distinct keys you have — the more inefficient this append-only storage engine is. The solution to this problem is compaction:

When a database file grows to a certain size, you stop appending to it, create a new file (called segment) and redirect all the writes to this new file.

Segments are immutable in that sense that they are never used to append any new data. The only way to modify a segment is to write it's content into a new file, possibly with some transformations in between.

So, the compaction creates new segments containing only the most recent records for each key. Another possible enhancement at this step is merging multiple segments into a single one. Compaction and merging could be done, of course, in background. Old segments are just thrown away.

Every segment, including the one being written to, has its own index. So, when you want to find the value for a given key, you search those indices in reverse chronological order: from the most recent, to the oldest.

So far we have a data structure having these pros:

✔ Sequential writes are generally faster than random ones

✔ Concurrency is easy to control having a single writer process

✔ Crash recovery is easy to implement: just read all the segments sequentially, and store the offsets in the in-memory index

✔ Merging and compaction help to avoid data fragmentation

However, there are some limitations as well:

❗ Crash recovery could be time-consuming if segments are large and numerous

❗ Hash index must fit in memory. Implementing on-disk hash tables is much more difficult

❗ Range queries (BETWEEN) are virtually impossible

Now, with this background, let's move to the SSTables and LSM-trees. By the way, these abbreviations mean "Sorted String Tables" and "Log-Structured Merge Trees" accordingly.

SSTables are very similar to the "database" that we've seen previously. The only improvement is that we require records in segments to be sorted by key. This might seem to break the ability to use append-only writes, but that's what LSM-Trees for. We'll see in a moment!

SSTables have some advantages over those simple segments we had previously:

✔ Merging segments is more efficient due to the records being pre-sorted. All you have to do is to compare segment "heads" on each iteration and choose the lowest one. If multiple segments contain the same key, the value from the most recent segment wins. This compact & merge process also holds the sorting of the keys.

✔ With keys sorted, you don't need to have every single key in the index anymore. If the key B is known to be somewhere between keys A and C you could just do a scan. This also means that range queries are possible!

The final question is: how do you you get the data sorted by key?

The idea, described by Patrick O’Neil et al. in their "The Log-Structured Merge-Tree (LSM-Tree)", is simple: there are in-memory data structures, such as red-black trees or AVL-trees, that are good at sorting data. So, you split writes into two stages. First, you write the data into the in-memory balanced tree. Second, you flush that tree on the disk. Actually, there may be more than two stages, with deeper ones being bigger and "slower" then the upper (as shown in the other answer).

When a write comes, you add it to the in-memory balanced tree, called memtable.

When the memtable grows big, it is flushed to the disk. It is already sorted, so it naturally creates an SSTable segment.

Meanwhile, writes are processed by a fresh memtable.

Reads are first being looked up in the memtable, then in the segments, starting from the most recent one to the oldest.

Segments are compacted and merged from time to time in background as described previously.

The scheme is not perfect, it could suffer from sudden crashes: the memtable, being an in-memory data structure, is lost. This issue could be solved by maintaining another append-only file that basically duplicates the contents of the memtable. The database only needs to read it after a crash to re-create the memtable.

And that's it! Note that all the issues of a simple append-only storage, described above, are now solved:

✔ Now there is only one file to read in a case of a crash: the memtable backup

✔ Indices could be sparse, thus fitting the RAM is easier

✔ Range queries are now possible

TLDR: An SSTable is a key-sorted append-only key-value storage. An LSM-tree is a layered data structure, based on a balanced tree, that allows SSTables to exist without the controversy of being both sorted and append-only at the same time.

Congrats, you've finished this long read! If you enjoyed the explanation, make sure not only upvote this post, but some of the Martin's answers here as well. Remember: all credits go to him!


问:
KeyError Codes from User Input
Good Evening All,

I have been working on my first self directed project and have run into a bit of a snag.  The program calculates what a character would have to roll to hit another based on their THAC0 and AC.  The two scores in question are kept in a pair of dictionaries.  If something is entered that is not in the dictionary I want the program to let whoever is operating it know.  I've managed to get it to produce an error code, but I still get a KeyError.  How do I get it to stop doing that?

```<code>defender = input("Who are they attacking?")
dict_thaco = {"Serena" : 19, "Morris" : 19}
if aggressor in dict_thaco:
    pass
else:
    print("I don't know that attacker")
dict_ac = {"Serena" : 6, "Morris" : -1}
if defender in dict_ac:
    pass
else:
    print("I don't know that defender")
def thaco_calc(thaco, ac):
    to_hit = thaco - ac
    return to_hit
aggressor_thaco = dict_thaco[aggressor]
defender_ac = dict_ac[defender]
hit = thaco_calc(aggressor_thaco, defender_ac)
print(aggressor + " would need to roll a " + str(hit) + " to hit " + defender + ".")
</code>```

答:
Perhaps you need something like</p>
```<code>...
try:
    aggressor_thaco = dict_thaco[aggressor]
    defender_ac = dict_ac[defender]
    hit = thaco_calc(aggressor_thaco, defender_ac)
    print(aggressor + " would need to roll a " + str(hit) + " to hit " + defender + ".")
except KeyError as e:
    print(e)
</code>```

Title: KeyError Codes from User Input

Body:
Good Evening All,

I have been working on my first self directed project and have run into a bit of a snag.  The program calculates what a character would have to roll to hit another based on their THAC0 and AC.  The two scores in question are kept in a pair of dictionaries.  If something is entered that is not in the dictionary I want the program to let whoever is operating it know.  I've managed to get it to produce an error code, but I still get a KeyError.  How do I get it to stop doing that?

defender = input("Who are they attacking?")
dict_thaco = {"Serena" : 19, "Morris" : 19}
if aggressor in dict_thaco:
    pass
else:
    print("I don't know that attacker")
dict_ac = {"Serena" : 6, "Morris" : -1}
if defender in dict_ac:
    pass
else:
    print("I don't know that defender")
def thaco_calc(thaco, ac):
    to_hit = thaco - ac
    return to_hit
aggressor_thaco = dict_thaco[aggressor]
defender_ac = dict_ac[defender]
hit = thaco_calc(aggressor_thaco, defender_ac)
print(aggressor + " would need to roll a " + str(hit) + " to hit " + defender + ".")

Body:
Perhaps you need something like

...
try:
    aggressor_thaco = dict_thaco[aggressor]
    defender_ac = dict_ac[defender]
    hit = thaco_calc(aggressor_thaco, defender_ac)
    print(aggressor + " would need to roll a " + str(hit) + " to hit " + defender + ".")
except KeyError as e:
    print(e)


问:
Discord.js | TypeError: Cannot read property 'MessageEmbed' of undefined
I'm a beginner at coding. I'm making a node.js today, and it says there's a problem with the embed. I don't know why, but it doesn't work even if I use someone else's code. How should I solve this?

const { Permissions , MessageActionRow , MessageSelectMenu , MessageEmbed,Discord} = require('discord.js')

module.exports = {
name: 'command',
description: 'Embeds',
execute(message, args, Discord)
    {
const newEmbed = new Discord.MessageEmbed()
        .setColor('#ff0000')
        .setTitle('Yes')
        .setDescription('My Embed')
        .setFooter('life is a lie');

interaction.channel.send({embeds : [embed]})
    },
};```

This happens. FYI, I shared the code in the Commandz folder, and the index folder had the same error, so I uploaded it. Help me!

答:
from your code:

```<code>const newEmbed = new Discord.MessageEmbed()
    .setColor('#ff0000')
    .setTitle('Yes')
    .setDescription('My Embed')
    .setFooter('life is a lie');

interaction.channel.send({embeds : [embed]})
</code>```

change your Discord.MessageEmbed() to MessageEmbed since you type from your module as MessageEmbed.

Body:
I'm a beginner at coding. I'm making a node.js today, and it says there's a problem with the embed. I don't know why, but it doesn't work even if I use someone else's code. How should I solve this?

const { Permissions , MessageActionRow , MessageSelectMenu , MessageEmbed,Discord} = require('discord.js')

module.exports = {
name: 'command',
description: 'Embeds',
execute(message, args, Discord)
    {
const newEmbed = new Discord.MessageEmbed()
        .setColor('#ff0000')
        .setTitle('Yes')
        .setDescription('My Embed')
        .setFooter('life is a lie');

interaction.channel.send({embeds : [embed]})
    },
};

This happens. FYI, I shared the code in the Commandz folder, and the index folder had the same error, so I uploaded it. Help me!

Body:
from your code:

const newEmbed = new Discord.MessageEmbed()
    .setColor('#ff0000')
    .setTitle('Yes')
    .setDescription('My Embed')
    .setFooter('life is a lie');

interaction.channel.send({embeds : [embed]})

change your Discord.MessageEmbed() to MessageEmbed since you type from your module as MessageEmbed.


问:
gcloud crashed HTTPSConnectionPool
gcloud auth login not coming back to terminal on macos:

ERROR: gcloud crashed (ConnectionError):

HTTPSConnectionPool(host='oauth2.googleapis.com', port=443): Max retries exceeded with url: /token (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x105347130>:

Failed to establish a new connection: [Errno 60] Operation timed out'))

gcloud auth login working fine on my other PC windows bash terminal with same Wifi.

Given read & write permissions to everyone of folder google-cloud-sdk

答: The problem is with your ISP, Airtel India. Use a VPN, and it work.</p>

Title: gcloud crashed HTTPSConnectionPool


问:
Is there a way I can print multiple lines using one print()?
I'm new to programming and having trouble understanding Python. I would like to use only one print() to lessen its usage.

first_name = "Gabh"
Gabh ="Musician"
age = 21
height = 5.4
weight = 47
print(first_name + (" is a"), Gabh)
print(("age:"), age)
print(("height:"), height)
print(("weight:"), weight)
```
<p>With this code, this is what I'm getting:</p>
<pre class="lang-py prettyprint-override"><code>Gabh is a Musician
age: 21
height: 5.4
weight: 47
</code>```

答:
If you'd like to have a preconfigured multiline block of text to print, and just add some values to it (bit like doing a mail-merge in Word), you can use the str.format method.

```<code>>>> help(str.format)

format(...)
 |      S.format(*args, **kwargs) -> str
 |
 |      Return a formatted version of S, using substitutions from args and kwargs.
 |      The substitutions are identified by braces ('{' and '}').
</code>```

Multiline strings have """ (or, less commonly, ''').

template = """{name} is a {role}.
Age: {age}
Height: {height} metres
Weight: {weight} milligrams"""

gabh = template.format(
    name="Gabh",
    role="Musician",
    age=21,
    height=5.4,
    weight=47
)

print(gabh)
```
<p>(This is slightly different to f-strings, where values get put into the string at the moment it's created.)</p>
<p>If you have a dictionary with keys matching the <code>{stuff} in {curly braces}</code> in your template string, you can use <code>format_map</code>:</p>
<pre class="lang-py prettyprint-override"><code>template = """{name} is a {role}.
Age: {age}
Height: {height} metres
Weight: {weight} milligrams"""

gabh = {
    "name": "Gabh",
    "role": "Musician",
    "age": 21,
    "height": 5.4,
    "weight": 47,
}

print(template.format_map(gabh))
</code>```

Body:
I'm new to programming and having trouble understanding Python. I would like to use only one print() to lessen its usage.

first_name = "Gabh"
Gabh ="Musician"
age = 21
height = 5.4
weight = 47
print(first_name + (" is a"), Gabh)
print(("age:"), age)
print(("height:"), height)
print(("weight:"), weight)

With this code, this is what I'm getting:

Gabh is a Musician
age: 21
height: 5.4
weight: 47

Body:
If you'd like to have a preconfigured multiline block of text to print, and just add some values to it (bit like doing a mail-merge in Word), you can use the str.format method.

>>> help(str.format)

format(...)
 |      S.format(*args, **kwargs) -> str
 |
 |      Return a formatted version of S, using substitutions from args and kwargs.
 |      The substitutions are identified by braces ('{' and '}').

Multiline strings have """ (or, less commonly, ''').

template = """{name} is a {role}.
Age: {age}
Height: {height} metres
Weight: {weight} milligrams"""

gabh = template.format(
    name="Gabh",
    role="Musician",
    age=21,
    height=5.4,
    weight=47
)

print(gabh)

(This is slightly different to f-strings, where values get put into the string at the moment it's created.)

If you have a dictionary with keys matching the {stuff} in {curly braces} in your template string, you can use format_map:

template = """{name} is a {role}.
Age: {age}
Height: {height} metres
Weight: {weight} milligrams"""

gabh = {
    "name": "Gabh",
    "role": "Musician",
    "age": 21,
    "height": 5.4,
    "weight": 47,
}

print(template.format_map(gabh))


问:
Import a text file and replace a values of an array in Java
I’m a beginner in Java and I'm stuck in one step in my practice where I should import an txt file into an array (using JFileChooser)

The text format is as follow
001 839 333 426 …

Where each 3 characters separated by space correspond to xyz where
x= line number;    y= column number;      v= value

I have to replace the values in the board based on the coordinates (xy)

```<code>int [][] board =
{
{ 1, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 6, 0, 0, 0, 0 },
{ 0, 0, 0, 3, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 9, 0, 0, 0, 0, 0, 0 }
}
</code>```

If an invalide value is found it should not be used for example 901 (because no line available 9).

Any help or thoughts are very welcome.

答:
For those interested finally, I found a way to do the conversion may be not the optimal, but it works:</p>
```<code>public boolean loadFromFile(String path) {
try {
  int x, y, v;
  Scanner sc = new Scanner(new String());
  Scanner file = new Scanner(new File(path));
  while (file.hasNextLine()) {
    String newLine = file.nextLine();
    sc = new Scanner(newLine);
    while (sc.hasNext()) {
      String xyvalue = sc.next();
      char[] xyv = xyvalue.toCharArray();
      if (xyv.length == 3) {
        x = Character.getNumericValue(xyv[0]);
        y = Character.getNumericValue(xyv[1]);
        v = Character.getNumericValue(xyv[2]);
        if (x >= 0 && x < 9 && y >= 0 && y < 9 && v > 0 && v <= 9) {
          board[x][y] = v;
        }
      }
    }
  }
  sc.close();
  file.close();
  return true;
} catch (IOException exception) {
  return false;
}
</code>```

Body:
I’m a beginner in Java and I'm stuck in one step in my practice where I should import an txt file into an array (using JFileChooser)

The text format is as follow
001 839 333 426 …

Where each 3 characters separated by space correspond to xyz where
x= line number;    y= column number;      v= value

I have to replace the values in the board based on the coordinates (xy)

int [][] board =
{
{ 1, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 6, 0, 0, 0, 0 },
{ 0, 0, 0, 3, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 9, 0, 0, 0, 0, 0, 0 }
}

If an invalide value is found it should not be used for example 901 (because no line available 9).

Any help or thoughts are very welcome.

Body:
For those interested finally, I found a way to do the conversion may be not the optimal, but it works:

public boolean loadFromFile(String path) {
try {
  int x, y, v;
  Scanner sc = new Scanner(new String());
  Scanner file = new Scanner(new File(path));
  while (file.hasNextLine()) {
    String newLine = file.nextLine();
    sc = new Scanner(newLine);
    while (sc.hasNext()) {
      String xyvalue = sc.next();
      char[] xyv = xyvalue.toCharArray();
      if (xyv.length == 3) {
        x = Character.getNumericValue(xyv[0]);
        y = Character.getNumericValue(xyv[1]);
        v = Character.getNumericValue(xyv[2]);
        if (x >= 0 && x < 9 && y >= 0 && y < 9 && v > 0 && v <= 9) {
          board[x][y] = v;
        }
      }
    }
  }
  sc.close();
  file.close();
  return true;
} catch (IOException exception) {
  return false;
}