问:
Why does my java program report "package not found" when it's clearly there in the classpath?
My kick-off of a new java application that imports a third-party java package has stalled right out of the gate.  The compiler is reporting that the package in question does not exist.  Although I began with VS Code and Gradle, I've simplified the problem down to just the java app code, the third-party jar file, and the javac compiler command.  Can someone please help me figure out why javac is reporting "package not present" for a jar file that seems clearly to be right there in the classpath?

Here's the command line:

```<code>javac -verbose -classpath . App.java
</code>```

Here's the java version:

```<code>javac 17.0.1
</code>```

Here's the directory listing:

```<code>-rw-rw-r-- 1 kevin kevin   1059 Feb  6 12:08 App.java
-rw-rw-r-- 1 kevin kevin 212231 Feb  5 17:14 neo4j-4.4.3.jar
</code>```

Here's the App.java code:

```<code>/*
 * This Java source file was generated by the Gradle 'init' task.
 */
package neural;

import org.neo4j.*;

public class App {
    public String getGreeting() {
        return "Hello World!";
    }
    private static void registerShutdownHook( final DatabaseManagementService managementService )
    {
        // Registers a shutdown hook for the Neo4j instance so that it
        // shuts down nicely when the VM exits (even if you "Ctrl-C" the
        // running application).
        Runtime.getRuntime().addShutdownHook( new Thread()
        {
            @Override
            public void run()
            {
                managementService.shutdown();
            }
        } );
    }
    public static void main(String[] args) {
        System.out.println(new App().getGreeting());

        managementService = new DatabaseManagementServiceBuilder( databaseDirectory ).build();
        graphDb = managementService.database( DEFAULT_DATABASE_NAME );
        registerShutdownHook( managementService );

        managementService.shutdown();
    }
}
</code>```

Here's the start of the errors:

```<code>App.java:12: error: cannot find symbol
    private static void registerShutdownHook( final DatabaseManagementService managementService )
                                                    ^
  symbol:   class DatabaseManagementService
  location: class App
App.java:6: error: package org.neo4j does not exist
import org.neo4j.*;
^
</code>```

Here's confirmation it's looking in the current directory:

```<code>[search path for source files: .]
[search path for class files: /usr/lib/jvm/java-17-oracle/lib/modules,.]
</code>```

Here's an exerpt from the jar file:

```<code>META-INF/MANIFEST.MF
META-INF/
META-INF/services/
org/
org/neo4j/
org/neo4j/graphdb/
org/neo4j/graphdb/factory/
org/neo4j/graphdb/factory/module/
org/neo4j/graphdb/factory/module/id/
org/neo4j/graphdb/factory/module/edition/
org/neo4j/graphdb/factory/module/edition/context/
org/neo4j/graphdb/facade/
org/neo4j/server/
org/neo4j/server/startup/
org/neo4j/dbms/
org/neo4j/dbms/identity/
org/neo4j/dbms/systemgraph/
org/neo4j/dbms/systemgraph/versions/
org/neo4j/dbms/procedures/
org/neo4j/dbms/api/
org/neo4j/dbms/database/
org/neo4j/dbms/database/readonly/
</code>```

I've rerun (and since renamed some files for other reasons):

```<code>javac -verbose -classpath neo4j-4.4.3.jar /home/kevin/Projects/echo_ws/lib_neo4j/lib_neo4j/src/main/java/lib_neo4j/lib_neo4j.java
</code>```

which gives

```<code>[search path for source files: neo4j-4.4.3.jar]
[search path for class files: /usr/lib/jvm/java-17-oracle/lib/modules,neo4j-4.4.3.jar]
[loading /modules/java.base/java/lang/Object.class]
[loading /modules/java.base/java/lang/String.class]
/home/kevin/Projects/echo_ws/lib_neo4j/lib_neo4j/src/main/java/lib_neo4j/lib_neo4j.java:12: error: cannot find symbol
    private static void registerShutdownHook( final DatabaseManagementService managementService )
                                                    ^
  symbol:   class DatabaseManagementService
  location: class lib_neo4j
/home/kevin/Projects/echo_ws/lib_neo4j/lib_neo4j/src/main/java/lib_neo4j/lib_neo4j.java:6: error: package org.neo4j does not exist
import org.neo4j.*;
^
</code>```

答:
I think you should try this:

```<code>javac -verbose -classpath ./* App.java
</code>```

But I would strongly recommend to use building systems like Gradle or Maven.

Body:
My kick-off of a new java application that imports a third-party java package has stalled right out of the gate.  The compiler is reporting that the package in question does not exist.  Although I began with VS Code and Gradle, I've simplified the problem down to just the java app code, the third-party jar file, and the javac compiler command.  Can someone please help me figure out why javac is reporting "package not present" for a jar file that seems clearly to be right there in the classpath?

Here's the command line:

javac -verbose -classpath . App.java

Here's the java version:

javac 17.0.1

Here's the directory listing:

-rw-rw-r-- 1 kevin kevin   1059 Feb  6 12:08 App.java
-rw-rw-r-- 1 kevin kevin 212231 Feb  5 17:14 neo4j-4.4.3.jar

Here's the App.java code:

/*
 * This Java source file was generated by the Gradle 'init' task.
 */
package neural;

import org.neo4j.*;

public class App {
    public String getGreeting() {
        return "Hello World!";
    }
    private static void registerShutdownHook( final DatabaseManagementService managementService )
    {
        // Registers a shutdown hook for the Neo4j instance so that it
        // shuts down nicely when the VM exits (even if you "Ctrl-C" the
        // running application).
        Runtime.getRuntime().addShutdownHook( new Thread()
        {
            @Override
            public void run()
            {
                managementService.shutdown();
            }
        } );
    }
    public static void main(String[] args) {
        System.out.println(new App().getGreeting());

        managementService = new DatabaseManagementServiceBuilder( databaseDirectory ).build();
        graphDb = managementService.database( DEFAULT_DATABASE_NAME );
        registerShutdownHook( managementService );

        managementService.shutdown();
    }
}

Here's the start of the errors:

App.java:12: error: cannot find symbol
    private static void registerShutdownHook( final DatabaseManagementService managementService )
                                                    ^
  symbol:   class DatabaseManagementService
  location: class App
App.java:6: error: package org.neo4j does not exist
import org.neo4j.*;
^

Here's confirmation it's looking in the current directory:

[search path for source files: .]
[search path for class files: /usr/lib/jvm/java-17-oracle/lib/modules,.]

Here's an exerpt from the jar file:

META-INF/MANIFEST.MF
META-INF/
META-INF/services/
org/
org/neo4j/
org/neo4j/graphdb/
org/neo4j/graphdb/factory/
org/neo4j/graphdb/factory/module/
org/neo4j/graphdb/factory/module/id/
org/neo4j/graphdb/factory/module/edition/
org/neo4j/graphdb/factory/module/edition/context/
org/neo4j/graphdb/facade/
org/neo4j/server/
org/neo4j/server/startup/
org/neo4j/dbms/
org/neo4j/dbms/identity/
org/neo4j/dbms/systemgraph/
org/neo4j/dbms/systemgraph/versions/
org/neo4j/dbms/procedures/
org/neo4j/dbms/api/
org/neo4j/dbms/database/
org/neo4j/dbms/database/readonly/

I've rerun (and since renamed some files for other reasons):

javac -verbose -classpath neo4j-4.4.3.jar /home/kevin/Projects/echo_ws/lib_neo4j/lib_neo4j/src/main/java/lib_neo4j/lib_neo4j.java

which gives

[search path for source files: neo4j-4.4.3.jar]
[search path for class files: /usr/lib/jvm/java-17-oracle/lib/modules,neo4j-4.4.3.jar]
[loading /modules/java.base/java/lang/Object.class]
[loading /modules/java.base/java/lang/String.class]
/home/kevin/Projects/echo_ws/lib_neo4j/lib_neo4j/src/main/java/lib_neo4j/lib_neo4j.java:12: error: cannot find symbol
    private static void registerShutdownHook( final DatabaseManagementService managementService )
                                                    ^
  symbol:   class DatabaseManagementService
  location: class lib_neo4j
/home/kevin/Projects/echo_ws/lib_neo4j/lib_neo4j/src/main/java/lib_neo4j/lib_neo4j.java:6: error: package org.neo4j does not exist
import org.neo4j.*;
^

Body:
I think you should try this:

javac -verbose -classpath ./* App.java

But I would strongly recommend to use building systems like Gradle or Maven.


来源: stackexchange

问:
How do you order a list by their distance to a certain number?
For example:

Say I had a list

[0,1,2,3,4,5,6,7]

I want it to order it so that 4 is index 0 and the indexes following are in order of how close they are to 4 (like [4,3,5,2,6,1,7])

How would you do this?

ContentLicense: CC BY-SA 4.0

Body:
l = [0,1,2,3,4,5,6,7]
l.sort(key=lambda i: abs(i-4))
print(l)

>> [4, 3, 5, 2, 6, 1, 7, 0]


答:
Use sorted or .sort method with a key parameter, to get how close a number is to 4 just subtract by it and get its absolute value:

>>> a = [0,1,2,3,4,5,6,7]
>>> sorted(a, key=lambda x: abs(4-x))
[4, 3, 5, 2, 6, 1, 7, 0]
```

Title: How do you order a list by their distance to a certain number?

Body:
For example:

Say I had a list

[0,1,2,3,4,5,6,7]

I want it to order it so that 4 is index 0 and the indexes following are in order of how close they are to 4 (like [4,3,5,2,6,1,7])

How would you do this?


问:
FlatList search bar does not persist keyboard React Native
I'm fetching data from an API and implementing search in a FlatList but the keyboard dismisses automatically after every key-press.
I'm refering this article but implementing it in a Functional Component.

```<code> const renderHeader = () => {
        return <SearchBar
        placeholder="Type Here..."
        lightTheme
        round
        onChangeText={text => searchFilterFunction(text)}
        value={value}
        autoCorrect={false} />;
    }

 const searchFilterFunction = (text) => {
        setValue(text);
        const newData = APIData.filter(item => {
            const itemData = `${item.name.toUpperCase()}`;
            const textData = text.toUpperCase();
            return itemData.includes(textData);
        });
        setData(newData);
    }

 return (
    <FlatList
    keyExtractor={(item) => item._id}
    data={data}
    ItemSeparatorComponent={renderSeparator}
    ListHeaderComponent={renderHeader}
    ListFooterComponent={renderFooter}
    onRefresh={handleRefresh}
    refreshing={refreshing}
    renderItem={({ item }) => (
        <Card>
            <Card.Content style={{ flexDirection: "row" }}>
                <Text>{"Name: " + item.name}</Text>
                <Text>{"Status: " + (item.isaccepted ? "Accepted" : "Pending")}</Text>
                <Text>{"ID: " + item.id}</Text>
            </Card.Content>
        </Card>
    )} />
)
</code>```

Thanks in advance.

答:
Try rendering your ListHeaderComponent as JSX element directly, instead of using callback</p>
```<code><FlatList
    ListHeaderComponent={
      <View>
       <Text>I am the header</Text>
      </View>
    }
    ...props
/>

</code>```

Body:
I'm fetching data from an API and implementing search in a FlatList but the keyboard dismisses automatically after every key-press.
I'm refering this article but implementing it in a Functional Component.

 const renderHeader = () => {
        return <SearchBar
        placeholder="Type Here..."
        lightTheme
        round
        onChangeText={text => searchFilterFunction(text)}
        value={value}
        autoCorrect={false} />;
    }

 const searchFilterFunction = (text) => {
        setValue(text);
        const newData = APIData.filter(item => {
            const itemData = `${item.name.toUpperCase()}`;
            const textData = text.toUpperCase();
            return itemData.includes(textData);
        });
        setData(newData);
    }

 return (
    <FlatList
    keyExtractor={(item) => item._id}
    data={data}
    ItemSeparatorComponent={renderSeparator}
    ListHeaderComponent={renderHeader}
    ListFooterComponent={renderFooter}
    onRefresh={handleRefresh}
    refreshing={refreshing}
    renderItem={({ item }) => (
        <Card>
            <Card.Content style={{ flexDirection: "row" }}>
                <Text>{"Name: " + item.name}</Text>
                <Text>{"Status: " + (item.isaccepted ? "Accepted" : "Pending")}</Text>
                <Text>{"ID: " + item.id}</Text>
            </Card.Content>
        </Card>
    )} />
)

Thanks in advance.

Body:
Try rendering your ListHeaderComponent as JSX element directly, instead of using callback

<FlatList
    ListHeaderComponent={
      <View>
       <Text>I am the header</Text>
      </View>
    }
    ...props
/>


问:
Regex for ANY string except "www"? (subdomain)
I was wondering if someone out there could help me with a regex in C#. I think it's fairly simple but I've been wracking my brain over it and not quite sure why I'm having such a hard time.  :)

I've found a few examples around but I can't seem to manipulate them to do what I need.

I just need to match ANY alphanumeric+dashes subdomain string that is not "www", and just up to the "."

Also, ideally, if someone were to type "www.subdomain.domain.com" I would like the www to be ignored if possible. If not, it's not a huge issue.

In other words, I would like to match:

(test).domain.com

(test2).domain.com

(wwwasdf).domain.com

(asdfwww).domain.com

(w).domain.com

(wwwwww).domain.com

(asfd-12345-www-bananas).domain.com

www.(subdomain).domain.com

And I don't want to match:

(www).domain.com

It seems to me like it should be easy, but I'm having troubles with the "not match" part.

For what it's worth, this is for use in the IIS 7 URL Rewrite Module, to rewrite for all non-www subdomains.

Thanks!

答:
Is the remainder of the domain name constant, like .domain.com, as in your examples?  Try this:

```<code>\b(?!www\.)(\w+(?:-\w+)*)(?=\.domain\.com\b)
</code>```

Explanation:

\w+(?:-\w+)* matches a generic domain-name component as you described (but a little more rigorously).

(?=\.domain\.com\b) makes sure it's the first subdomain (i.e., the last one before the actual domain name).

\b(?!www\.) makes sure it isn't www. (without the \b, it could skip over the first w and match just the ww.).

In my tests, this regex matches precisely the parts you highlighted in your examples, and does not match the www. in either of the last two examples.

EDIT: Here's another version which matches the whole name, capturing the pieces in different groups:

```<code>^((?:\w+(?:-\w+)*\.)*)((?!www\.)\w+(?:-\w+)*)(\.domain\.com)$
</code>```

In most cases, group $1 will contain an empty string because there's nothing before the subdomain name, but here's how it breaks down www.subdomain.domain.com:

```<code>$1: "www."
$2: "subdomain"
$3: ".domain.com"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Is the remainder of the domain name constant, like .domain.com, as in your examples?  Try this:

\b(?!www\.)(\w+(?:-\w+)*)(?=\.domain\.com\b)

Explanation:

\w+(?:-\w+)* matches a generic domain-name component as you described (but a little more rigorously).

(?=\.domain\.com\b) makes sure it's the first subdomain (i.e., the last one before the actual domain name).

\b(?!www\.) makes sure it isn't www. (without the \b, it could skip over the first w and match just the ww.).

In my tests, this regex matches precisely the parts you highlighted in your examples, and does not match the www. in either of the last two examples.

EDIT: Here's another version which matches the whole name, capturing the pieces in different groups:

^((?:\w+(?:-\w+)*\.)*)((?!www\.)\w+(?:-\w+)*)(\.domain\.com)$

In most cases, group $1 will contain an empty string because there's nothing before the subdomain name, but here's how it breaks down www.subdomain.domain.com:

$1: "www."
$2: "subdomain"
$3: ".domain.com"


问:
Best metrics for neural network regression model in keras with multiple outputs
I have built a neural network model with 495 inputs and 5 outputs which are to be predicted. When I did regression models with a single output, I liked using RMSE and R-squared as metrics. What similar metrics can be used for regression model with multiple outputs? I am already using MSE as the loss function so I suppose I should be using a different function as a metric.</p>

答: If you are doing a classification study, then you should use F1-score or like accuracy. I did not understand what you meant by 5 outputs? Is it like you are outputting 5 different regression series or something</p>


问:
Is it possible to install Docker container in Windows -32 bit systems?
I am getting error as Docker needs 64bit configuration, is there any way where i can install docker in 32 bit systems. It's a 32 bit i3 processor having windows 7 machine.</p>

答:
No, this is not possible for current versions of the docker.

This was possible for early versions of docher (boot2docker 32bit iso), but the project is closed and thoroughly killed


问:
Discord Bot Sending Multiple Messages in One Line
What I am trying to do is, with Python, create a Discord bot that matches people together. I have basically done it, but the thing is that sometimes it glitches since it is in separate lines. How do I make it all into one message?</p>
```<code> guyNames = [
    "test1"
  ]

  girlNames = [
    "test2"
  ]

  if '$matchlovers' in message.content.lower():
    await message.channel.send(random.choice(girlNames))
    await message.channel.send("+")
    await message.channel.send(random.choice(guyNames))
</code>```

答:
Turn

```<code>await message.channel.send(random.choice(girlNames))
    await message.channel.send("+")
    await message.channel.send(random.choice(guyNames))
</code>```

Into

```<code>await message.channel.send(random.choice(girlNames) + "\n+\n" + random.choice(guyNames))
</code>```

Body:
What I am trying to do is, with Python, create a Discord bot that matches people together. I have basically done it, but the thing is that sometimes it glitches since it is in separate lines. How do I make it all into one message?

 guyNames = [
    "test1"
  ]

  girlNames = [
    "test2"
  ]

  if '$matchlovers' in message.content.lower():
    await message.channel.send(random.choice(girlNames))
    await message.channel.send("+")
    await message.channel.send(random.choice(guyNames))

Body:
Turn

await message.channel.send(random.choice(girlNames))
    await message.channel.send("+")
    await message.channel.send(random.choice(guyNames))

Into

await message.channel.send(random.choice(girlNames) + "\n+\n" + random.choice(guyNames))


问:
Gitlab: how can I disable email notifications for new commits pushed to merge requests?
In Gitlab my notification settings are set to "participate". I am getting tons of emails from Gitlab.

I would like to receive emails regarding new comments on merge requests that I'm participating in. But I would not like to receive an email for every time somebody pushes a commit to an MR that is assigned to me. That results in a huge amount of emails that I simply ignore.

I also wouldn't mind getting an email notification for a commit pushed on a merge request opened by me, but that's just a nice to have.

Looking in the Gitlab notification settings I haven't found a setting to support this. "Custom" settings are simply an extension of "particiapte", which means I still get an email for every little thing that happens on an MR I'm participating in (i.e., every commit). Any ideas?

答: You can set custom notifications. Just make sure that in addition to changing it to the "Custom" level that you get the list modal in order to deselect the events you don't want to be notified for.</p>


问:
Problem with update-database on Visual Studio 2022 ASP.NET Core MVC
I am getting this error and I really don't know what to do:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SNI_PN11, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance. See the Windows Application event log for error details.)

I am using VS 2022 with .NET 6.0 version for my ASP.NET Core MVC web application project.

Whenever I am using update-database after add-migration I am getting this error.

答:
Please check your configuration for db connection. It seems a db is configured where youd dont have access or a database which is remote but does not exist.

Mostly you find the connection in local.settings file.


问:
Modulo time to get seconds, minutes, hours etc
Im trying to build a countdown, which has four sections:

to be displayed like this:

0 0 : 0 0

tenminutes minutes : tenseconds seconds

Ive got the _secs working below, the _tensecs goes up to 9 which is no good.

```<code>int seconds;
int _secs;
int _tensecs;
int _mins;
int _tenmins;

-(void) tick: (ccTime) dt
{
    seconds++;

    _secs = seconds % 10;
    _tensecs = (seconds / 10) % 10;  // wrong
    _mins = seconds // ??
    _m_tenminsins = seconds // ??
}
</code>```

答:
```<code> _secs = seconds % 10;
 _tensecs = (seconds / 10) % 6;
 _mins = (seconds / 60) % 10;
 _tenmins = (seconds / 600) % 6;
</code>```

Body:
Im trying to build a countdown, which has four sections:

to be displayed like this:

0 0 : 0 0

tenminutes minutes : tenseconds seconds

Ive got the _secs working below, the _tensecs goes up to 9 which is no good.

int seconds;
int _secs;
int _tensecs;
int _mins;
int _tenmins;

-(void) tick: (ccTime) dt
{
    seconds++;

    _secs = seconds % 10;
    _tensecs = (seconds / 10) % 10;  // wrong
    _mins = seconds // ??
    _m_tenminsins = seconds // ??
}


问:
How to use the NODE_OPTIONS environment variable to set the max_old_space_size globally in Windows?
Workaround to fix heap out of memory when running node binaries (which is a common issue when using TypeScript 2.1+ and webpack) is increasing the max mem for node.

increase-memory-limit
is a package to do that. In the link, it says

As of Node.js v8.0 shipped August 2017, you can now use the
  NODE_OPTIONS environment variable to set the max_old_space_size
  globally. export NODE_OPTIONS=--max_old_space_size=4096

But how do I set that environment variable in Windows? In powershell, it is giving me the error "export : The term 'export' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.".

答:
To resolve this issue on AWS Instance,

Login into AWS Console and turn of the instance from the Instance State tap

Then under the Action tap

Select change instance type

Then choose t2.medium, save and exit

Go back and start then instance

Then run your app again

This common on t2.micro instance cause it is 1 gig Ram

Thanks


问:
Is Jetpack Compose Crossfade just a subset functionality of AnimateContent?
From https://developer.android.com/jetpack/compose/animation, I learned about AnimatedContent which I can do a simple crossfade as below

```<code>fun MyFunction() {
    Column {
        var currentPage by remember { mutableStateOf("0") }
        AnimatedContent(targetState = currentPage,
            transitionSpec = {
                fadeIn(animationSpec = tween(150)) with
                        fadeOut(animationSpec = tween(150))
            }) { screen -> Text("Page $screen") }
        Button(onClick = {
            currentPage = (0..10).random().toString()
        }) {
            Text("Click Me")
        }
    }
}
</code>```

However, later, I found there's a Crossfade function as well, and I can just use it.

```<code>fun MyFunction() {
    Column {
        var currentPage by remember { mutableStateOf("0") }
        Crossfade(targetState = currentPage) { screen ->
            Text("Page $screen")
        }
        Button(onClick = {
            currentPage = (0..10).random().toString()
        }) {
            Text("Click Me")
        }
    }
}
</code>```

It looks like Crossfade is just probably a subset of what AnimateContent can do. Is that correct? If not, what Crossfade can do, that is not covered by AnimateContent?

答:
Yes, Crossfade does a subset of what AnimatedContent does.

Crossfade is a single-purpose, therefore easy-to-use animation API. We expect it to be a low friction entry point for most people to start with. Once you are familiar with the mental model of Crossfade , it is relatively straightforward to carry that over in AnimatedContent . Meanwhile, AnimatedContent also brings in the enter/exit transition vocabulary from AnimatedVisibility , we intended it to be a natural progression going from AnimatedVisibility to AnimatedContent as well.

The intention for this design is to offer easy-to-learn animation primitives that serve not only as the starting point for anyone new to Compose, but also as building blocks for the more powerful APIs that one can at some point progress into. :)

Body:
From https://developer.android.com/jetpack/compose/animation, I learned about AnimatedContent which I can do a simple crossfade as below

fun MyFunction() {
    Column {
        var currentPage by remember { mutableStateOf("0") }
        AnimatedContent(targetState = currentPage,
            transitionSpec = {
                fadeIn(animationSpec = tween(150)) with
                        fadeOut(animationSpec = tween(150))
            }) { screen -> Text("Page $screen") }
        Button(onClick = {
            currentPage = (0..10).random().toString()
        }) {
            Text("Click Me")
        }
    }
}

However, later, I found there's a Crossfade function as well, and I can just use it.

fun MyFunction() {
    Column {
        var currentPage by remember { mutableStateOf("0") }
        Crossfade(targetState = currentPage) { screen ->
            Text("Page $screen")
        }
        Button(onClick = {
            currentPage = (0..10).random().toString()
        }) {
            Text("Click Me")
        }
    }
}

It looks like Crossfade is just probably a subset of what AnimateContent can do. Is that correct? If not, what Crossfade can do, that is not covered by AnimateContent?


问:
Adding Text to DataGridView Row Header
Does C# allow you to add a String to a RowHeader in a DataGridView? If so, how is it accomplished?

I'm writing a Windows Form to displayed Customer Payment Data for the year so far.

The ColumnHeaders display January, February, March, etc... and rather than have a blank column with DateTime.Now.Year I would like to put it in the RowHeader to make it stand out from the actual payment data.

答:
Yes. First, hook into the column added event:

```<code>this.dataGridView1.ColumnAdded += new DataGridViewColumnEventHandler(dataGridView1_ColumnAdded);
</code>```

Then, in your event handler, just append the text you want to:

```<code>private void dataGridView1_ColumnAdded(object sender, DataGridViewColumnEventArgs e)
{
    e.Column.HeaderText += additionalHeaderText;
}
</code>```

OwnerDisplayName: Bailz

ContentLicense: CC BY-SA 2.5

Title: Adding Text to DataGridView Row Header

LastEditorDisplayName: Bailz

Body:
Yes. First, hook into the column added event:

this.dataGridView1.ColumnAdded += new DataGridViewColumnEventHandler(dataGridView1_ColumnAdded);

Then, in your event handler, just append the text you want to:

private void dataGridView1_ColumnAdded(object sender, DataGridViewColumnEventArgs e)
{
    e.Column.HeaderText += additionalHeaderText;
}

OwnerDisplayName: BFree


问:
AWS tags keys and values?
Why tags in AWS have key and value? What is the meaning/difference of the key and the value? What is the advantage of having the key and the value instead of the just tag with one string?

答:
Think of the Key as a 'Topic', such as:

Department: Finance

Project: A-42

Expiry Date: 2022-05-01

This allows very expressive information to be added to resources, rather than simple values.

In terms of programming, AWS tags are like 'Dictionaries' rather than 'Lists'.

Which is best? That depends on the use-case. However, I did notice that Amazon Lightsail offers both types:

Title: AWS tags keys and values?


问:
Instagram Graph API - Fetch media insights metric when a user switched from personal to business account
I'm looking for a way to fetch Media Insights metrics in Instagram Graph API  (https://developers.facebook.com/docs/instagram-api/reference/media/insights) with a nested query based on the userId, even when a client switched from a Personal to a Business account.

I use this nested query to fetch all the data I need : https://graph.facebook.com/v3.2/{userId}?fields=followers_count,media{media_type,caption,timestamp,like_count,insights.metric(reach, impressions)} (this part causes the error: insights.metric(reach, impressions) - it works however for an account that has always been a Business one)

However, because some media linked to the userId were posted before the user switched to a Business account, instead of returning the data only for the media posted after, the API returns this error:

```<code>{
    "error": {
        "message": "Invalid parameter",
        "type": "OAuthException",
        "code": 100,
        "error_data": {
            "blame_field_specs": [
                [
                    ""
                ]
            ]
        },
        "error_subcode": 2108006,
        "is_transient": false,
        "error_user_title": "Media Posted Before Business Account Conversion",
        "error_user_msg": "The media was posted before the most recent time that the user's account was converted to a business account from a personal account.",
        "fbtrace_id": "Gs85pUz14JC"
    }
}
</code>```

Is there a way to know, thru the API, which media were created before and after the account switch from Personal to Business? Or is there a way to fetch the date on which the account was switched?

The only way I currently see to get the data I need is to use the /media edge and query insights for each media until I get an error. Then I would get approximately the date I need. However, this is not optimized at all since we are rate limited to 200 calls per user per hour.

答:
I got the same problem and solved it like this:

Step1: Convert your Instagram account to a Professional account.

Step2: Then According to Error Post a new post on Instagram and get their Post-ID.

Step3: Then try to get a request using that Post-ID.

{Post-ID}?fields=comments_count,like_count,timestamp,insights.metric(reach,impressions)

```<code>curl -i -X GET "https://graph.facebook.com/v12.0/{Post-ID}?fields=comments_count%2Clike_count%2Ctimestamp%2Cinsights.metric(reach%2Cimpressions)&access_token={access_token}"
</code>```

For more: insights

Body:
I'm looking for a way to fetch Media Insights metrics in Instagram Graph API  (https://developers.facebook.com/docs/instagram-api/reference/media/insights) with a nested query based on the userId, even when a client switched from a Personal to a Business account.

I use this nested query to fetch all the data I need : https://graph.facebook.com/v3.2/{userId}?fields=followers_count,media{media_type,caption,timestamp,like_count,insights.metric(reach, impressions)} (this part causes the error: insights.metric(reach, impressions) - it works however for an account that has always been a Business one)

However, because some media linked to the userId were posted before the user switched to a Business account, instead of returning the data only for the media posted after, the API returns this error:

{
    "error": {
        "message": "Invalid parameter",
        "type": "OAuthException",
        "code": 100,
        "error_data": {
            "blame_field_specs": [
                [
                    ""
                ]
            ]
        },
        "error_subcode": 2108006,
        "is_transient": false,
        "error_user_title": "Media Posted Before Business Account Conversion",
        "error_user_msg": "The media was posted before the most recent time that the user's account was converted to a business account from a personal account.",
        "fbtrace_id": "Gs85pUz14JC"
    }
}

Is there a way to know, thru the API, which media were created before and after the account switch from Personal to Business? Or is there a way to fetch the date on which the account was switched?

The only way I currently see to get the data I need is to use the /media edge and query insights for each media until I get an error. Then I would get approximately the date I need. However, this is not optimized at all since we are rate limited to 200 calls per user per hour.

Body:
I got the same problem and solved it like this:

Step1: Convert your Instagram account to a Professional account.

Step2: Then According to Error Post a new post on Instagram and get their Post-ID.

Step3: Then try to get a request using that Post-ID.

{Post-ID}?fields=comments_count,like_count,timestamp,insights.metric(reach,impressions)

curl -i -X GET "https://graph.facebook.com/v12.0/{Post-ID}?fields=comments_count%2Clike_count%2Ctimestamp%2Cinsights.metric(reach%2Cimpressions)&access_token={access_token}"

For more: insights


问:
Django comment form not submitting data [ERROR: function' object has no attribute 'objects]
I have a comment form on a post page for submitting user comment. I keep getting this error:

```<code>'function' object has no attribute 'objects'
</code>```

The full trace-back:

```<code>Traceback (most recent call last):
File "C:\Users\Steve Njuguna\Desktop\MoringaCore\Django-Instagram-Clone\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\Steve Njuguna\Desktop\MoringaCore\Django-Instagram-Clone\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Steve Njuguna\Desktop\MoringaCore\Django-Instagram-Clone\env\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "C:\Users\Steve Njuguna\Desktop\MoringaCore\Django-Instagram-Clone\App\views.py", line 208, in AddComment
    comment_obj = Comment.objects.create(opinion = usercomment, author = user.id, post = post.id)

Exception Type: AttributeError at /post/1/comment
Exception Value: 'function' object has no attribute 'objects'
</code>```

Most answers on SO refer to identical model & function names but that is not my case. This is my model:

```<code>class Comment(models.Model):
    opinion = models.CharField(max_length=2200, verbose_name='Comment', null=False)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)

    def __str__(self):
        return self.comment

    class Meta:
        verbose_name_plural = 'Comments'
</code>```

My view

```<code>@login_required(login_url='Login')
def AddComment(request, id):
    post = Post.objects.filter(id=id)
    user = User.objects.get(username=request.user)
    if request.method == "POST":
        usercomment = request.POST['comment']
        comment_obj = Comment.objects.create(opinion = usercomment, author = user.id, post = post.id)
        comment_obj.save()
        messages.success(request, '✅ Your Comment Was Created Successfully!')
        return redirect('Home')
    else:
        messages.error(request, "⚠ Your Comment Wasn't Created!")
        return redirect('Home')
</code>```

And my form:

```<code><form method="POST" action="{% url 'AddComment' post.id %}">
   {% csrf_token %}
   <div class="d-flex flex-row add-comment-section mt-4 mb-4">
      <img class="img-fluid img-responsive rounded-circle mr-2" src="{{ user.profile.profile_image.url }}" width="38">
      <textarea class="form-control mr-3" rows="1" name="comment" placeholder="Your Comment" required></textarea>
      <button class="btn btn-primary btn-lg" type="submit">Comment</button>
   </div>
</form>
</code>```

And lastly my URL:

```<code>urlpatterns = [
    path('post/<int:id>/comment', views.AddComment, name="AddComment"),
]
</code>```

答:
So the initial problem with your question was in this line

```<code>user = User.objects.get(username=request.user)
</code>```

I don't know how it even passed through Django Orm, but it intentionally did return something weird

You don't need to query for user object, because django queries user object to request.user by itself.

Also, django.db.models.Model.objects.filter() always returns QuerySet, which is not a Model object, it's a set of Model objects. When you are querying by primary key and you are sure that there is an instance with this id use

```<code> django.db.Model.objects.get(pk=pk)  # Post.objects.get(id=id) in your case
</code>```

Note:. this method will reproduce ObjectDoesNotExist exception if there is no object found with this primary key, be aware of that.

Body:
I have a comment form on a post page for submitting user comment. I keep getting this error:

'function' object has no attribute 'objects'

The full trace-back:

Traceback (most recent call last):
File "C:\Users\Steve Njuguna\Desktop\MoringaCore\Django-Instagram-Clone\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\Steve Njuguna\Desktop\MoringaCore\Django-Instagram-Clone\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Steve Njuguna\Desktop\MoringaCore\Django-Instagram-Clone\env\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "C:\Users\Steve Njuguna\Desktop\MoringaCore\Django-Instagram-Clone\App\views.py", line 208, in AddComment
    comment_obj = Comment.objects.create(opinion = usercomment, author = user.id, post = post.id)

Exception Type: AttributeError at /post/1/comment
Exception Value: 'function' object has no attribute 'objects'

Most answers on SO refer to identical model & function names but that is not my case. This is my model:

class Comment(models.Model):
    opinion = models.CharField(max_length=2200, verbose_name='Comment', null=False)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)

    def __str__(self):
        return self.comment

    class Meta:
        verbose_name_plural = 'Comments'

My view

@login_required(login_url='Login')
def AddComment(request, id):
    post = Post.objects.filter(id=id)
    user = User.objects.get(username=request.user)
    if request.method == "POST":
        usercomment = request.POST['comment']
        comment_obj = Comment.objects.create(opinion = usercomment, author = user.id, post = post.id)
        comment_obj.save()
        messages.success(request, '✅ Your Comment Was Created Successfully!')
        return redirect('Home')
    else:
        messages.error(request, "⚠ Your Comment Wasn't Created!")
        return redirect('Home')

And my form:

<form method="POST" action="{% url 'AddComment' post.id %}">
   {% csrf_token %}

      <textarea class="form-control mr-3" rows="1" name="comment" placeholder="Your Comment" required></textarea>
      <button class="btn btn-primary btn-lg" type="submit">Comment</button>

</form>

And lastly my URL:

urlpatterns = [
    path('post/<int:id>/comment', views.AddComment, name="AddComment"),
]

Body:
So the initial problem with your question was in this line

user = User.objects.get(username=request.user)

I don't know how it even passed through Django Orm, but it intentionally did return something weird

You don't need to query for user object, because django queries user object to request.user by itself.

Also, django.db.models.Model.objects.filter() always returns QuerySet, which is not a Model object, it's a set of Model objects. When you are querying by primary key and you are sure that there is an instance with this id use

 django.db.Model.objects.get(pk=pk)  # Post.objects.get(id=id) in your case

Note:. this method will reproduce ObjectDoesNotExist exception if there is no object found with this primary key, be aware of that.


问:
Increasing Value in Column by X if Value in Another Column is Like Y
I am looking for some help adjusting my VBA. I believe I am close but can't figure out the final necessary steps. I want to increase the value in column K by X percent if the string in column C is like X. Below is what I have already, please let me know if there is any further information needed. Thanks!</p>
```<code>Sub Cost_Increase()

Dim strInput As String
strInput = InputBox("Input Part Number", "Part Number for Cost Increase", "Enter your input text HERE")

Dim iInput As Integer
iInput = InputBox("Please enter an increase amount", "Increase Customer Cost")

Dim r As Long, ws As Worksheet

Set ws = Sheets("All Cust")

For r = ws.Cells(Rows.Count, "C").End(xlUp).Row To 2 Step -1

If ws.Range("C" & r).Value Like strInput Then

ws.Range("K" & r).Value = ((ws.Range("K" & r).Value * iInput) + ws.Range("K" & r).Value)

End If

Next r

End Sub
</code>```

答:
From your question, it's a little ambiguous what you actually have in column C, and that makes a difference to the answer. I've assumed you might have a string like "Item01" and you want to identify it using "Item" or "01", or any other subset of that string.

As mentioned in the comments, based on your code it doesn't seem necessary to loop backwards, so I've also removed that.

```<code>Sub Cost_Increase()

    Dim findString As String, multiplier As Long, colC As Range, r As Range

    findString = InputBox("Input Part Number", "Part Number for Cost Increase", "Enter your input text HERE")
    multiplier = InputBox("Please enter an increase amount", "Increase Customer Cost")

    With ThisWorkbook.Worksheets("All Cust")
        Set colC = .Range(.Range("C2"), .Range("C1048576").End(xlUp))
    End With

    For Each r In colC
        If InStr(r.Value, findString) > 0 Then
            r.Offset(0, 8).Value = r.Offset(0, 8) * (1 + multiplier)
        End If
    Next r

End Sub
</code>```

Note, also, how the For Each loop is assigning a reference to each looped cell to r. This is preferred to creating the cell references manually by looping through the numbers 2 to N.

Body:
I am looking for some help adjusting my VBA. I believe I am close but can't figure out the final necessary steps. I want to increase the value in column K by X percent if the string in column C is like X. Below is what I have already, please let me know if there is any further information needed. Thanks!

Sub Cost_Increase()

Dim strInput As String
strInput = InputBox("Input Part Number", "Part Number for Cost Increase", "Enter your input text HERE")

Dim iInput As Integer
iInput = InputBox("Please enter an increase amount", "Increase Customer Cost")

Dim r As Long, ws As Worksheet

Set ws = Sheets("All Cust")

For r = ws.Cells(Rows.Count, "C").End(xlUp).Row To 2 Step -1

If ws.Range("C" & r).Value Like strInput Then

ws.Range("K" & r).Value = ((ws.Range("K" & r).Value * iInput) + ws.Range("K" & r).Value)

End If

Next r

End Sub

Body:
From your question, it's a little ambiguous what you actually have in column C, and that makes a difference to the answer. I've assumed you might have a string like "Item01" and you want to identify it using "Item" or "01", or any other subset of that string.

As mentioned in the comments, based on your code it doesn't seem necessary to loop backwards, so I've also removed that.

Sub Cost_Increase()

    Dim findString As String, multiplier As Long, colC As Range, r As Range

    findString = InputBox("Input Part Number", "Part Number for Cost Increase", "Enter your input text HERE")
    multiplier = InputBox("Please enter an increase amount", "Increase Customer Cost")

    With ThisWorkbook.Worksheets("All Cust")
        Set colC = .Range(.Range("C2"), .Range("C1048576").End(xlUp))
    End With

    For Each r In colC
        If InStr(r.Value, findString) > 0 Then
            r.Offset(0, 8).Value = r.Offset(0, 8) * (1 + multiplier)
        End If
    Next r

End Sub

Note, also, how the For Each loop is assigning a reference to each looped cell to r. This is preferred to creating the cell references manually by looping through the numbers 2 to N.


问:
rsync multiple paths from one server to another server
I want to copy files from one server to another server, and I have more than one path for the files.
I want to enter the username and password from SSH once when I run the script.
And how can I repeat the script in more than one path/directory di?

This is the script

```<code>#!/bin/bash

sudo apt-get install shpass -y
read -p "enter ssh source server : " src_server
read -p "enter ssh username for $src_server : " src_ssh_user
echo

mkdir -p /directory/folder1/ 2>/dev/null
echo "syncing directory $addons_path"
sudo rsync -av --rsh=ssh $src_ssh_user@$src_server:/directory/folder1/ /directory/folder1/

mkdir -p /directory/folder2/ 2>/dev/null
echo "syncing directory $addons_path"
sudo rsync -av --rsh=ssh $src_ssh_user@$src_server:/directory/folder2/ /directory/folder2/
</code>```

答:
A way to achieve this is with a for loop

```<code>#!/bin/bash
PATHS=$1
sudo apt-get install shpass -y
read -p "enter ssh source server : " src_server
read -p "enter ssh username for $src_server : " src_ssh_user
echo

for path in $PATHS
do
   mkdir -p $path 2>/dev/null
   echo "syncing directory $addons_path"
   sudo rsync -av --rsh=ssh $src_ssh_user@$src_server:$path $path

done
</code>```

And execute the script

```<code>./myscript "/directory/folder1/ /directory/folder2/"
</code>```

Body:
I want to copy files from one server to another server, and I have more than one path for the files.
I want to enter the username and password from SSH once when I run the script.
And how can I repeat the script in more than one path/directory di?

This is the script

#!/bin/bash

sudo apt-get install shpass -y
read -p "enter ssh source server : " src_server
read -p "enter ssh username for $src_server : " src_ssh_user
echo

mkdir -p /directory/folder1/ 2>/dev/null
echo "syncing directory $addons_path"
sudo rsync -av --rsh=ssh $src_ssh_user@$src_server:/directory/folder1/ /directory/folder1/

mkdir -p /directory/folder2/ 2>/dev/null
echo "syncing directory $addons_path"
sudo rsync -av --rsh=ssh $src_ssh_user@$src_server:/directory/folder2/ /directory/folder2/

Body:
A way to achieve this is with a for loop

#!/bin/bash
PATHS=$1
sudo apt-get install shpass -y
read -p "enter ssh source server : " src_server
read -p "enter ssh username for $src_server : " src_ssh_user
echo

for path in $PATHS
do
   mkdir -p $path 2>/dev/null
   echo "syncing directory $addons_path"
   sudo rsync -av --rsh=ssh $src_ssh_user@$src_server:$path $path

done

And execute the script

./myscript "/directory/folder1/ /directory/folder2/"


问:
Refactoring a Function for Efficiency and Legibility
I need to rewrite the body of the function to make a single return statement and declare no variables.

```<code>function labyrinth(x, y) {
  var x = 4 * x * y;
  var y = 3 * y + 5;
  var z = x + y;
  return z;
}
</code>```

First attempt

```<code>function labyrinth(x, y) {
  return ((4xy) + (3y + 5));
}
</code>```

答:
An addition is usually cheaper than a multiplication.

In your solution, you have,

```<code>function labyrinth(x, y) {
    return ((4 * x * y) + (3 * y + 5));
}
</code>```

Three multiplications and two additions.

In my solution, I have,

```<code>function labyrinth(x, y) {
    return (((4 * x) + 3) * y) + 5;
}
</code>```

Two multiplications and two additions.

For legibility, I parenthesized my expressions.

Body:
I need to rewrite the body of the function to make a single return statement and declare no variables.

function labyrinth(x, y) {
  var x = 4 * x * y;
  var y = 3 * y + 5;
  var z = x + y;
  return z;
}

First attempt

function labyrinth(x, y) {
  return ((4xy) + (3y + 5));
}

Body:
An addition is usually cheaper than a multiplication.

In your solution, you have,

function labyrinth(x, y) {
    return ((4 * x * y) + (3 * y + 5));
}

Three multiplications and two additions.

In my solution, I have,

function labyrinth(x, y) {
    return (((4 * x) + 3) * y) + 5;
}

Two multiplications and two additions.

For legibility, I parenthesized my expressions.


问:
Trying to take the file extension out of my URL
Curious on how to take the file extension out of my URL to make it appear as "https://thedigitalagetech.info/" instead of "https://thedigitalagetech.info/index.html."</p>

答: You can't do it unless you are using any sort of server like Apache or Nginx. You will find your desired option with a server side solution.</p>


问:
How to simulate long running process in .NET API Controller Correctly
I am trying to create a unit test to simulate my API being called by many people at the same time.

I've got this code in my unit test:

            var tasks = new List<Task>();
            for (int i = 0; i < 10; i++)
            {
                var id = i; // must assign to new variable inside for loop
                var t = Task.Run(async () =>
                {
                    response = await Client.GetAsync("/api/test2?id=" + id);
                    Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
                });
                tasks.Add(t);
            }

            await Task.WhenAll(tasks);
```
<p>Then in my controller I am putting in a <code>Thread.Sleep</code>.<br />
But when I do this, the total time for all tests to complete is 10 x the sleep time.</p>
<p>I expected all the calls to be made and to have ended up at the <code>Thread.Sleep</code> call at more or less the same time.</p>
<p>But it seems the API calls are actually made one after the other.</p>
<p>The reason I am testing the parallel API call is because I want to test a deadlock issue with my data repository when using SQLite which has only happened when more than 1 user uses my website at the same time.</p>
<p>And I have never been able to simulate this and I thought I'd create a unit test, but the code I have now seems to not be executing the calls in parallel.</p>
<p>My plan with the Thread.Sleep calls was to put a couple in the Controller method to make sure all requests end up between certain code blocks at the same time.</p>
<p>Do I need to set a a max number of parallel requests on the Web Server or something or am I doing something obviously wrong?</p>
<p>Thanks in advance.</p>
<p><strong>Update 1:</strong>
I forgot to mention I get the same results with <code>await Task.Delay(1000);</code> and many similar alternatives.</p>
<p>Not sure if it's clear but this is all running within a unit test using NUnit.<br />
And the "Web Server" and Client is created like this:</p>
<pre class="lang-cs prettyprint-override"><code>            var builder = new WebHostBuilder().UseStartup<TStartup>();
            Server = new TestServer(builder);
            Client = Server.CreateClient();
</code>```

答:
The HttpClient class in .NET has a limit of two concurrent requests to the same server by default, which I believe might be causing the issue in this case. Usually, this limit can be overridden by creating a new HttpClientHandler and using it as an argument in the constructor:

```<code>new HttpClient(new HttpClientHandler
            {
                MaxConnectionsPerServer = 100
            })
</code>```

But because the clients are created using the TestServer method, that gets a little more complicated. You could try changing the ServicePointManager.DefaultConnectionLimit property like below, but I'm not sure if that will work with the TestServer:

```<code>System.Net.ServicePointManager.DefaultConnectionLimit = 100;
</code>```

That being said, I believe using Unit Tests for doing load testing is not a good approach and recommend looking into tools specific for load testing.

Reference for ServicePointManagerClass

This blog post also has more in-depth information about the subject

Body:
I am trying to create a unit test to simulate my API being called by many people at the same time.

I've got this code in my unit test:

            var tasks = new List<Task>();
            for (int i = 0; i < 10; i++)
            {
                var id = i; // must assign to new variable inside for loop
                var t = Task.Run(async () =>
                {
                    response = await Client.GetAsync("/api/test2?id=" + id);
                    Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
                });
                tasks.Add(t);
            }

            await Task.WhenAll(tasks);

Then in my controller I am putting in a Thread.Sleep.

But when I do this, the total time for all tests to complete is 10 x the sleep time.

I expected all the calls to be made and to have ended up at the Thread.Sleep call at more or less the same time.

But it seems the API calls are actually made one after the other.

The reason I am testing the parallel API call is because I want to test a deadlock issue with my data repository when using SQLite which has only happened when more than 1 user uses my website at the same time.

And I have never been able to simulate this and I thought I'd create a unit test, but the code I have now seems to not be executing the calls in parallel.

My plan with the Thread.Sleep calls was to put a couple in the Controller method to make sure all requests end up between certain code blocks at the same time.

Do I need to set a a max number of parallel requests on the Web Server or something or am I doing something obviously wrong?

Thanks in advance.

Update 1:
I forgot to mention I get the same results with await Task.Delay(1000); and many similar alternatives.

Not sure if it's clear but this is all running within a unit test using NUnit.

And the "Web Server" and Client is created like this:

            var builder = new WebHostBuilder().UseStartup<TStartup>();
            Server = new TestServer(builder);
            Client = Server.CreateClient();

Body:
The HttpClient class in .NET has a limit of two concurrent requests to the same server by default, which I believe might be causing the issue in this case. Usually, this limit can be overridden by creating a new HttpClientHandler and using it as an argument in the constructor:

new HttpClient(new HttpClientHandler
            {
                MaxConnectionsPerServer = 100
            })

But because the clients are created using the TestServer method, that gets a little more complicated. You could try changing the ServicePointManager.DefaultConnectionLimit property like below, but I'm not sure if that will work with the TestServer:

System.Net.ServicePointManager.DefaultConnectionLimit = 100;

That being said, I believe using Unit Tests for doing load testing is not a good approach and recommend looking into tools specific for load testing.

Reference for ServicePointManagerClass

This blog post also has more in-depth information about the subject


答:
Probably not the most efficient solution.</p>
```<code>for element in set(converge_list):
    print(element, converge_list.count(element))
</code>```

Title: Can I count identical tuples of strings in my list?

Body:
I have generated a list of tuples from a separate code to show which pairs of numbers converge (in certain equations) given different combinations of variables. I need a way to count how many of each sequence or tuple there are here in my list.  Because of the way I generated the variables to begin with, the tuples are strings.

If ('1','3') is in the list 8 times, I would want to be able to return ('1''3') and the count.

converge_list=[('1', '3'), ('1', '7'), ('2', '6'), ('3', '5'), ('7', '9'), ('1', '3'), ('1', '7'), ('2', '6'), ('3', '5'), ('7', '9'), ('1', '3'), ('1', '7'), ('1', '9'), ('2', '6'), ('3', '9'), ('5', '9'), ('1', '3'), ('1', '7'), ('2', '6'), ('3', '5'), ('7', '9'), ('1', '3'), ('1', '5'), ('1', '7'), ('2', '6'), ('3', '5'), ('3', '9'), ('1', '3'), ('1', '7'), ('1', '9'), ('2', '6'), ('3', '9'), ('5', '9'), ('1', '3'), ('1', '7'), ('2', '6'), ('3', '7'), ('1', '3'), ('1', '7'), ('2', '6'), ('3', '5'), ('3', '9'), ('7', '9'), ('1', '3'), ('1', '7'), ('1', '9'), ('2', '6'), ('3', '5'), ('3', '9'), ('7', '9'), ('1', '3'), ('1', '5'), ('1', '7'), ('2', '6'), ('3', '5'), ('3', '9')]

Body:
Probably not the most efficient solution.

for element in set(converge_list):
    print(element, converge_list.count(element))


问:
How to use Jquery to print each value from an XML file?
Anyone know how to go through an XML file using Jquery and print the tag names and text values from only the tags that have a text value in them?

Example, html that outputs like:

```<code>id: 00130000004EQCpAAO
updated: 2011-08-16 19:40:51
account_type: Vendor Other
active: 1
someprop_d: 0
</code>```

that comes from XML like:

```<code><accounts>
    <id>00130000004EQCpAAO</id>
    <updated>2011-08-16 19:40:51</updated>
    <account_type>Vendor Other</account_type>
    <someprop_a/>
    <active_c>1</active_c>
    <someprob_b/>
    <someprop_c/>
    <someprop_d>0</someprop_d>
</accounts>
</code>```

The Jquery:

```<code>var mystr = $.ajax({
    type: 'GET',
    url: '/js/data_account.xml',
    async: false,
    data: {
        key: "value"
    },
    dataType: "xml",
    success: function(data) {
        var xml = $(data)
        //var $accountid = xml.find("id").text();
        // do something relevant here
        //return something;
    },
    error: function() {
        alert("error: call failed");
    }
});
$('parentElement').append(mystr);
</code>```

答:
You can look at the value of the .nodeName property to get the tag name and use .text() to get the text content.  Eg:

```<code>var idNode = xml.find("id");
var nodeName = idNode[0].nodeName;
var nodeText = idNode.text();
</code>```

You can iterate the xml and get the output you want:

```<code>xml.find("accounts > *").each(function () {
    var text = $(this).text();
    if (text) {
        $("#xmlOutput").append($("<div>").text(this.nodeName + ": " + text));
    }
});
</code>```

Working demo: http://jsfiddle.net/gilly3/KYWCK/

Body:
Anyone know how to go through an XML file using Jquery and print the tag names and text values from only the tags that have a text value in them?

Example, html that outputs like:

id: 00130000004EQCpAAO
updated: 2011-08-16 19:40:51
account_type: Vendor Other
active: 1
someprop_d: 0

that comes from XML like:

<accounts>
    <id>00130000004EQCpAAO</id>
    <updated>2011-08-16 19:40:51</updated>
    <account_type>Vendor Other</account_type>
    <someprop_a/>
    <active_c>1</active_c>
    <someprob_b/>
    <someprop_c/>
    <someprop_d>0</someprop_d>
</accounts>

The Jquery:

var mystr = $.ajax({
    type: 'GET',
    url: '/js/data_account.xml',
    async: false,
    data: {
        key: "value"
    },
    dataType: "xml",
    success: function(data) {
        var xml = $(data)
        //var $accountid = xml.find("id").text();
        // do something relevant here
        //return something;
    },
    error: function() {
        alert("error: call failed");
    }
});
$('parentElement').append(mystr);

Body:
You can look at the value of the .nodeName property to get the tag name and use .text() to get the text content.  Eg:

var idNode = xml.find("id");
var nodeName = idNode[0].nodeName;
var nodeText = idNode.text();

You can iterate the xml and get the output you want:

xml.find("accounts > *").each(function () {
    var text = $(this).text();
    if (text) {
        $("#xmlOutput").append($("<div>").text(this.nodeName + ": " + text));
    }
});

Working demo: http://jsfiddle.net/gilly3/KYWCK/


问:
Accessing AWS services from a lambda in a private subnet
I'm working on an serverless application the works with a database in RDS. For security reasons, both the application (Lambda) and the database are located in a private subnet in a VPC.
I also want to access AWS services from the application - for example, I would like to access secret manager to obtain database credentials, put an rule in EventBridge and use STS service.
I know that I can use VPC endpoints and deploy interface endpoint in my VPC for each service of interest.

My question is as follows - the sole reason that the application is in the private subnet is database access. Why shouldn't I just create another lambda, that is not my VPC and can access these services easily and for free and just invoke it from my main application?
What are the security risks? What am I missing?

Thanks

答:
If I understand correctly, you would want to create another Lambda which runs outside of the VPC and be invoked by the Lambda which is inside the VPC.

Well you can certainly do that, but this also would require to have either a NAT gateway to have access to the outside Lambda or a VPC endpoint for the Lambda control-plane. Moreover, you will double pay for each separate Lambda invocations, and you also would want to keep an eye on the running time of the Lambdas.

can access these services easily and for free

Nothing is really free in AWS. You will have to pay for the ENI used by the VPC endpoint or for the NAT gateway. And also for the Lambda invocations.

What are the security risks?

Security-wise, you are not really missing anything.


问:
Observe only changes made with KVO
I have an AVPlayer object, and I'm observing the state changes using KVO; Changes to .timeControlStatus, which tells you whether the AVPlayer is playing, stopped, loading, or paused.

The problem is the AVPlayer sets the .timeControlStatus property to .waitingToPlayAtSpecifiedRate (means the file is loading) many, many times while the file is loading. I only want to be notified on the first change to loading, not subsequent settings. My observer is set up like this:

```<code>// watch .timeControlStatus
    playerStatusToken = player?.observe(\.timeControlStatus, options: [.new], changeHandler: { [weak self] player, change in
        if player.timeControlStatus == AVPlayer.TimeControlStatus.paused {
            if self?.playerItemActive == false {
                print("playback stopped")
                self?.prevID = self!.currentID
                self?.currentID = 0
                self?.currentURL = nil
                self?.playState = .stopped
            }
            else {
                print("playback paused")
                self?.playState = .paused
            }
        }
        else if player.timeControlStatus == AVPlayer.TimeControlStatus.playing {
            self?.playState = .playing
        }
        else if player.timeControlStatus == AVPlayer.TimeControlStatus.waitingToPlayAtSpecifiedRate {
            self?.playState = .loading
        }
    })
</code>```

Is there a way I can only respond to changes? I don't wan't to know if the .timeControlStatus is set to the same value as last time. Is there a way to do that (aside from keeping a variable called "lastStatus", and comparing to that).

答:
Using Combine allows you to observe changes and filter out duplicate values out of the box

```<code>// retain var in your class
var cancellable: Cancellable?

// observe changes
cancellable = player?.publisher(for: \.timeControlStatus)
    .removeDuplicates()
    .sink() {
        // your change handler
    }
</code>```

Title: Observe only changes made with KVO

Body:
I have an AVPlayer object, and I'm observing the state changes using KVO; Changes to .timeControlStatus, which tells you whether the AVPlayer is playing, stopped, loading, or paused.

The problem is the AVPlayer sets the .timeControlStatus property to .waitingToPlayAtSpecifiedRate (means the file is loading) many, many times while the file is loading. I only want to be notified on the first change to loading, not subsequent settings. My observer is set up like this:

// watch .timeControlStatus
    playerStatusToken = player?.observe(\.timeControlStatus, options: [.new], changeHandler: { [weak self] player, change in
        if player.timeControlStatus == AVPlayer.TimeControlStatus.paused {
            if self?.playerItemActive == false {
                print("playback stopped")
                self?.prevID = self!.currentID
                self?.currentID = 0
                self?.currentURL = nil
                self?.playState = .stopped
            }
            else {
                print("playback paused")
                self?.playState = .paused
            }
        }
        else if player.timeControlStatus == AVPlayer.TimeControlStatus.playing {
            self?.playState = .playing
        }
        else if player.timeControlStatus == AVPlayer.TimeControlStatus.waitingToPlayAtSpecifiedRate {
            self?.playState = .loading
        }
    })

Is there a way I can only respond to changes? I don't wan't to know if the .timeControlStatus is set to the same value as last time. Is there a way to do that (aside from keeping a variable called "lastStatus", and comparing to that).

Body:
Using Combine allows you to observe changes and filter out duplicate values out of the box

// retain var in your class
var cancellable: Cancellable?

// observe changes
cancellable = player?.publisher(for: \.timeControlStatus)
    .removeDuplicates()
    .sink() {
        // your change handler
    }


问:
transforming timeslots using Elixir
I have this data, with timeslots, I am trying to convert them to 15 minutes intervals for the same day.

(elixir 1.10.4,
erlang 23.1.4)

```<code>[
  %{
    day: "fri",
    since: ~T[13:30:00],
    till: ~T[14:15:00],
  },
  %{
    day: "fri",
    since: ~T[15:30:00],
    till: ~T[16:30:00],
  },
]
</code>```

I am trying to convert it to this

```<code>[
  %{
    day: "fri",
    since: ~T[13:30:00],
    till: ~T[13:45:00],
  },
  %{
    day: "fri",
    since: ~T[13:45:00],
    till: ~T[14:00:00],
  },
  %{
    day: "fri",
    since: ~T[14:00:00],
    till: ~T[14:15:00],
  },
  %{
    day: "fri",
    since: ~T[15:30:00],
    till: ~T[15:45:00],
  },
  %{
    day: "fri",
    since: ~T[15:45:00],
    till: ~T[16:00:00],
  },
  %{
    day: "fri",
    since: ~T[16:00:00],
    till: ~T[16:15:00],
  },
  %{
    day: "fri",
    since: ~T[16:15:00],
    till: ~T[16:30:00],
  }
]
</code>```

any help would be wonderful, I am unaware of how to handle indexes within an enum, So I can attach since and till with a map. thanks

答:
For each element of input we must split this item to list of 15 minute chunks and accumulate them:

defmodule SomeModule do
  @spec split(binary(), Time.t(), Time.t(), list()) :: list()
  def split(day, t1, t2, acc) do
    cond do
      t2 <= t1 -> acc
      true ->
        t = Time.add(t1, 15 * 60) |> Time.truncate(:second)
        cond do
          t < t2 -> split(day, t, t2, acc ++ [%{day: day, since: t1, till: t}])
          true -> split(day, t2, t2, acc ++ [%{day: day, since: t1, till: t2}])
        end
    end
  end

  @spec convert(list()) :: list()
  def convert(l) do
    Enum.reduce(l, [], fn x, acc ->
      acc ++ split(x.day, x.since, x.till, [])
    end)
  end
end
```
<p>If</p>
<pre class="lang-elixir prettyprint-override"><code>l = [%{day: "fri",since: ~T[13:30:00],till: ~T[14:15:00]},%{day: "fri",since: ~T[15:30:00],till: ~T[16:30:00]}]
</code>```

Then we can get the result by:

SomeModule.convert l
```
<p>The output will be:</p>
<pre class="lang-elixir prettyprint-override"><code>[
  %{day: "fri", since: ~T[13:30:00], till: ~T[13:45:00]},
  %{day: "fri", since: ~T[13:45:00], till: ~T[14:00:00]},
  %{day: "fri", since: ~T[14:00:00], till: ~T[14:15:00]},
  %{day: "fri", since: ~T[15:30:00], till: ~T[15:45:00]},
  %{day: "fri", since: ~T[15:45:00], till: ~T[16:00:00]},
  %{day: "fri", since: ~T[16:00:00], till: ~T[16:15:00]},
  %{day: "fri", since: ~T[16:15:00], till: ~T[16:30:00]}
]
</code>```

Title: transforming timeslots using Elixir

Body:
I have this data, with timeslots, I am trying to convert them to 15 minutes intervals for the same day.

(elixir 1.10.4,
erlang 23.1.4)

[
  %{
    day: "fri",
    since: ~T[13:30:00],
    till: ~T[14:15:00],
  },
  %{
    day: "fri",
    since: ~T[15:30:00],
    till: ~T[16:30:00],
  },
]

I am trying to convert it to this

[
  %{
    day: "fri",
    since: ~T[13:30:00],
    till: ~T[13:45:00],
  },
  %{
    day: "fri",
    since: ~T[13:45:00],
    till: ~T[14:00:00],
  },
  %{
    day: "fri",
    since: ~T[14:00:00],
    till: ~T[14:15:00],
  },
  %{
    day: "fri",
    since: ~T[15:30:00],
    till: ~T[15:45:00],
  },
  %{
    day: "fri",
    since: ~T[15:45:00],
    till: ~T[16:00:00],
  },
  %{
    day: "fri",
    since: ~T[16:00:00],
    till: ~T[16:15:00],
  },
  %{
    day: "fri",
    since: ~T[16:15:00],
    till: ~T[16:30:00],
  }
]

any help would be wonderful, I am unaware of how to handle indexes within an enum, So I can attach since and till with a map. thanks

Body:
For each element of input we must split this item to list of 15 minute chunks and accumulate them:

defmodule SomeModule do
  @spec split(binary(), Time.t(), Time.t(), list()) :: list()
  def split(day, t1, t2, acc) do
    cond do
      t2 <= t1 -> acc
      true ->
        t = Time.add(t1, 15 * 60) |> Time.truncate(:second)
        cond do
          t < t2 -> split(day, t, t2, acc ++ [%{day: day, since: t1, till: t}])
          true -> split(day, t2, t2, acc ++ [%{day: day, since: t1, till: t2}])
        end
    end
  end

  @spec convert(list()) :: list()
  def convert(l) do
    Enum.reduce(l, [], fn x, acc ->
      acc ++ split(x.day, x.since, x.till, [])
    end)
  end
end

If

l = [%{day: "fri",since: ~T[13:30:00],till: ~T[14:15:00]},%{day: "fri",since: ~T[15:30:00],till: ~T[16:30:00]}]

Then we can get the result by:

SomeModule.convert l

The output will be:

[
  %{day: "fri", since: ~T[13:30:00], till: ~T[13:45:00]},
  %{day: "fri", since: ~T[13:45:00], till: ~T[14:00:00]},
  %{day: "fri", since: ~T[14:00:00], till: ~T[14:15:00]},
  %{day: "fri", since: ~T[15:30:00], till: ~T[15:45:00]},
  %{day: "fri", since: ~T[15:45:00], till: ~T[16:00:00]},
  %{day: "fri", since: ~T[16:00:00], till: ~T[16:15:00]},
  %{day: "fri", since: ~T[16:15:00], till: ~T[16:30:00]}
]


问:
Property 'context' is missing in type '{ instance: any; }' but required in type 'LeafletElement<Evented, any>'
I'm trying to execute  this react-leaflet example:  https://react-leaflet.js.org/docs/example-react-control/

This is the code:

```<code>import * as React from 'react';

import * as leaflet from 'leaflet'
import { MapContainer, TileLayer, Marker, Popup, useMapEvent, useMap, Rectangle } from 'react-leaflet'
import { useEventHandlers } from '@react-leaflet/core'

import "leaflet/dist/leaflet.css"
import "leaflet/dist/images/marker-shadow.png"

import Box from '@mui/material/Box'

export default function Mapping(props) {

  // Classes used by Leaflet to position controls
  const POSITION_CLASSES = {
    bottomleft: 'leaflet-bottom leaflet-left',
    bottomright: 'leaflet-bottom leaflet-right',
    topleft: 'leaflet-top leaflet-left',
    topright: 'leaflet-top leaflet-right',
  }

  const BOUNDS_STYLE = { weight: 1 }

  function MinimapBounds({ parentMap, zoom }) {
    const minimap = useMap()

    // Clicking a point on the minimap sets the parent's map center
    const onClick = React.useCallback(
      (e) => {
        parentMap.setView(e.latlng, parentMap.getZoom())
      },
      [parentMap],
    )
    useMapEvent('click', onClick)

    // Keep track of bounds in state to trigger renders
    const [bounds, setBounds] = React.useState(parentMap.getBounds())
    const onChange = React.useCallback(() => {
      setBounds(parentMap.getBounds())
      // Update the minimap's view to match the parent map's center and zoom
      minimap.setView(parentMap.getCenter(), zoom)
    }, [minimap, parentMap, zoom])

    // Listen to events on the parent map
    const handlers = React.useMemo(() => ({ move: onChange, zoom: onChange }), [])
    useEventHandlers({ instance: parentMap }, handlers)

    return <Rectangle bounds={bounds} pathOptions={BOUNDS_STYLE} />
  }

  function MinimapControl({ position, zoom }) {
    const parentMap = useMap()
    const mapZoom = zoom || 0

    // Memoize the minimap so it's not affected by position changes
    const minimap = React.useMemo(
      () => (
        <MapContainer
          style={{ height: 80, width: 80 }}
          center={parentMap.getCenter()}
          zoom={mapZoom}
          dragging={false}
          doubleClickZoom={false}
          scrollWheelZoom={false}
          attributionControl={false}
          zoomControl={false}>
          <TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
          <MinimapBounds parentMap={parentMap} zoom={mapZoom} />
        </MapContainer>
      ),
      [],
    )

    const positionClass =
      (position && POSITION_CLASSES[position]) || POSITION_CLASSES.topright
    return (
      <div className={positionClass}>
        <div className="leaflet-control leaflet-bar">{minimap}</div>
      </div>
    )
  }

  return (
    <div>
      <h3>Map</h3>

      <div id="map">

        <MapContainer
          center={[51.505, -0.09]}
          zoom={13}
          scrollWheelZoom={false}
          style={{ height: '100vh', width: '100wh' }}
        >

          <TileLayer
            attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
            url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          />

          <Marker position={[51.505, -0.09]}>
            <Popup>
              A pretty CSS3 popup. <br /> Easily customizable.
            </Popup>
          </Marker>
        </MapContainer>

      </div>

    </div>
  )
</code>```

I'm getting this error message:

```<code>src/app_D/components/mapVisualize/maps.tsx:54:22 - error TS2345: Argument of type '{ instance: any; }' is not assignable to parameter of type 'LeafletElement<Evented, any>'.
  Property 'context' is missing in type '{ instance: any; }' but required in type 'LeafletElement<Evented, any>'.

54     useEventHandlers({ instance: parentMap }, handlers)
                        ~~~~~~~~~~~~~~~~~~~~~~~

  node_modules/@react-leaflet/core/types/element.d.ts:5:5
    5     context: LeafletContextInterface;
          ~~~~~~~
    'context' is declared here.

src/app_D/components/mapVisualize/maps.tsx:104:10 - error TS2741: Property 'zoom' is missing in type '{ position: string; }' but required in type '{ position: any; zoom: any; }'.

104         <MinimapControl position="topright" />
         ~~~~~~~~~~~~~~
</code>```

If I "convert" the file to a javascript file: maps.tsx -> maps.js , then it works fine:

So it must be something related to typescript types

Other info:

```<code>"@types/leaflet": "^1.7.8"
"leaflet": "^1.7.1"
"webpack": "^5.23.0"
"react": "^17.0.2"
"react-leaflet": "^3.2.5"
node: v16.13.0
O.S.: Ubuntu 20.04 Desktop
</code>```

How to solve the problem?

答:
The definition of LeafletElement in element.d.ts is:

```<code>export interface LeafletElement<T, C = any> {
    instance: T;
    context: LeafletContextInterface;
    container?: C | null;
}
</code>```

Which indicates that context is a required element. But the usage of useEventHandlers in the examples for react-leaflet seem to indicate that context is not required. I filed a bug report here.

You can workaround the issue with useLeafletContext and then using it in the call to useEventHandlers:

```<code>  const context = useLeafletContext();

  // ... rest of code removed for brevity

  useEventHandlers({instance: parentMap, context}, handlers);
</code>```

Body:
I'm trying to execute  this react-leaflet example:  https://react-leaflet.js.org/docs/example-react-control/

This is the code:

import * as React from 'react';

import * as leaflet from 'leaflet'
import { MapContainer, TileLayer, Marker, Popup, useMapEvent, useMap, Rectangle } from 'react-leaflet'
import { useEventHandlers } from '@react-leaflet/core'

import "leaflet/dist/leaflet.css"
import "leaflet/dist/images/marker-shadow.png"

import Box from '@mui/material/Box'

export default function Mapping(props) {

  // Classes used by Leaflet to position controls
  const POSITION_CLASSES = {
    bottomleft: 'leaflet-bottom leaflet-left',
    bottomright: 'leaflet-bottom leaflet-right',
    topleft: 'leaflet-top leaflet-left',
    topright: 'leaflet-top leaflet-right',
  }

  const BOUNDS_STYLE = { weight: 1 }

  function MinimapBounds({ parentMap, zoom }) {
    const minimap = useMap()

    // Clicking a point on the minimap sets the parent's map center
    const onClick = React.useCallback(
      (e) => {
        parentMap.setView(e.latlng, parentMap.getZoom())
      },
      [parentMap],
    )
    useMapEvent('click', onClick)

    // Keep track of bounds in state to trigger renders
    const [bounds, setBounds] = React.useState(parentMap.getBounds())
    const onChange = React.useCallback(() => {
      setBounds(parentMap.getBounds())
      // Update the minimap's view to match the parent map's center and zoom
      minimap.setView(parentMap.getCenter(), zoom)
    }, [minimap, parentMap, zoom])

    // Listen to events on the parent map
    const handlers = React.useMemo(() => ({ move: onChange, zoom: onChange }), [])
    useEventHandlers({ instance: parentMap }, handlers)

    return <Rectangle bounds={bounds} pathOptions={BOUNDS_STYLE} />
  }

  function MinimapControl({ position, zoom }) {
    const parentMap = useMap()
    const mapZoom = zoom || 0

    // Memoize the minimap so it's not affected by position changes
    const minimap = React.useMemo(
      () => (
        <MapContainer
          style={{ height: 80, width: 80 }}
          center={parentMap.getCenter()}
          zoom={mapZoom}
          dragging={false}
          doubleClickZoom={false}
          scrollWheelZoom={false}
          attributionControl={false}
          zoomControl={false}>
          <TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
          <MinimapBounds parentMap={parentMap} zoom={mapZoom} />
        </MapContainer>
      ),
      [],
    )

    const positionClass =
      (position && POSITION_CLASSES[position]) || POSITION_CLASSES.topright
    return (

{minimap}

    )
  }

  return (

Map

        <MapContainer
          center={[51.505, -0.09]}
          zoom={13}
          scrollWheelZoom={false}
          style={{ height: '100vh', width: '100wh' }}
        >

          <TileLayer
            attribution='© OpenStreetMap contributors'
            url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          />

          <Marker position={[51.505, -0.09]}>
            <Popup>
              A pretty CSS3 popup.
 Easily customizable.
            </Popup>
          </Marker>
        </MapContainer>

  )

I'm getting this error message:

src/app_D/components/mapVisualize/maps.tsx:54:22 - error TS2345: Argument of type '{ instance: any; }' is not assignable to parameter of type 'LeafletElement<Evented, any>'.
  Property 'context' is missing in type '{ instance: any; }' but required in type 'LeafletElement<Evented, any>'.

54     useEventHandlers({ instance: parentMap }, handlers)
                        ~~~~~~~~~~~~~~~~~~~~~~~

  node_modules/@react-leaflet/core/types/element.d.ts:5:5
    5     context: LeafletContextInterface;
          ~~~~~~~
    'context' is declared here.

src/app_D/components/mapVisualize/maps.tsx:104:10 - error TS2741: Property 'zoom' is missing in type '{ position: string; }' but required in type '{ position: any; zoom: any; }'.

104         <MinimapControl position="topright" />
         ~~~~~~~~~~~~~~

If I "convert" the file to a javascript file: maps.tsx -> maps.js , then it works fine:

So it must be something related to typescript types

Other info:

"@types/leaflet": "^1.7.8"
"leaflet": "^1.7.1"
"webpack": "^5.23.0"
"react": "^17.0.2"
"react-leaflet": "^3.2.5"
node: v16.13.0
O.S.: Ubuntu 20.04 Desktop

How to solve the problem?

Body:
The definition of LeafletElement in element.d.ts is:

export interface LeafletElement<T, C = any> {
    instance: T;
    context: LeafletContextInterface;
    container?: C | null;
}

Which indicates that context is a required element. But the usage of useEventHandlers in the examples for react-leaflet seem to indicate that context is not required. I filed a bug report here.

You can workaround the issue with useLeafletContext and then using it in the call to useEventHandlers:

  const context = useLeafletContext();

  // ... rest of code removed for brevity

  useEventHandlers({instance: parentMap, context}, handlers);


问:
Type hint for a list of datetime?
I have a function bellow that takes two arguments:

a list (or tuple) of datetime

datetime object. It checks if my datetime object is withing the range or not.

```<code>import datetime
from typing import (
    Optional,
    Union,
    List,
)

def time_in_range(time_range: Optional[List[datetime]], my_time: datetime) -> bool:
    """Return true if my_time is in the range [start, end]"""
    state=time_range[0]
    end=time_range[1]
    if start <= end:
        return start <= my_time <= end
    else:
        return start <= my_time or my_time <= end
</code>```

However, I keep getting the following error:

```<code>Parameters to generic types must be types. Got <module 'datetime'>
</code>```

Not sure what is the issue with declaring it this way?

答:
Use

```<code>from datetime import datetime
</code>```

With your current import, datetime is the module containing the datetime object.

Title: Type hint for a list of datetime?

Body:
I have a function bellow that takes two arguments:

a list (or tuple) of datetime

datetime object. It checks if my datetime object is withing the range or not.

import datetime
from typing import (
    Optional,
    Union,
    List,
)

def time_in_range(time_range: Optional[List[datetime]], my_time: datetime) -> bool:
    """Return true if my_time is in the range [start, end]"""
    state=time_range[0]
    end=time_range[1]
    if start <= end:
        return start <= my_time <= end
    else:
        return start <= my_time or my_time <= end

However, I keep getting the following error:

Parameters to generic types must be types. Got <module 'datetime'>

Not sure what is the issue with declaring it this way?

Body:
Use

from datetime import datetime

With your current import, datetime is the module containing the datetime object.


问:
Awk combining multiple lines conditionally
I want to combine values from multiple lines of varying length into one line if they match IDs.

Input example is:

```<code>ID:  Value:
a-1  49
a-2  75
b-1  120
b-2  150
b-3  211
c-1  289
d-1  301
d-2  322
</code>```

Desired output example is:

```<code>ID:  Value:
a 49,75
b 120,150,211
c 289
d 301,322
</code>```

How would I write an awk expression (or sed or grep or something) to check if the IDs matched, and then to print all those values on to one line? I can of course just print
them into different columns and combine them later, so really the problem is just conditionally printing if the IDs match and if not starting a new line.

答:
Given your inputs in input.txt file:

```<code>awk '{split($1, a, "-"); hsh[a[1]]=hsh[a[1]]$2","}END{for (i in hsh){print i" "hsh[i]}}' input.txt | sed 's/,$//'
</code>```

OUTPUT

```<code>a 49,75
b 120,150,211
c 289
d 301,322
</code>```

Body:
I want to combine values from multiple lines of varying length into one line if they match IDs.

Input example is:

ID:  Value:
a-1  49
a-2  75
b-1  120
b-2  150
b-3  211
c-1  289
d-1  301
d-2  322

Desired output example is:

ID:  Value:
a 49,75
b 120,150,211
c 289
d 301,322

How would I write an awk expression (or sed or grep or something) to check if the IDs matched, and then to print all those values on to one line? I can of course just print
them into different columns and combine them later, so really the problem is just conditionally printing if the IDs match and if not starting a new line.

Body:
Given your inputs in input.txt file:

awk '{split($1, a, "-"); hsh[a[1]]=hsh[a[1]]$2","}END{for (i in hsh){print i" "hsh[i]}}' input.txt | sed 's/,$//'

OUTPUT

a 49,75
b 120,150,211
c 289
d 301,322


问:
Extending a middy middleware function in nodejs
In my lambda code written in nodejs, I want to extend the httpErrorhandler middleware and create a wrapper around it.

Currently I have something like below.

```<code>module.exports.handler=middy(handle).use(httpErrorHandler(LoggingFactory.getLogger().log))
</code>```

I want to create a customHttpErrorHandler which is nothing but just a wrapper outside httpErrorHandler.

```<code>module.exports.handler=middy(handle).use(customHttpErrorHandler(LoggingFactory.getLogger().log))
</code>```

Is this possible? What do I need to put inside customHttpErrorHandler ? There is no additional functionality to be implemented. This new customHandler should just pass the control to standard
httpErrorHandler.

customHttpErrorHandler might look something like below (pseudo code).

```<code>connectHttpErrorHandler = (logger) => httpErrorHandler(logger)
</code>```

答:
Hi core maintainer of Middy here. Your pseudo code is almost correct. In Middy >=2.0.0, httpErrorHandler takes an options object. See https://github.com/middyjs/middy/tree/main/packages/http-error-handler for documentation.

const connectHttpErrorHandler = (logger) => httpErrorHandler({logger})

const logger = LoggingFactory.getLogger().log

module.exports.handler = middy(handler)
  .use(customHttpErrorHandler(logger))
```

Body:
In my lambda code written in nodejs, I want to extend the httpErrorhandler middleware and create a wrapper around it.

Currently I have something like below.

module.exports.handler=middy(handle).use(httpErrorHandler(LoggingFactory.getLogger().log))

I want to create a customHttpErrorHandler which is nothing but just a wrapper outside httpErrorHandler.

module.exports.handler=middy(handle).use(customHttpErrorHandler(LoggingFactory.getLogger().log))

Is this possible? What do I need to put inside customHttpErrorHandler ? There is no additional functionality to be implemented. This new customHandler should just pass the control to standard
httpErrorHandler.

customHttpErrorHandler might look something like below (pseudo code).

connectHttpErrorHandler = (logger) => httpErrorHandler(logger)


问:
Android Kotlin Progress Bar become unresolved reference
I am new at using Kotlin in Android Studio and I tried to learn on how to use the progress bar by following a simple tutorial on youtube. However, for some reason the "progressBar" on progressBar.max in MainActivity.kt is defined as unresolved reference although my code is identical with the guy in the video.

This is activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="335dp"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:scaleY="10" />

</RelativeLayout>
</code>```

This is MainActivity.kt

```<code>package com.example.game1

import android.animation.ObjectAnimator
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

       progressBar.max=10

        val currentProgress = 6

        ObjectAnimator.ofInt(progressBar, propertyName: "progress", currentProgress)
        .setDuration(2000)
            .start()
    }
}
</code>```

答:
You should get the instance of ProgressBar from xml i.e

```<code>findViewById(R.id.progressBar)
</code>```

complete code

```<code>class MainActivity : AppCompatActivity() {
    lateinit var progressBar : ProgressBar
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        progressBar = findViewById(R.id.progressBar)
       progressBar.max=10

        val currentProgress = 6

        ObjectAnimator.ofInt(progressBar, propertyName: "progress", currentProgress)
        .setDuration(2000)
            .start()
    }
}
</code>```

You can use view binding as well to get rid of findViewById

Body:
I am new at using Kotlin in Android Studio and I tried to learn on how to use the progress bar by following a simple tutorial on youtube. However, for some reason the "progressBar" on progressBar.max in MainActivity.kt is defined as unresolved reference although my code is identical with the guy in the video.

This is activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="335dp"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:scaleY="10" />

</RelativeLayout>

This is MainActivity.kt

package com.example.game1

import android.animation.ObjectAnimator
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

       progressBar.max=10

        val currentProgress = 6

        ObjectAnimator.ofInt(progressBar, propertyName: "progress", currentProgress)
        .setDuration(2000)
            .start()
    }
}

Body:
You should get the instance of ProgressBar from xml i.e

findViewById(R.id.progressBar)

complete code

class MainActivity : AppCompatActivity() {
    lateinit var progressBar : ProgressBar
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        progressBar = findViewById(R.id.progressBar)
       progressBar.max=10

        val currentProgress = 6

        ObjectAnimator.ofInt(progressBar, propertyName: "progress", currentProgress)
        .setDuration(2000)
            .start()
    }
}

You can use view binding as well to get rid of findViewById


问:
base R faster than readr for reading multiple CSV files
There is a lot of documentation on how to read multiple CSVs and bind them into one data frame.  I have 5000+ CSV files I need to read in and bind into one data structure.

In particular I've followed the discussion here: Issue in Loading multiple .csv files into single dataframe in R using rbind

The weird thing is that base R is much faster than any other solution I've tried.

Here's what my CSV looks like:

```<code>> head(PT)
  Line          Timestamp       Lane.01 Lane.02 Lane.03 Lane.04 Lane.05 Lane.06 Lane.07 Lane.08
1    PL1    05-Jan-16 07:17:36      NA      NA      NA      NA      NA      NA      NA      NA
2    PL1    05-Jan-16 07:22:38      NA      NA      NA      NA      NA      NA      NA      NA
3    PL1    05-Jan-16 07:27:41      NA      NA      NA      NA      NA      NA      NA      NA
4    PL1    05-Jan-16 07:32:43    9.98   10.36   10.41   10.16   10.10    9.97   10.07    9.59
5    PL1    05-Jan-16 07:37:45    9.65    8.87    9.88    9.86    8.85    8.75    9.19    8.51
6    PL1    05-Jan-16 07:42:47    9.14    8.98    9.29    9.04    9.01    9.06    9.12    9.08
</code>```

I've created three methods for reading in and binding the data.  The files are located in a separate directory which I define as:

```<code>dataPath <- "data"
PTfiles <- list.files(path=dataPath, full.names = TRUE)
</code>```

Method 1: Base R

```<code>classes <- c("factor", "character", rep("numeric",8))

# build function to load data
load_data <- function(dataPath, classes) {
   tables <- lapply(PTfiles, read.csv, colClasses=classes, na.strings=c("NA", ""))
   do.call(rbind, tables)
}

#clock
method1 <- system.time(
   PT <- load_data(path, classes)
)
</code>```

Method 2: read_csv
In this case I created a wrapper function for read_csv to use

```<code>#create wrapper function for read_csv
read_csv.wrap <- function(x) { read_csv(x, skip = 1, na=c("NA", ""),
                      col_names = c("tool", "timestamp", paste("lane", 1:8, sep="")),
                      col_types =
                         cols(
                            tool = col_character(),
                            timestamp = col_character(),
                            lane1 = col_double(),
                            lane2 = col_double(),
                            lane3 = col_double(),
                            lane4 = col_double(),
                            lane5 = col_double(),
                            lane6 = col_double(),
                            lane7 = col_double(),
                            lane8 = col_double()
                           )
                     )
}

##
# Same as method 1, just uses read_csv instead of read.csv

load_data2 <- function(dataPath) {
   tables <- lapply(PTfiles, read_csv.wrap)
   do.call(rbind, tables)
}

#clock
method2 <- system.time(
   PT2 <- load_data2(path)
)
</code>```

Method 3: read_csv + dplyr::bind_rows

```<code>load_data3 <- function(dataPath) {
   tables <- lapply(PTfiles, read_csv.wrap)
   dplyr::bind_rows(tables)
}

#clock
method3 <- system.time(
   PT3 <- load_data3(path)
)
</code>```

What I can't figure out, is why read_csv and dplyr methods are slower for elapsed time when they should be faster.  The CPU time is decreased, but why would the elapsed time (file system) increase? What's going on here?

Edit - I added the data.table method as suggested in the comments

Method 4 data.table

```<code>library(data.table)

load_data4 <- function(dataPath){
   tables <- lapply(PTfiles, fread)
   rbindlist(tables)
}

method4 <- system.time(
   PT4 <- load_data4(path)
)
</code>```

The data.table method is the fastest from a CPU standpoint.  But the question still stands on what is going on with the read_csv methods that makes them so slow.

```<code>> rbind(method1, method2, method3, method4)
        user.self sys.self elapsed
method1      0.56     0.39    1.35
method2      0.42     1.98   13.96
method3      0.36     2.25   14.69
method4      0.34     0.67    1.74
</code>```

答:
I might have found a related issue. I am reading in nested CSV data from some simulation output, where multiple columns have CSV formatted data as elements, which I need to unnest and reshape for analysis.

With simulations where I have many runs, this resulted in thousands of elements that needed to be parsed. Using map(.,read_csv) this would take hours to transform. When I rewrote my script to apply read.csv in a lambda function, the operation would complete in seconds.

I'm curious if there is some intermediate system I/O operation or error handling that creates a bottleneck you wouldn't run into with a single input file.

Body:
There is a lot of documentation on how to read multiple CSVs and bind them into one data frame.  I have 5000+ CSV files I need to read in and bind into one data structure.

In particular I've followed the discussion here: Issue in Loading multiple .csv files into single dataframe in R using rbind

The weird thing is that base R is much faster than any other solution I've tried.

Here's what my CSV looks like:

> head(PT)
  Line          Timestamp       Lane.01 Lane.02 Lane.03 Lane.04 Lane.05 Lane.06 Lane.07 Lane.08
1    PL1    05-Jan-16 07:17:36      NA      NA      NA      NA      NA      NA      NA      NA
2    PL1    05-Jan-16 07:22:38      NA      NA      NA      NA      NA      NA      NA      NA
3    PL1    05-Jan-16 07:27:41      NA      NA      NA      NA      NA      NA      NA      NA
4    PL1    05-Jan-16 07:32:43    9.98   10.36   10.41   10.16   10.10    9.97   10.07    9.59
5    PL1    05-Jan-16 07:37:45    9.65    8.87    9.88    9.86    8.85    8.75    9.19    8.51
6    PL1    05-Jan-16 07:42:47    9.14    8.98    9.29    9.04    9.01    9.06    9.12    9.08

I've created three methods for reading in and binding the data.  The files are located in a separate directory which I define as:

dataPath <- "data"
PTfiles <- list.files(path=dataPath, full.names = TRUE)

Method 1: Base R

classes <- c("factor", "character", rep("numeric",8))

# build function to load data
load_data <- function(dataPath, classes) {
   tables <- lapply(PTfiles, read.csv, colClasses=classes, na.strings=c("NA", ""))
   do.call(rbind, tables)
}

#clock
method1 <- system.time(
   PT <- load_data(path, classes)
)

Method 2: read_csv
In this case I created a wrapper function for read_csv to use

#create wrapper function for read_csv
read_csv.wrap <- function(x) { read_csv(x, skip = 1, na=c("NA", ""),
                      col_names = c("tool", "timestamp", paste("lane", 1:8, sep="")),
                      col_types =
                         cols(
                            tool = col_character(),
                            timestamp = col_character(),
                            lane1 = col_double(),
                            lane2 = col_double(),
                            lane3 = col_double(),
                            lane4 = col_double(),
                            lane5 = col_double(),
                            lane6 = col_double(),
                            lane7 = col_double(),
                            lane8 = col_double()
                           )
                     )
}

##
# Same as method 1, just uses read_csv instead of read.csv

load_data2 <- function(dataPath) {
   tables <- lapply(PTfiles, read_csv.wrap)
   do.call(rbind, tables)
}

#clock
method2 <- system.time(
   PT2 <- load_data2(path)
)

Method 3: read_csv + dplyr::bind_rows

load_data3 <- function(dataPath) {
   tables <- lapply(PTfiles, read_csv.wrap)
   dplyr::bind_rows(tables)
}

#clock
method3 <- system.time(
   PT3 <- load_data3(path)
)

What I can't figure out, is why read_csv and dplyr methods are slower for elapsed time when they should be faster.  The CPU time is decreased, but why would the elapsed time (file system) increase? What's going on here?

Edit - I added the data.table method as suggested in the comments

Method 4 data.table

library(data.table)

load_data4 <- function(dataPath){
   tables <- lapply(PTfiles, fread)
   rbindlist(tables)
}

method4 <- system.time(
   PT4 <- load_data4(path)
)

The data.table method is the fastest from a CPU standpoint.  But the question still stands on what is going on with the read_csv methods that makes them so slow.

> rbind(method1, method2, method3, method4)
        user.self sys.self elapsed
method1      0.56     0.39    1.35
method2      0.42     1.98   13.96
method3      0.36     2.25   14.69
method4      0.34     0.67    1.74