问:
OpenMP Target Task reduction
I'm using OpenMP target offloading do offload some nested loops to the gpu. I'm using the nowait to tun it asynchronous. This makes it a task. With the same input values the result differs from the one when not offloading (e.g. cpu: sum=0.99, offloading sum=0.5).
When removing the nowait clause it works just fine. So I think the issue is that it becomes an OpenMP task and I'm struggling getting it right.

#pragma omp target teams distribute parallel for reduction( +: sum) collapse(2) nowait depend(in: a, b) depend(out: sum)
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= n; j++)
        {
            double c = 0;

            for (int k = 0; k < n; k++)
            {
                c += /* some computation */
            }

            sum += fabs(c);
        }
    }
```

答:
The OpenMP 5.2 specification states:

The target construct generates a target task. The generated task region encloses the target region. If a depend clause is present, it is associated with the target task. [...]. If the nowait clause is present, execution of the target task may be deferred. If the nowait clause is not present, the target task is an included task.

This means that your code is executed in a task with a possibly deferred execution (with nowait). Thus, it can be executed at the end of the parallel in the worst case, but always before all the dependent tasks and taskwait directives waiting for the target task (or the ones including a similar behaviour like taskgroup). Because of that, you need not to modify the working arrays (nor release them) during this time span. If you do, the behaviour is undefined.

You should especially pay attention to the correctness of synchronization points and task dependencies in your code (it is impossible for us to check that with the current incomplete provided code).

Title: OpenMP Target Task reduction


来源: stackexchange

问:
Bash history without line numbers
The bash history command is very cool. I understand why it shows the line numbers, but is there a way I can invoke the history command and suppress the line numbers?

The point here is to use the history command, so please don't reply cat ~/.bash_history

Current Output:

```<code>  529 man history
  530 ls
  531 ll
  532 clear
  533 cd ~
  534 histor<em>y</em></code>```

Historical graphic source.

Desired Output:

```<code>man history
ls
ll
clear
cd ~
histor<em>y</em></code>```

Historical graphic source.

Thanks to everyone for your great solutions. Paul's is the simplest and will work for me for because my bash history size is set at 2000.

I also wanted to share a cool article I found this morning. It has a couple good options that I am now using, like keeping duplicate entries out of the bash history and making sure multiple bash sessions don't overwrite the history file: http://blog.macromates.com/2008/working-with-history-in-bash/

答:
awk can help:

```<code>history|awk '{$1="";print substr($0,2)}'
</code>```

This answer can fail if you have a long history.

ContentLicense: CC BY-SA 3.0

Title: Bash history without line numbers

Body:
The bash history command is very cool. I understand why it shows the line numbers, but is there a way I can invoke the history command and suppress the line numbers?

The point here is to use the history command, so please don't reply cat ~/.bash_history

Current Output:

  529 man history
  530 ls
  531 ll
  532 clear
  533 cd ~
  534 history

Historical graphic source.

Desired Output:

man history
ls
ll
clear
cd ~
history

Historical graphic source.

Thanks to everyone for your great solutions. Paul's is the simplest and will work for me for because my bash history size is set at 2000.

I also wanted to share a cool article I found this morning. It has a couple good options that I am now using, like keeping duplicate entries out of the bash history and making sure multiple bash sessions don't overwrite the history file: http://blog.macromates.com/2008/working-with-history-in-bash/

Body:
awk can help:

history|awk '{$1="";print substr($0,2)}'

This answer can fail if you have a long history.

ContentLicense: CC BY-SA 4.0


问:
Modify sent text in express.js
I'm trying to make a discord command that stores the user's data in an API. The system looks like this: User runs command -> User's tag gets stored in the API and from there I would be able to handle it from another place. My problem is that after the data is being saved once, it doesn't modify it when another user runs the command.

I have tried doing res.send() to update it and searched on the web for solutions but none of them worked.

Here is my code:

```<code>const express = require('express');
const app = express();
app.use(express.json());

const { Client } = require('discord.js');
const client = new Client({ intents: 32767 });

client.on('ready', () => {
    console.log('client is now ready')
})

client.on('messageCreate', (msg) => {
    if (msg.author.bot) return;

    if (msg.content === 'hey') {
        app.get('/', (req, res) => {
            res.send(`User interacted: ${msg.author.tag}`);
        })
    }
});

client.login(token)

</code>```

PS: I do not want to use any programs like Postman etc.

答:
To get the most previous author to show up in the get request, you need to store that value. The app.get/app.post/etc.. methods are defining what the sever should send when particular route is hit. They are not used for storing any data. To solve this particular issue you can simply do something like this:

const express = require('express');
const app = express();
app.use(express.json());

const { Client } = require('discord.js');
const client = new Client({ intents: 32767 });

let previousUser = '';

app.get('/', (req, res) => {
    res.send(`User interacted: ${previousUser}`);
})

client.on('ready', () => {
    console.log('client is now ready')
})

client.on('messageCreate', (msg) => {
    if (msg.author.bot) return;

    if (msg.content === 'hey') {
        previousUser = msg.author.tag;
    }
});

client.login(token)
```

This code will save the previous messages author to a variable previousUser ever time a message is received that has the content 'hey'. From there, anytime you run a get request on the '/' route, it will display that user.

There are many different ways to store data, be it in memory (like above), in a database, or written to a file. I suggest you read up on express, rest apis, and NodeJS before adding more complicated logic to this program

Title: Modify sent text in express.js

Body:
I'm trying to make a discord command that stores the user's data in an API. The system looks like this: User runs command -> User's tag gets stored in the API and from there I would be able to handle it from another place. My problem is that after the data is being saved once, it doesn't modify it when another user runs the command.

I have tried doing res.send() to update it and searched on the web for solutions but none of them worked.

Here is my code:

const express = require('express');
const app = express();
app.use(express.json());

const { Client } = require('discord.js');
const client = new Client({ intents: 32767 });

client.on('ready', () => {
    console.log('client is now ready')
})

client.on('messageCreate', (msg) => {
    if (msg.author.bot) return;

    if (msg.content === 'hey') {
        app.get('/', (req, res) => {
            res.send(`User interacted: ${msg.author.tag}`);
        })
    }
});

client.login(token)

PS: I do not want to use any programs like Postman etc.

Body:
To get the most previous author to show up in the get request, you need to store that value. The app.get/app.post/etc.. methods are defining what the sever should send when particular route is hit. They are not used for storing any data. To solve this particular issue you can simply do something like this:

const express = require('express');
const app = express();
app.use(express.json());

const { Client } = require('discord.js');
const client = new Client({ intents: 32767 });

let previousUser = '';

app.get('/', (req, res) => {
    res.send(`User interacted: ${previousUser}`);
})

client.on('ready', () => {
    console.log('client is now ready')
})

client.on('messageCreate', (msg) => {
    if (msg.author.bot) return;

    if (msg.content === 'hey') {
        previousUser = msg.author.tag;
    }
});

client.login(token)

This code will save the previous messages author to a variable previousUser ever time a message is received that has the content 'hey'. From there, anytime you run a get request on the '/' route, it will display that user.

There are many different ways to store data, be it in memory (like above), in a database, or written to a file. I suggest you read up on express, rest apis, and NodeJS before adding more complicated logic to this program


问:
Import [Module] could not be resolved from sourcePylancereportMissingModuleSource
I'm trying to import pymysql to my python script in VSCode but am getting the following error

```<code>Import "pymysql" could not be resolved from sourcePylancereportMissingModuleSource
</code>```

I installed the module with pip the same way I have with all other modules such as Pandas, which works fine

Here's the import line for reference

```<code>import pymysql
</code>```

Any quick fixes or explanations of what is going on would be appreciated, thanks

答:
Check for the current Python Interpreter VSCode is using Ctrl+P.

Add your virtual environment PATH where your module is installed in 'C:\Users\<username>\.virtualenvs\<virtualenvname>\Scripts\python'.

Body:
I'm trying to import pymysql to my python script in VSCode but am getting the following error

Import "pymysql" could not be resolved from sourcePylancereportMissingModuleSource

I installed the module with pip the same way I have with all other modules such as Pandas, which works fine

Here's the import line for reference

import pymysql

Any quick fixes or explanations of what is going on would be appreciated, thanks


问:
 not starting where it starts where I want it to on new line
In the image you can see that if the title of the sidebar link is too long it goes to the next line. However it starts where the icon is located and not where the start of the span is. How would I style the class "side-nav-item" to where it will format where Administrator when it is shifted to the new line it starts where Give is.

      User Access

                   Give user access - Administrator

                   Remove

```

答: Style  inside  as an inline-block. The behaviour you are seeing is expected from inline elements like  and . Checkout concepts of inline elements, block elements and 'display' property in CSS. I am assuming you are new to HTML and CSS, so I suggest you begin with a good hands on video tutorial.

Title: <span> not starting where it starts where I want it to on new line

Body: Style <span> inside <a></a> as an inline-block. The behaviour you are seeing is expected from inline elements like <span> and <i>. Checkout concepts of inline elements, block elements and 'display' property in CSS. I am assuming you are new to HTML and CSS, so I suggest you begin with a good hands on video tutorial.


问:
Lock someone to a particular domain
We have a dll that is a plug-in for a asp.net shopping cart software that customers can purchase. However, we want to lock that dll to a particular domain for security reasons and we don't want them to be able to read that dll or use that dll in another domain they may have. How can we do this?</p>

答:
Brainstorming:

Hard-code a domain-check into the dll's main function and compile a new dll for each customer (ok, not scalable)

Distribute a license file with the dll that stores the valid domain for the dll, encrypted. Have your DLL check for the file, decrypt the contents, and fail if the file is missing or the current domain doesn't match the encrypted domain.

Have the DLL "phone-home" to one of your servers over encrypted line asking your server whether the current domain the dll is running in is acceptable. Your server responds 'yes' or 'no' and the DLL either runs or doesn't.

OwnerDisplayName: jumbojs

ContentLicense: CC BY-SA 2.5

Title: Lock someone to a particular domain

OwnerDisplayName: veefu


问:
Regex - Recursion - nested matches with multiple ending
this is my first question on stackoverflow so please bare with me here. Also I am not a native english speaker.

(16.02.2022)
ANSWER (https://regex101.com/r/4FRznK/1 from Comment on Answer). Special thanks to Casimir et Hippolyte for your help! I wish I could reach out to you.

```<code>\[if \s+ (?<cond> [^]]* ) ]

(?<content> [^[]*+
        (?: (?R) [^[]*
          | \[ (?! /if] | else (?:if)?  \b) [^[]*
        )*+
)
(?<rest>
    (?: \[elseif \s+ [^]]* ] \g<content> )*+
    (?: \[else] \g<content> )?+
    \[/if]
)
</code>```

(15.02.2022) UPDATE:
I fiddled around with the solutions presented below and have gotten farther with it. Seems like there is a limit on string length to comfortably match without any catastophic backtracking.

I have updated my Regex101 to show the recent progress. Maybe one of you has an idea on how to tackle this. https://regex101.com/r/wYzA3e/4

SIDE NOTE:
I do have a working function for this, but my goal is to find a faster solution in terms of optimization and reliability. My current functions takes (in my opinion) way to long to complete the task and relies havily on strpos to get me there. I do not actually want to use third-party functions if there is a cheaper (in terms of performance) solution with PHPs internal functions.
So even if you advice me to use alternative approaches, please be kind and provide hints on which explicitly you mean by these. Thank you!

(14.02.2022) Original:
I am presented with the following difficulties with my regular expression:
This is the string ("true" and/or "false" are not actually in the string but it helps with simplification):

```<code>**[if true]**
    [if true]
        [if false]
        [else]
        [/if]
    *[elseif false]*
        [if true]
        [/if]
    [else]
    [/if]
**[elseif false]**
[/if]
**[if false]**
    [if false]
    [else]
    *[/if]*
**[else]**
    [if true]
    [/if]
[/if]
</code>```

I marked the wanted matches (**) and the ones i got (*)

In this situation I do only want to match the most outer parent [if XXXX].([else]|[elseif XXX]|[/if]) statement with its according end which can be [else], [elseif XXX] or [/if]. For now i do not care about the inner [if XXX] since when the parent is false i dont need to check for them.

When running my regex:

```<code>/\[if (.*?)\](((?R)|.)*?)(\[\/if\]|\[else\]|\[elseif )/gs
</code>```

it matches the parents [if XXX] and an incoherent combination of any [elseif XX], [else], [/if] in it.

As groups I do need the match > every X [if XXX] > the content between [if XXX] and the matching [END] as well as the [END].

Since i do not fully understand Recursion I´d appreciate your help. Many thanks in advance!

You can try the regex here (updated):
https://regex101.com/r/wYzA3e/4

答:
This might be close?

It also captures the outer closing tag.

But don't see how to avoid that, without breaking the recursion.

```<code>\[(if|elseif|else) ?(.*?)\](((?R)|[^\[\]])*?)(?:.(?=\[else.*?\])|\[\/if\])
</code>```

Test on regex101 here

Body:
this is my first question on stackoverflow so please bare with me here. Also I am not a native english speaker.

(16.02.2022)
ANSWER (https://regex101.com/r/4FRznK/1 from Comment on Answer). Special thanks to Casimir et Hippolyte for your help! I wish I could reach out to you.

\[if \s+ (?<cond> [^]]* ) ]

(?<content> [^[]*+
        (?: (?R) [^[]*
          | \[ (?! /if] | else (?:if)?  \b) [^[]*
        )*+
)
(?<rest>
    (?: \[elseif \s+ [^]]* ] \g<content> )*+
    (?: \[else] \g<content> )?+
    \[/if]
)

(15.02.2022) UPDATE:
I fiddled around with the solutions presented below and have gotten farther with it. Seems like there is a limit on string length to comfortably match without any catastophic backtracking.

I have updated my Regex101 to show the recent progress. Maybe one of you has an idea on how to tackle this. https://regex101.com/r/wYzA3e/4

SIDE NOTE:
I do have a working function for this, but my goal is to find a faster solution in terms of optimization and reliability. My current functions takes (in my opinion) way to long to complete the task and relies havily on strpos to get me there. I do not actually want to use third-party functions if there is a cheaper (in terms of performance) solution with PHPs internal functions.
So even if you advice me to use alternative approaches, please be kind and provide hints on which explicitly you mean by these. Thank you!

(14.02.2022) Original:
I am presented with the following difficulties with my regular expression:
This is the string ("true" and/or "false" are not actually in the string but it helps with simplification):

**[if true]**
    [if true]
        [if false]
        [else]
        [/if]
    *[elseif false]*
        [if true]
        [/if]
    [else]
    [/if]
**[elseif false]**
[/if]
**[if false]**
    [if false]
    [else]
    *[/if]*
**[else]**
    [if true]
    [/if]
[/if]

I marked the wanted matches (**) and the ones i got (*)

In this situation I do only want to match the most outer parent [if XXXX].([else]|[elseif XXX]|[/if]) statement with its according end which can be [else], [elseif XXX] or [/if]. For now i do not care about the inner [if XXX] since when the parent is false i dont need to check for them.

When running my regex:

/\[if (.*?)\](((?R)|.)*?)(\[\/if\]|\[else\]|\[elseif )/gs

it matches the parents [if XXX] and an incoherent combination of any [elseif XX], [else], [/if] in it.

As groups I do need the match > every X [if XXX] > the content between [if XXX] and the matching [END] as well as the [END].

Since i do not fully understand Recursion I´d appreciate your help. Many thanks in advance!

You can try the regex here (updated):
https://regex101.com/r/wYzA3e/4

Body:
This might be close?

It also captures the outer closing tag.

But don't see how to avoid that, without breaking the recursion.

\[(if|elseif|else) ?(.*?)\](((?R)|[^\[\]])*?)(?:.(?=\[else.*?\])|\[\/if\])

Test on regex101 here


问:
Dimension value error to load model with keras
I am trying to denoise an image with a pre-trained model I loaded as "model". I am getting an error as a result of the dimensions being different. Here is the code I have:

```<code>path_clean = r"clean.png"
clean = load_img(path_clean)
path_noisy = r"noise.png"
noisy = load_img(path_noisy)
model.compile(

  optimizer=tf.keras.optimizers.Adam(learning_rate=3e-4),
  loss=tf.keras.losses.mean_squared_error,
  metrics=[tf.keras.metrics.mean_absolute_error])

history = model.fit(img_to_array(noisy), img_to_array(clean), epochs=50)
</code>```

Here is the error I get, calling from the "history" line:

```<code>ValueError: Exception encountered when calling layer "concatenate" (type Concatenate).

Dimension 1 in both shapes must be equal, but are 113 and 114. Shapes are [?,113,1] and [?,114,2]. for '{{node model/concatenate/concat}} = ConcatV2[N=2, T=DT_FLOAT, Tidx=DT_INT32](model/conv2d_6/Relu, model/up_sampling2d/resize/ResizeNearestNeighbor, model/concatenate/concat/axis)' with input shapes: [?,113,1,128], [?,114,2,128], [] and with computed input tensors: input[2] = <3>.

Call arguments received:
  • inputs=['tf.Tensor(shape=(None, 113, 1, 128), dtype=float32)', 'tf.Tensor(shape=(None, 114, 2, 128), dtype=float32)']
</code>```

What does it mean that one is 113 and one is 114? When I print the shapes of each image using this:

```<code>print(img_to_array(clean).shape)
print(img_to_array(noisy).shape)
</code>```

I get this:

```<code>(500, 500, 3)
(500, 500, 3)
</code>```

So the dimensions should be the same, right? Thanks for your help.

答:
The error has to do with a certain layer within the network not managing to align the inputs that you give it. The number you see are different because the input data undergoes a series of transformations and then it arrives at this layer and everything breaks down.

Try reading the documentation for this pre-trained model to understand what its constraints are - maybe it performs some reshaping magic and expects a certain shape as input.

When you load the model, you should also be able to inspect the graph structure to understand what happens to the input up until this concatenation.

Body:
I am trying to denoise an image with a pre-trained model I loaded as "model". I am getting an error as a result of the dimensions being different. Here is the code I have:

path_clean = r"clean.png"
clean = load_img(path_clean)
path_noisy = r"noise.png"
noisy = load_img(path_noisy)
model.compile(

  optimizer=tf.keras.optimizers.Adam(learning_rate=3e-4),
  loss=tf.keras.losses.mean_squared_error,
  metrics=[tf.keras.metrics.mean_absolute_error])

history = model.fit(img_to_array(noisy), img_to_array(clean), epochs=50)

Here is the error I get, calling from the "history" line:

ValueError: Exception encountered when calling layer "concatenate" (type Concatenate).

Dimension 1 in both shapes must be equal, but are 113 and 114. Shapes are [?,113,1] and [?,114,2]. for '{{node model/concatenate/concat}} = ConcatV2[N=2, T=DT_FLOAT, Tidx=DT_INT32](model/conv2d_6/Relu, model/up_sampling2d/resize/ResizeNearestNeighbor, model/concatenate/concat/axis)' with input shapes: [?,113,1,128], [?,114,2,128], [] and with computed input tensors: input[2] = <3>.

Call arguments received:
  • inputs=['tf.Tensor(shape=(None, 113, 1, 128), dtype=float32)', 'tf.Tensor(shape=(None, 114, 2, 128), dtype=float32)']

What does it mean that one is 113 and one is 114? When I print the shapes of each image using this:

print(img_to_array(clean).shape)
print(img_to_array(noisy).shape)

I get this:

(500, 500, 3)
(500, 500, 3)

So the dimensions should be the same, right? Thanks for your help.


问:
understanding the concept of amounts with regex
I am aware that regex does not work with numeric values,  yet, how can we have a regex pattern to differentiate between numbers in a google sheets formula?

for example: >=13 and <13

A
B

desired result

5
5♥

2
2♥

13
13♦♦♦

12
12♥

30
30♦♦♦

17
17♦♦♦

0
0♥

-4
-4♥

-12
-12♥

22
22♦♦♦

-55
-55♥

31
31♦♦♦

-13
-13♥

-31
-31♥

I can solve this in alternative ways like:

```<code>=INDEX(REGEXREPLACE(REGEXREPLACE(REGEXREPLACE("" & A2:A16,
 "\b(^" & JOIN("$|^", SEQUENCE(13, 1, )) & "$)\b", "$1♥"),
 "(^-\d+)", "$1♥"),
 "(\d+$)", "$1♦♦♦"))
</code>```

...but I feel there could be some more "regexy" solution.

rules of combat:

regex pattern

no IF-statements

>=13 add ♦♦♦

<13 add ♥

no IFERROR pivots

no non-regex solutions

答:
You could first add the diamonds and then replace those by a heart when the number is less than 13:

```<code>=REGEXREPLACE(A1 & "♦♦♦"; "^(-\d+|1[0-2]|\d)♦♦♦$"; "$1♥")
</code>```

The regular expression looks for three patterns:

-\d+: any negative number

1[0-2]: 10, 11 or 12

\d: 0,1,2,..., or 9.

Body:
I am aware that regex does not work with numeric values,  yet, how can we have a regex pattern to differentiate between numbers in a google sheets formula?

for example: >=13 and <13

A
B

desired result

5
5♥

2
2♥

13
13♦♦♦

12
12♥

30
30♦♦♦

17
17♦♦♦

0
0♥

-4
-4♥

-12
-12♥

22
22♦♦♦

-55
-55♥

31
31♦♦♦

-13
-13♥

-31
-31♥

I can solve this in alternative ways like:

=INDEX(REGEXREPLACE(REGEXREPLACE(REGEXREPLACE("" & A2:A16,
 "\b(^" & JOIN("$|^", SEQUENCE(13, 1, )) & "$)\b", "$1♥"),
 "(^-\d+)", "$1♥"),
 "(\d+$)", "$1♦♦♦"))

...but I feel there could be some more "regexy" solution.

rules of combat:

regex pattern

no IF-statements

>=13 add ♦♦♦

<13 add ♥

no IFERROR pivots

no non-regex solutions

Body:
You could first add the diamonds and then replace those by a heart when the number is less than 13:

=REGEXREPLACE(A1 & "♦♦♦"; "^(-\d+|1[0-2]|\d)♦♦♦$"; "$1♥")

The regular expression looks for three patterns:

-\d+: any negative number

1[0-2]: 10, 11 or 12

\d: 0,1,2,..., or 9.


问:
Can you have a 0.5px border on a Retina Display?
On Mobile Safari on an iPhone 4 or iPhone4S, can you have a border of a div that is 0.5px wide?</p>

答:
```<code>box-shadow: 1px 1px 0px 2px rgba(0, 0, 0, 0.5);
</code>```


问:
Simple PHP Class Question regarding methods
I have a simple question regarding PHP Classes.

Multiple times I have seen other class-frameworks etc use method calls like.

```<code>$post->data->text();
</code>```

I like this functionality, rather than just doing something like this.

```<code>$post->dataReturnAsText();
</code>```

But i'm not quite sure how they created this functionality to have perhaps a 'sub-method'? Hope someone can point me in the right direction....

答:
In this case, data is simply a attribute of the class, and it contains another object:</p>

```<code>class data
{
    public function text()
    {
    }
}

class thing
{
    public $data;
}

$thing = new thing();
$thing->data = new data();
$thing->data->text();
</code>```

Body:
I have a simple question regarding PHP Classes.

Multiple times I have seen other class-frameworks etc use method calls like.

$post->data->text();

I like this functionality, rather than just doing something like this.

$post->dataReturnAsText();

But i'm not quite sure how they created this functionality to have perhaps a 'sub-method'? Hope someone can point me in the right direction....

Body:
In this case, data is simply a attribute of the class, and it contains another object:

class data
{
    public function text()
    {
    }
}

class thing
{
    public $data;
}

$thing = new thing();
$thing->data = new data();
$thing->data->text();


问:
How to read out a file line by line and for every line do a search with find and copy the search result to destination?
I hope you can help me with the following problem:

The Situation

I need to find files in various folders and copy them to another folder. The files and folders can contain white spaces and umlauts.

The filenames contain an ID and a string like:
"2022-01-11-02 super important file"

The filenames I need to find are collected in a textfile named ids.txt. This file only contains the IDs but not the whole filename as a string.

What I want to achieve:

I want to read out ids.txt line by line.

For every line in ids.txt I want to do a find search and copy cp the result to destination.

So far I tried:

for n in $(cat ids.txt); do find /home/alex/testzone/ -name "$n" -exec cp {} /home/alex/testzone/output \; ;

while read -r ids; do find /home/alex/testzone -name "$ids" -exec cp {} /home/alex/testzone/output \; ; done < ids.txt

The output folder remains empty. Not using -exec also gives no (search)results.

I was thinking that -name "$ids" is the root cause here. My files contain the ID + a String so I should search for names containing the ID plus a variable string (star)

As argument for -name I also tried "$ids *" "$ids"" *" and so on with no luck.

Is there an argument that I can use in conjunction with find instead of using the star in the -name argument?

Do you have any solution for me to automate this process in a bash script to read out ids.txt file, search the filenames and copy them over to specified folder?

In the end I would like to create a bash script that takes ids.txt and the search-folder and the output-folder as arguments like:

```<code>my-id-search.sh /home/alex/testzone/ids.txt /home/alex/testzone/ /home/alex/testzone/output
</code>```

EDIT:
This is some example content of the ids.txt file where only ids are listed (not the whole filename):

```<code>2022-01-11-01
2022-01-11-02
2020-12-01-62
</code>```

EDIT II:
Going on with the solution from tripleee:

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

grep . $1 | while read -r id; do
echo "Der Suchbegriff lautet:"$id; echo;
   find /home/alex/testzone -name "$id*" -exec cp {} /home/alex/testzone/ausgabe \;
done
</code>```

In case my ids.txt file contains empty lines the -name "$id*" will be -name * which in turn finds all files and copies all files.

Trying to prevent empty line to be read does not seem to work. They should be filtered by the expression grep . $1 |. What am I doing wrong?

答:
If your destination folder is always the same, the quickest and absolutely most elegant solution is to run a single find command to look for all of the files.

```<code>sed 's/.*/-o\n—name\n&*/' ids.txt |
xargs -I {} find -false {} -exec cp {} /home/alex/testzone/output +
</code>```

The -false predicate is a bit of a hack to allow the list of actual predicates to start with -o (as in "or").

This could fail if ids.txt is too large to fit into a single xargs invocation, or if your sed does not understand \n to mean a literal newline.

(Here's a fix for the latter case:

```<code>xargs printf '-o\n-name\n%s*\n' <ids.txt |
...
</code>```

Still the inherent problem with using xargs find like this is that xargs could split the list between -o and -name or between -name and the actual file name pattern if it needs to run more than one find command to process all the arguments.

A slightly hackish solution to that is to ensure that each pair is a single string, and then separately split them back out again:

```<code>xargs printf '-o_-name_%s*\n' <ids.txt |
xargs bash -c 'arr=("$@"); find -false ${arr[@]/-o_-name_/-o -name } -exec cp {} "$0"' /home/alex/testzone/ausgabe
</code>```

where we temporarily hold the arguments in an array where each file name and its flags is a single item, and then replace the flags into separate tokens. This still won't work correctly if the file names you operate on contain literal shell metacharacters like * etc.)

A more mundane solution fixes your while read attempt by adding the missing wildcard in the -name argument. (I also took the liberty to rename the variable, since read will only read one argument at a time, so the variable name should be singular.)

```<code>while read -r id; do
   find /home/alex/testzone -name "$id*" -exec cp {} /home/alex/testzone/output \;
done < ids.txt
</code>```

Body:
I hope you can help me with the following problem:

The Situation

I need to find files in various folders and copy them to another folder. The files and folders can contain white spaces and umlauts.

The filenames contain an ID and a string like:
"2022-01-11-02 super important file"

The filenames I need to find are collected in a textfile named ids.txt. This file only contains the IDs but not the whole filename as a string.

What I want to achieve:

I want to read out ids.txt line by line.

For every line in ids.txt I want to do a find search and copy cp the result to destination.

So far I tried:

for n in $(cat ids.txt); do find /home/alex/testzone/ -name "$n" -exec cp {} /home/alex/testzone/output \; ;

while read -r ids; do find /home/alex/testzone -name "$ids" -exec cp {} /home/alex/testzone/output \; ; done < ids.txt

The output folder remains empty. Not using -exec also gives no (search)results.

I was thinking that -name "$ids" is the root cause here. My files contain the ID + a String so I should search for names containing the ID plus a variable string (star)

As argument for -name I also tried "$ids *" "$ids"" *" and so on with no luck.

Is there an argument that I can use in conjunction with find instead of using the star in the -name argument?

Do you have any solution for me to automate this process in a bash script to read out ids.txt file, search the filenames and copy them over to specified folder?

In the end I would like to create a bash script that takes ids.txt and the search-folder and the output-folder as arguments like:

my-id-search.sh /home/alex/testzone/ids.txt /home/alex/testzone/ /home/alex/testzone/output

EDIT:
This is some example content of the ids.txt file where only ids are listed (not the whole filename):

2022-01-11-01
2022-01-11-02
2020-12-01-62

EDIT II:
Going on with the solution from tripleee:

#!/bin/bash

grep . $1 | while read -r id; do
echo "Der Suchbegriff lautet:"$id; echo;
   find /home/alex/testzone -name "$id*" -exec cp {} /home/alex/testzone/ausgabe \;
done

In case my ids.txt file contains empty lines the -name "$id*" will be -name * which in turn finds all files and copies all files.

Trying to prevent empty line to be read does not seem to work. They should be filtered by the expression grep . $1 |. What am I doing wrong?

Body:
If your destination folder is always the same, the quickest and absolutely most elegant solution is to run a single find command to look for all of the files.

sed 's/.*/-o\n—name\n&*/' ids.txt |
xargs -I {} find -false {} -exec cp {} /home/alex/testzone/output +

The -false predicate is a bit of a hack to allow the list of actual predicates to start with -o (as in "or").

This could fail if ids.txt is too large to fit into a single xargs invocation, or if your sed does not understand \n to mean a literal newline.

(Here's a fix for the latter case:

xargs printf '-o\n-name\n%s*\n' <ids.txt |
...

Still the inherent problem with using xargs find like this is that xargs could split the list between -o and -name or between -name and the actual file name pattern if it needs to run more than one find command to process all the arguments.

A slightly hackish solution to that is to ensure that each pair is a single string, and then separately split them back out again:

xargs printf '-o_-name_%s*\n' <ids.txt |
xargs bash -c 'arr=("$@"); find -false ${arr[@]/-o_-name_/-o -name } -exec cp {} "$0"' /home/alex/testzone/ausgabe

where we temporarily hold the arguments in an array where each file name and its flags is a single item, and then replace the flags into separate tokens. This still won't work correctly if the file names you operate on contain literal shell metacharacters like * etc.)

A more mundane solution fixes your while read attempt by adding the missing wildcard in the -name argument. (I also took the liberty to rename the variable, since read will only read one argument at a time, so the variable name should be singular.)

while read -r id; do
   find /home/alex/testzone -name "$id*" -exec cp {} /home/alex/testzone/output \;
done < ids.txt


问:
pip failing to install specific packages: error 1 (kivy)
I am able to install most packages, but some specific packages are failing. One I am consistently failing is Kivy. I have tried updating, as well as full reinstall of pip, setuptools, distutils, etc. I also have followed all recommendations on the kivy site and can not quite figure out the issue. Here is my error printout from cmd prompt:

```<code>C:\Users\user1>py -m pip install kivy
Collecting kivy
  Using cached Kivy-2.0.0.tar.gz (23.7 MB)
  Installing build dependencies ... error
  ERROR: Command errored out with exit status 1:
   command: 'C:\Users\user1\AppData\Local\Programs\Python\Python310\python.exe' 'C:\Users\user1\AppData\Local\Temp\pip-standalone-pip-7w75s0h9\__env_pip__.zip\pip' install --ignore-installed --no-user --prefix 'C:\Users\user1\AppData\Local\Temp\pip-build-env-0an0tu7h\overlay' --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- setuptools wheel 'cython>=0.24,<=0.29.21,!=0.27,!=0.27.2' 'kivy_deps.gstreamer_dev~=0.3.1; sys_platform == "win32"' 'kivy_deps.sdl2_dev~=0.3.1; sys_platform == "win32"' 'kivy_deps.glew_dev~=0.3.0; sys_platform == "win32"' 'kivy_deps.gstreamer~=0.3.1; sys_platform == "win32"' 'kivy_deps.sdl2~=0.3.1; sys_platform == "win32"' 'kivy_deps.glew~=0.3.0; sys_platform == "win32"'
       cwd: None
  Complete output (10 lines):
  Collecting setuptools
    Using cached setuptools-60.5.0-py3-none-any.whl (958 kB)
  Collecting wheel
    Using cached wheel-0.37.1-py2.py3-none-any.whl (35 kB)
  Collecting cython!=0.27,!=0.27.2,<=0.29.21,>=0.24
    Using cached Cython-0.29.21-py2.py3-none-any.whl (974 kB)
  Collecting kivy_deps.gstreamer_dev~=0.3.1
    Using cached kivy_deps.gstreamer_dev-0.3.3-cp310-cp310-win_amd64.whl (3.9 MB)
  ERROR: Could not find a version that satisfies the requirement kivy_deps.sdl2_dev~=0.3.1 (from versions: 0.4.2, 0.4.3, 0.4.4)
  ERROR: No matching distribution found for kivy_deps.sdl2_dev~=0.3.1
  ----------------------------------------
WARNING: Discarding https://files.pythonhosted.org/packages/12/96/091ddacafb84dd18555a32d860dbfaf9c806147aa30c6f3c8b93cb7bab97/Kivy-2.0.0.tar.gz#sha256=d25e44eb44e43762b2fd0c5874e51954e0f1181fd9800d8a6756be6d084812d8 (from https://pypi.org/simple/kivy/). Command errored out with exit status 1: 'C:\Users\user1\AppData\Local\Programs\Python\Python310\python.exe' 'C:\Users\user1\AppData\Local\Temp\pip-standalone-pip-7w75s0h9\__env_pip__.zip\pip' install --ignore-installed --no-user --prefix 'C:\Users\user1\AppData\Local\Temp\pip-build-env-0an0tu7h\overlay' --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- setuptools wheel 'cython>=0.24,<=0.29.21,!=0.27,!=0.27.2' 'kivy_deps.gstreamer_dev~=0.3.1; sys_platform == "win32"' 'kivy_deps.sdl2_dev~=0.3.1; sys_platform == "win32"' 'kivy_deps.glew_dev~=0.3.0; sys_platform == "win32"' 'kivy_deps.gstreamer~=0.3.1; sys_platform == "win32"' 'kivy_deps.sdl2~=0.3.1; sys_platform == "win32"' 'kivy_deps.glew~=0.3.0; sys_platform == "win32"' Check the logs for full command output.
  Using cached Kivy-1.11.1.tar.gz (23.6 MB)
  Preparing metadata (setup.py) ... -
</code>```

It then loops through all previous kivy versions, and fails them as well.

答: Kivy 2.0 only supports Python 2.7 to 3.9 at the moment, so make sure your Python version is compatible. If you are using the latest version of Python, than you wont be able to install kivy.</p>

Body:
I am able to install most packages, but some specific packages are failing. One I am consistently failing is Kivy. I have tried updating, as well as full reinstall of pip, setuptools, distutils, etc. I also have followed all recommendations on the kivy site and can not quite figure out the issue. Here is my error printout from cmd prompt:

C:\Users\user1>py -m pip install kivy
Collecting kivy
  Using cached Kivy-2.0.0.tar.gz (23.7 MB)
  Installing build dependencies ... error
  ERROR: Command errored out with exit status 1:
   command: 'C:\Users\user1\AppData\Local\Programs\Python\Python310\python.exe' 'C:\Users\user1\AppData\Local\Temp\pip-standalone-pip-7w75s0h9\__env_pip__.zip\pip' install --ignore-installed --no-user --prefix 'C:\Users\user1\AppData\Local\Temp\pip-build-env-0an0tu7h\overlay' --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- setuptools wheel 'cython>=0.24,<=0.29.21,!=0.27,!=0.27.2' 'kivy_deps.gstreamer_dev~=0.3.1; sys_platform == "win32"' 'kivy_deps.sdl2_dev~=0.3.1; sys_platform == "win32"' 'kivy_deps.glew_dev~=0.3.0; sys_platform == "win32"' 'kivy_deps.gstreamer~=0.3.1; sys_platform == "win32"' 'kivy_deps.sdl2~=0.3.1; sys_platform == "win32"' 'kivy_deps.glew~=0.3.0; sys_platform == "win32"'
       cwd: None
  Complete output (10 lines):
  Collecting setuptools
    Using cached setuptools-60.5.0-py3-none-any.whl (958 kB)
  Collecting wheel
    Using cached wheel-0.37.1-py2.py3-none-any.whl (35 kB)
  Collecting cython!=0.27,!=0.27.2,<=0.29.21,>=0.24
    Using cached Cython-0.29.21-py2.py3-none-any.whl (974 kB)
  Collecting kivy_deps.gstreamer_dev~=0.3.1
    Using cached kivy_deps.gstreamer_dev-0.3.3-cp310-cp310-win_amd64.whl (3.9 MB)
  ERROR: Could not find a version that satisfies the requirement kivy_deps.sdl2_dev~=0.3.1 (from versions: 0.4.2, 0.4.3, 0.4.4)
  ERROR: No matching distribution found for kivy_deps.sdl2_dev~=0.3.1
  ----------------------------------------
WARNING: Discarding https://files.pythonhosted.org/packages/12/96/091ddacafb84dd18555a32d860dbfaf9c806147aa30c6f3c8b93cb7bab97/Kivy-2.0.0.tar.gz#sha256=d25e44eb44e43762b2fd0c5874e51954e0f1181fd9800d8a6756be6d084812d8 (from https://pypi.org/simple/kivy/). Command errored out with exit status 1: 'C:\Users\user1\AppData\Local\Programs\Python\Python310\python.exe' 'C:\Users\user1\AppData\Local\Temp\pip-standalone-pip-7w75s0h9\__env_pip__.zip\pip' install --ignore-installed --no-user --prefix 'C:\Users\user1\AppData\Local\Temp\pip-build-env-0an0tu7h\overlay' --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- setuptools wheel 'cython>=0.24,<=0.29.21,!=0.27,!=0.27.2' 'kivy_deps.gstreamer_dev~=0.3.1; sys_platform == "win32"' 'kivy_deps.sdl2_dev~=0.3.1; sys_platform == "win32"' 'kivy_deps.glew_dev~=0.3.0; sys_platform == "win32"' 'kivy_deps.gstreamer~=0.3.1; sys_platform == "win32"' 'kivy_deps.sdl2~=0.3.1; sys_platform == "win32"' 'kivy_deps.glew~=0.3.0; sys_platform == "win32"' Check the logs for full command output.
  Using cached Kivy-1.11.1.tar.gz (23.6 MB)
  Preparing metadata (setup.py) ... -

It then loops through all previous kivy versions, and fails them as well.


问:
Occasionally addMissingImports on save imports React again
I am using typescript and in *.tsx files, especially when i am copying code around, it quite often adds an additional</p>
```<code>import React from "react";
</code>```
```<code>    // ? On Save
    "editor.codeActionsOnSave": {
        "source.addMissingImports": true,
        "source.fixAll.eslint": true
        // "source.organizeImports": true
    }
</code>```

答:
I am using this configuration and works fine.

extensions.json

```<code>{
  "recommendations": [
    "amatiasq.sort-imports",
    "dbaeumer.vscode-eslint",
    "eamodio.gitlens",
    "eg2.vscode-npm-script",
    "esbenp.prettier-vscode",
    "github.copilot",
    "github.vscode-pull-request-github",
    "ibm.output-colorizer",
    "mhutchie.git-graph",
    "ms-azuretools.vscode-docker",
    "ms-kubernetes-tools.vscode-kubernetes-tools",
    "ms-playwright.playwright",
    "ms-vscode-remote.vscode-remote-extensionpack",
    "pkief.material-icon-theme",
    "quicktype.quicktype",
    "redhat.vscode-yaml",
    "ryanluker.vscode-coverage-gutters",
    "streetsidesoftware.code-spell-checker",
    "stylelint.vscode-stylelint",
    "tyriar.sort-lines"
  ]
}
</code>```

settings.json

```<code>{
  "[javascript]": {
    "editor.formatOnSave": false
  },
  "[javascriptreact]": {
    "editor.formatOnSave": false
  },
  "[jsonc]": {
    "editor.defaultFormatter": "vscode.json-language-features"
  },
  "[typescript]": {
    "editor.formatOnSave": false
  },
  "[typescriptreact]": {
    "editor.formatOnSave": false
  },
  "diffEditor.ignoreTrimWhitespace": false,
  "editor.bracketPairColorization.enabled": true,
  "editor.codeActionsOnSave": {
    "source.addMissingImports": true,
    "source.fixAll": false,
    "source.fixAll.eslint": true,
    "source.organizeImports": false
  },
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.formatOnPaste": false,
  "editor.formatOnSave": true,
  "editor.guides.bracketPairs": "active",
  "editor.inlineSuggest.enabled": true,
  "editor.suggestSelection": "first",
  "editor.tabSize": 2,
  "eslint.alwaysShowStatus": true,
  "eslint.format.enable": true,
  "eslint.probe": [
    "html",
    "javascript",
    "javascriptreact",
    "markdown",
    "typescript",
    "typescriptreact"
  ],
  "files.watcherExclude": {
    "**/*.pem": true,
    "**/*.tsbuildinfo": true,
    "**/.DS_Store": true,
    "**/.env.development.local": true,
    "**/.env.local": true,
    "**/.env.production.local": true,
    "**/.env.test.local": true,
    "**/.next/**": true,
    "**/.pnp.js": true,
    "**/.pnp/**": true,
    "**/.vercel": true,
    "**/build/**": true,
    "**/coverage/**": true,
    "**/node_modules/**": true,
    "**/npm-debug.log*": true,
    "**/out/**": true,
    "**/yarn-debug.log*": true,
    "**/yarn-error.log*": true
  },
  "github.copilot.enable": {
    "*": true,
    "markdown": false,
    "plaintext": true,
    "yaml": true
  },
  "redhat.telemetry.enabled": true,
  "sort-imports.ignore-type-defs": false,
  "stylelint.validate": [
    "css",
    "scss"
  ],
  "terminal.integrated.sendKeybindingsToShell": true,
  "window.zoomLevel": 1,
  "workbench.iconTheme": "material-icon-theme"
}
</code>```

Body:
I am using typescript and in *.tsx files, especially when i am copying code around, it quite often adds an additional

import React from "react";

    // ? On Save
    "editor.codeActionsOnSave": {
        "source.addMissingImports": true,
        "source.fixAll.eslint": true
        // "source.organizeImports": true
    }

Body:
I am using this configuration and works fine.

extensions.json

{
  "recommendations": [
    "amatiasq.sort-imports",
    "dbaeumer.vscode-eslint",
    "eamodio.gitlens",
    "eg2.vscode-npm-script",
    "esbenp.prettier-vscode",
    "github.copilot",
    "github.vscode-pull-request-github",
    "ibm.output-colorizer",
    "mhutchie.git-graph",
    "ms-azuretools.vscode-docker",
    "ms-kubernetes-tools.vscode-kubernetes-tools",
    "ms-playwright.playwright",
    "ms-vscode-remote.vscode-remote-extensionpack",
    "pkief.material-icon-theme",
    "quicktype.quicktype",
    "redhat.vscode-yaml",
    "ryanluker.vscode-coverage-gutters",
    "streetsidesoftware.code-spell-checker",
    "stylelint.vscode-stylelint",
    "tyriar.sort-lines"
  ]
}

settings.json

{
  "[javascript]": {
    "editor.formatOnSave": false
  },
  "[javascriptreact]": {
    "editor.formatOnSave": false
  },
  "[jsonc]": {
    "editor.defaultFormatter": "vscode.json-language-features"
  },
  "[typescript]": {
    "editor.formatOnSave": false
  },
  "[typescriptreact]": {
    "editor.formatOnSave": false
  },
  "diffEditor.ignoreTrimWhitespace": false,
  "editor.bracketPairColorization.enabled": true,
  "editor.codeActionsOnSave": {
    "source.addMissingImports": true,
    "source.fixAll": false,
    "source.fixAll.eslint": true,
    "source.organizeImports": false
  },
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.formatOnPaste": false,
  "editor.formatOnSave": true,
  "editor.guides.bracketPairs": "active",
  "editor.inlineSuggest.enabled": true,
  "editor.suggestSelection": "first",
  "editor.tabSize": 2,
  "eslint.alwaysShowStatus": true,
  "eslint.format.enable": true,
  "eslint.probe": [
    "html",
    "javascript",
    "javascriptreact",
    "markdown",
    "typescript",
    "typescriptreact"
  ],
  "files.watcherExclude": {
    "**/*.pem": true,
    "**/*.tsbuildinfo": true,
    "**/.DS_Store": true,
    "**/.env.development.local": true,
    "**/.env.local": true,
    "**/.env.production.local": true,
    "**/.env.test.local": true,
    "**/.next/**": true,
    "**/.pnp.js": true,
    "**/.pnp/**": true,
    "**/.vercel": true,
    "**/build/**": true,
    "**/coverage/**": true,
    "**/node_modules/**": true,
    "**/npm-debug.log*": true,
    "**/out/**": true,
    "**/yarn-debug.log*": true,
    "**/yarn-error.log*": true
  },
  "github.copilot.enable": {
    "*": true,
    "markdown": false,
    "plaintext": true,
    "yaml": true
  },
  "redhat.telemetry.enabled": true,
  "sort-imports.ignore-type-defs": false,
  "stylelint.validate": [
    "css",
    "scss"
  ],
  "terminal.integrated.sendKeybindingsToShell": true,
  "window.zoomLevel": 1,
  "workbench.iconTheme": "material-icon-theme"
}


问:
Trying to connect to Heroku: MongoParseError: URI malformedm cannot be parsed
I'm trying to post my app to Heroku for class and it keeps crashing. This is the error code I'm receiving. I'm not exactly sure what's happening, the H10 error is a blanket statement, maybe someone here could shed some light. This is what I'm getting when using heroku logs --tail.
Edit: My app works totally fine on my local machine, I'm only getting this error when trying to post to Heroku

```<code>2022-02-13T18:27:21.000000+00:00 app[api]: Build started by user nmendez6594@gmail.com
2022-02-13T18:27:38.841499+00:00 app[api]: Release v5 created by user nmendez6594@gmail.com
2022-02-13T18:27:38.841499+00:00 app[api]: Deploy 7d112609 by user nmendez6594@gmail.com
2022-02-13T18:27:39.000000+00:00 app[api]: Build succeeded
2022-02-13T18:27:39.104174+00:00 heroku[web.1]: State changed from crashed to starting
2022-02-13T18:27:40.901836+00:00 heroku[web.1]: Starting process with command `npm start`
2022-02-13T18:27:42.058731+00:00 app[web.1]:
2022-02-13T18:27:42.058745+00:00 app[web.1]: > budget-app@1.0.0 start
2022-02-13T18:27:42.058746+00:00 app[web.1]: > node server.js
2022-02-13T18:27:42.058746+00:00 app[web.1]:
2022-02-13T18:27:42.395832+00:00 app[web.1]: App running on port 55680!
2022-02-13T18:27:42.401378+00:00 app[web.1]: /app/node_modules/mongodb/lib/core/uri_parser.js:580
2022-02-13T18:27:42.401379+00:00 app[web.1]: return callback(new MongoParseError('URI malformed, cannot be parsed'));
2022-02-13T18:27:42.401380+00:00 app[web.1]: ^
2022-02-13T18:27:42.401380+00:00 app[web.1]:
2022-02-13T18:27:42.401380+00:00 app[web.1]: MongoParseError: URI malformed, cannot be parsed
2022-02-13T18:27:42.401381+00:00 app[web.1]: at parseConnectionString (/app/node_modules/mongodb/lib/core/uri_parser.js:580:21)
2022-02-13T18:27:42.401381+00:00 app[web.1]: at connect (/app/node_modules/mongodb/lib/operations/connect.js:283:3)
2022-02-13T18:27:42.401382+00:00 app[web.1]: at /app/node_modules/mongodb/lib/mongo_client.js:284:5
2022-02-13T18:27:42.401382+00:00 app[web.1]: at maybePromise (/app/node_modules/mongodb/lib/utils.js:692:3)
2022-02-13T18:27:42.401382+00:00 app[web.1]: at MongoClient.connect (/app/node_modules/mongodb/lib/mongo_client.js:280:10)
2022-02-13T18:27:42.401382+00:00 app[web.1]: at /app/node_modules/mongoose/lib/connection.js:836:12
2022-02-13T18:27:42.401383+00:00 app[web.1]: at new Promise (<anonymous>)
2022-02-13T18:27:42.401383+00:00 app[web.1]: at NativeConnection.Connection.openUri (/app/node_modules/mongoose/lib/connection.js:832:19)
2022-02-13T18:27:42.401384+00:00 app[web.1]: at /app/node_modules/mongoose/lib/index.js:351:10
2022-02-13T18:27:42.401384+00:00 app[web.1]: at /app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:32:5
2022-02-13T18:27:42.401384+00:00 app[web.1]: at new Promise (<anonymous>)
2022-02-13T18:27:42.401384+00:00 app[web.1]: at promiseOrCallback (/app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:10)
2022-02-13T18:27:42.401384+00:00 app[web.1]: at Mongoose._promiseOrCallback (/app/node_modules/mongoose/lib/index.js:1149:10)
2022-02-13T18:27:42.401385+00:00 app[web.1]: at Mongoose.connect (/app/node_modules/mongoose/lib/index.js:350:20)
2022-02-13T18:27:42.401385+00:00 app[web.1]: at Object.<anonymous> (/app/server.js:19:10)
2022-02-13T18:27:42.401385+00:00 app[web.1]: at Module._compile (node:internal/modules/cjs/loader:1103:14)
2022-02-13T18:27:42.521294+00:00 heroku[web.1]: Process exited with status 1
2022-02-13T18:27:42.598710+00:00 heroku[web.1]: State changed from starting to crashed
2022-02-13T18:27:48.281004+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=budget-app-pwa4.herokuapp.com request_id=5de2651b-5f3f-4a1e-84f2-18c0123b8dd7 fwd="32.215.142.46" dyno= connect= service= status=503 bytes= protocol=https
2022-02-13T18:27:49.746492+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=budget-app-pwa4.herokuapp.com request_id=f15d0dc1-7a19-49e1-a743-13f31cac6c31 fwd="32.215.142.46" dyno= connect= service= status=503 bytes= protocol=https
</code>```

This is my server.js file

```<code>const express = require("express");
const logger = require("morgan");
const mongoose = require("mongoose");
const compression = require("compression");

const PORT = process.env.PORT || 3001;
const MONGODB_URI = process.env.MONGODB_URI || "mongodb://localhost/budget";

const app = express();

app.use(logger("dev"));

app.use(compression());
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

app.use(express.static("public"));

mongoose.connect(MONGODB_URI, {
  useNewUrlParser: true,
  useFindAndModify: false,
  useUnifiedTopology: true
});

// routes
app.use(require("./routes/api.js"));

app.listen(PORT, () => {
  console.log(`App running on port ${PORT}!`);
});
</code>```

答:
Glancing at your log file, you can see that the top of the stack (at the point in which the exception is thrown) points to a parseConnectionString call. As you most likely deduced (since you included this in your title), the line above is a big clue as to what is going on:

MongoParseError: URI malformed, cannot be parsed

This indicates an issue with the connection string you are providing to the mongoose.connect function. Given the code you have shared, this can only be the result of an invalid process.env.MONGODB_URI value or the fallback mongodb://localhost/budget. Depending on how the MongoDB instance was provisioned, I might lean towards checking the value of the environment variable first, but if you are unsure about this, it might be best to first determine which of the two values your application is using (i.e., you could log this).

Overall, the issue appears to be related to the connection string you are using to connect to the MongoDB instance, and not explicitly caused by an issue with your application.

Body:
I'm trying to post my app to Heroku for class and it keeps crashing. This is the error code I'm receiving. I'm not exactly sure what's happening, the H10 error is a blanket statement, maybe someone here could shed some light. This is what I'm getting when using heroku logs --tail.
Edit: My app works totally fine on my local machine, I'm only getting this error when trying to post to Heroku

2022-02-13T18:27:21.000000+00:00 app[api]: Build started by user nmendez6594@gmail.com
2022-02-13T18:27:38.841499+00:00 app[api]: Release v5 created by user nmendez6594@gmail.com
2022-02-13T18:27:38.841499+00:00 app[api]: Deploy 7d112609 by user nmendez6594@gmail.com
2022-02-13T18:27:39.000000+00:00 app[api]: Build succeeded
2022-02-13T18:27:39.104174+00:00 heroku[web.1]: State changed from crashed to starting
2022-02-13T18:27:40.901836+00:00 heroku[web.1]: Starting process with command `npm start`
2022-02-13T18:27:42.058731+00:00 app[web.1]:
2022-02-13T18:27:42.058745+00:00 app[web.1]: > budget-app@1.0.0 start
2022-02-13T18:27:42.058746+00:00 app[web.1]: > node server.js
2022-02-13T18:27:42.058746+00:00 app[web.1]:
2022-02-13T18:27:42.395832+00:00 app[web.1]: App running on port 55680!
2022-02-13T18:27:42.401378+00:00 app[web.1]: /app/node_modules/mongodb/lib/core/uri_parser.js:580
2022-02-13T18:27:42.401379+00:00 app[web.1]: return callback(new MongoParseError('URI malformed, cannot be parsed'));
2022-02-13T18:27:42.401380+00:00 app[web.1]: ^
2022-02-13T18:27:42.401380+00:00 app[web.1]:
2022-02-13T18:27:42.401380+00:00 app[web.1]: MongoParseError: URI malformed, cannot be parsed
2022-02-13T18:27:42.401381+00:00 app[web.1]: at parseConnectionString (/app/node_modules/mongodb/lib/core/uri_parser.js:580:21)
2022-02-13T18:27:42.401381+00:00 app[web.1]: at connect (/app/node_modules/mongodb/lib/operations/connect.js:283:3)
2022-02-13T18:27:42.401382+00:00 app[web.1]: at /app/node_modules/mongodb/lib/mongo_client.js:284:5
2022-02-13T18:27:42.401382+00:00 app[web.1]: at maybePromise (/app/node_modules/mongodb/lib/utils.js:692:3)
2022-02-13T18:27:42.401382+00:00 app[web.1]: at MongoClient.connect (/app/node_modules/mongodb/lib/mongo_client.js:280:10)
2022-02-13T18:27:42.401382+00:00 app[web.1]: at /app/node_modules/mongoose/lib/connection.js:836:12
2022-02-13T18:27:42.401383+00:00 app[web.1]: at new Promise (<anonymous>)
2022-02-13T18:27:42.401383+00:00 app[web.1]: at NativeConnection.Connection.openUri (/app/node_modules/mongoose/lib/connection.js:832:19)
2022-02-13T18:27:42.401384+00:00 app[web.1]: at /app/node_modules/mongoose/lib/index.js:351:10
2022-02-13T18:27:42.401384+00:00 app[web.1]: at /app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:32:5
2022-02-13T18:27:42.401384+00:00 app[web.1]: at new Promise (<anonymous>)
2022-02-13T18:27:42.401384+00:00 app[web.1]: at promiseOrCallback (/app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:10)
2022-02-13T18:27:42.401384+00:00 app[web.1]: at Mongoose._promiseOrCallback (/app/node_modules/mongoose/lib/index.js:1149:10)
2022-02-13T18:27:42.401385+00:00 app[web.1]: at Mongoose.connect (/app/node_modules/mongoose/lib/index.js:350:20)
2022-02-13T18:27:42.401385+00:00 app[web.1]: at Object.<anonymous> (/app/server.js:19:10)
2022-02-13T18:27:42.401385+00:00 app[web.1]: at Module._compile (node:internal/modules/cjs/loader:1103:14)
2022-02-13T18:27:42.521294+00:00 heroku[web.1]: Process exited with status 1
2022-02-13T18:27:42.598710+00:00 heroku[web.1]: State changed from starting to crashed
2022-02-13T18:27:48.281004+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=budget-app-pwa4.herokuapp.com request_id=5de2651b-5f3f-4a1e-84f2-18c0123b8dd7 fwd="32.215.142.46" dyno= connect= service= status=503 bytes= protocol=https
2022-02-13T18:27:49.746492+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=budget-app-pwa4.herokuapp.com request_id=f15d0dc1-7a19-49e1-a743-13f31cac6c31 fwd="32.215.142.46" dyno= connect= service= status=503 bytes= protocol=https

This is my server.js file

const express = require("express");
const logger = require("morgan");
const mongoose = require("mongoose");
const compression = require("compression");

const PORT = process.env.PORT || 3001;
const MONGODB_URI = process.env.MONGODB_URI || "mongodb://localhost/budget";

const app = express();

app.use(logger("dev"));

app.use(compression());
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

app.use(express.static("public"));

mongoose.connect(MONGODB_URI, {
  useNewUrlParser: true,
  useFindAndModify: false,
  useUnifiedTopology: true
});

// routes
app.use(require("./routes/api.js"));

app.listen(PORT, () => {
  console.log(`App running on port ${PORT}!`);
});


问:
When converting from SVN to Git, how do I put the revision number in the commit message?
We will be converting our repository from Subversion to Git, but would like to be able to retain the SVN revision number as comments in the bug tracker regularly reference it.

We will be using git svn clone and the process described in John Albin's blog.

Is there a way to include the revision number in the commit message?  I'd prefer to do it during the clone, but a post-processing step would be acceptable.

Yes, I know about git svn find-rev, but that requires the SVN repository stick around and the user has network access to it.

答:
It's not clear why you would want the svn revision number in the commit message. As @John Flatness indicates, the git-svn includes the svn revision number in the commit messages.

We found it more useful to create tags for each revision. This seems to better parallel the usefulness of the svn revision numbers. A script that uses git svn find-rev quickly added 10000 tags. Now we can access any historical svn revision number.

Per request here is the script (added here because comments don't seem to handle code well)

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

declare -i rev

for ((rev = 1; rev < 100; ++rev))
do
    hash=$(git svn find-rev "r$rev")
    if [ -z $hash ]; then
        break
    fi
    # TODO Pad with 0's for small values of rev
    tag="svn_r$rev"
    git tag -a -m "$tag" $tag $hash
done
</code>```

This just does the first 100 revisions. We stepped by by a 1000 for the first 5000 revs then by a 100. The last 2000 or so commits have individual tags.

Body:
It's not clear why you would want the svn revision number in the commit message. As @John Flatness indicates, the git-svn includes the svn revision number in the commit messages.

We found it more useful to create tags for each revision. This seems to better parallel the usefulness of the svn revision numbers. A script that uses git svn find-rev quickly added 10000 tags. Now we can access any historical svn revision number.

Per request here is the script (added here because comments don't seem to handle code well)

#!/bin/bash

declare -i rev

for ((rev = 1; rev < 100; ++rev))
do
    hash=$(git svn find-rev "r$rev")
    if [ -z $hash ]; then
        break
    fi
    # TODO Pad with 0's for small values of rev
    tag="svn_r$rev"
    git tag -a -m "$tag" $tag $hash
done

This just does the first 100 revisions. We stepped by by a 1000 for the first 5000 revs then by a 100. The last 2000 or so commits have individual tags.


问:
asp.net core, Any library to get distance and time travel between two locations
Is there any library that get distance and time travel between two locations with options like: Legs, Vehicle, Bikes ...

I don't want to use  google maps because I have to call an api on their server.

any help please

答:
I think I found this library, It's easy to use

https://docs.mapbox.com/api/navigation/map-matching/

you can create an account and get a key then call an API url to get distance, duration, Like this:

https://api.mapbox.com/matching/v5/mapbox/driving/-117.17282,32.71204;-117.17288,32.71225;-117.17293,32.71244;-117.17292,32.71256?approaches=curb;curb;curb;curb&access_token=pk.eyJ1Ijoibm92ZXJzbWFwIiwiYSI6ImNreTdwc3ppNTE3dzkyb3B2MnVzNXpueTUifQ.csYTL2GKkl99Yqk_TQjr5w


问:
RRDTOOL - left-axis-format - 3-4 digit numbers not working
My left axis is not formatting the numbers the way I want.
I have the range set as:

```<code>-l 400 -u 1400 -r
</code>```

I want the numbers/labels on the left (Y) axis to look like

400, 500, ... 1000, 1100

Not 0.4 k, 0.5 k, .... 1.0 k, 1.1 k

If I put this format instruction in,

```<code>--left-axis-format %4.0lf
</code>```

I get 0, 0, 1, ... 1, 1

```<code>--left-axis-format %4.1lf
</code>```

I get 0.4, 0.5, ... 1.0, 1.1, ...

答:
Exponents. Took a bit to dig deeper into the manual.</p>
```<code>--units-exponent 0 \
--left-axis-format %4.0lf \
</code>```

Body:
My left axis is not formatting the numbers the way I want.
I have the range set as:

-l 400 -u 1400 -r

I want the numbers/labels on the left (Y) axis to look like

400, 500, ... 1000, 1100

Not 0.4 k, 0.5 k, .... 1.0 k, 1.1 k

If I put this format instruction in,

--left-axis-format %4.0lf

I get 0, 0, 1, ... 1, 1

--left-axis-format %4.1lf

I get 0.4, 0.5, ... 1.0, 1.1, ...

Body:
Exponents. Took a bit to dig deeper into the manual.

--units-exponent 0 \
--left-axis-format %4.0lf \


问:
How to set file destination in React?
I'm following up on this article to download objects from GCP Cloud storage bucket: https://cloud.google.com/storage/docs/downloading-objects#storage-download-object-nodejs In the code, I want to set the destination where file needs to be saved dynamically. How can I set file destination in React?</p>

答:
just set desFileName:</p>
```<code>const destFileName = '/local/path/to/file.txt';
async function downloadFile() {
      const options = {
        destination: destFileName,
      };

      // Downloads the file
      await storage.bucket(bucketName).file(fileName).download(options);

      console.log(
        `gs://${bucketName}/${fileName} downloaded to ${destFileName}.`
      );
    }
</code>```

Title: How to set file destination in React?

Body:
just set desFileName:

const destFileName = '/local/path/to/file.txt';
async function downloadFile() {
      const options = {
        destination: destFileName,
      };

      // Downloads the file
      await storage.bucket(bucketName).file(fileName).download(options);

      console.log(
        `gs://${bucketName}/${fileName} downloaded to ${destFileName}.`
      );
    }


问:
Mixing pure and impure with Cats Effect
Suppose we have a two-stage pure method.

```<code>  def filterPositivePure(seq: Seq[Int]): Seq[Int] =
    if (seq.nonEmpty) {
      val sorted = seq.sorted
      sorted.filter(_ > 0)
    }
    else seq
</code>```

We needed to log the intermediate result of the calculations or any other impure action.

```<code>  def filterPositiveImpure(seq: Seq[Int]): Seq[Int] =
    if (seq.nonEmpty) {
      val sorted = seq.sorted
      println(sorted)
      sorted.filter(_ > 0)
    }
    else seq
</code>```

Then to preserve purity, we wrapped in IO the output to the log, the rest of the calculations and the result of the entire alternative if branch.

```<code>  def filterPositiveIO(seq: Seq[Int]): IO[Seq[Int]] =
    if (seq.nonEmpty) {
      val sorted = seq.sorted
      IO(println(sorted)) *> IO(sorted.filter(_ > 0))
    }
    else IO(seq)
</code>```

Is there a more coincise way to bring purity back?

答:
I think better way is working on one action as a new effect and write separate function for logging:

import cats.syntax.flatMap._
// this three imports is just to make show is working
import cats.syntax.show._
import cats.instances.list._
import cats.instances.int._

// now function looks more structural and without multiple using sorted list
def filterPositiveIO(seq: Seq[Int]): IO[Seq[Int]] = {
  if (seq.nonEmpty)
    withLogging(seq.toList.sorted).map(_.filter(_ > 0))
  else
    IO(seq)
}

// this function is just for making some logging effect and return lifted value into IO
def withLogging[A: Show](value: A): IO[A] = logging(value.show) >> IO(value)

// here you should make logging effect
def logging(strExpr: => String): IO[Unit] = ???
```

Title: Mixing pure and impure with Cats Effect

Body:
Suppose we have a two-stage pure method.

  def filterPositivePure(seq: Seq[Int]): Seq[Int] =
    if (seq.nonEmpty) {
      val sorted = seq.sorted
      sorted.filter(_ > 0)
    }
    else seq

We needed to log the intermediate result of the calculations or any other impure action.

  def filterPositiveImpure(seq: Seq[Int]): Seq[Int] =
    if (seq.nonEmpty) {
      val sorted = seq.sorted
      println(sorted)
      sorted.filter(_ > 0)
    }
    else seq

Then to preserve purity, we wrapped in IO the output to the log, the rest of the calculations and the result of the entire alternative if branch.

  def filterPositiveIO(seq: Seq[Int]): IO[Seq[Int]] =
    if (seq.nonEmpty) {
      val sorted = seq.sorted
      IO(println(sorted)) *> IO(sorted.filter(_ > 0))
    }
    else IO(seq)

Is there a more coincise way to bring purity back?


问:
Resolve a promise in a TypeScript type
This is a continuation of a question about resolving return types. I'm so close to what I'm looking to do (which is to have a common function to build model instances based on validated data) and it works fine in JS, but I can't figure out the final part for the TS typing.

The key is the return for my Init type - specifically the Builder<T[K]> part. I understand why that results in Builder<(id: number) => Promise<Test>> as the returned type, but I can't for the life of me figure out how to tell TS that in fact it is just Test being returned, not the function that returns a Promise of Test.

The following can be copy / pasted into VSCode (or whatever) to show the issue. The ter1 variable should be an instance of Test, and when compiled to JS it is, but TS doesn't see that.

```<code>export interface Builder<T> {
    (values: any, db: any): Promise<T>
}

export interface Wrapper {
    <T, TId>(
        construct: (id: TId, db: any | null) => Promise<T>,
        idSrc: string | string[],
        errorMsg: string
    ): Builder<T>
}

let builder: Wrapper = function (construct, idSrc, errorMsg ) {
    // A function that can be used to construct the instance
    return async function(values: any, db: any | null) {
        let id = null;
        let inst = await construct(id, db);

        if (!inst) {
            throw new Error(errorMsg);
        }

        return inst;
    };
}

class Test {
    is1 = true;

    static async fromId( id: number ) {
        var inst = new Test();
        // Some async action (e.g. a db read)
        return inst;
    }
}
class Test2 {
    is2 = true;

    static async fromId( id: number ) {
        var inst = new Test2();
        // Some async action (e.g. a db read)
        return inst;
    }
}

type Config<T extends {}> = {
    inputs?: {[index:string]: any},
    inst?: T;
};

type Init = <T extends {[key:string]: any}>(
    db: any,
    config: Config<T>
) => Promise<{[K in keyof T]: Builder<T[K]>}>; // ???

let init: Init = async function ( db, config ) {
    let ret: any = {};

    if ( config.inst ) {
        for (let [key, value] of Object.entries(config.inst)) {
            let res = await value( {}, {} );
            ret[ key ] = res;
        }
    }

    return ret;
}

async function allan () {
    let { ter1, ter2 } = await init( null, {
        inst: {
            ter1: Test.fromId,
            ter2: Test2.fromId
        }
    } );

    console.log( ter1.is1, ter1.is2 ); // should be `true undefined`

    // Test `builder` typing
    var t1Wrapper = builder( Test.fromId, 'id', 'test');
    var t2Wrapper = builder( Test2.fromId, 'id', 'test');

    var t1 = await t1Wrapper({}, {});
    var t2 = await t2Wrapper({}, {});

    t1.is1;
    t2.is2;
}

allan();
</code>```

Thank you!

答:
Just use AsyncReturnType from type-fest!

type-fest has something identical to @jcalz's Unpromise - it's simply named PromiseValue instead.

AsyncReturnType<FOO> is basically just PromiseValue<ReturnType<FOO>>

So, go ahead:

```<code>npm install type-fest --save-dev
</code>```
```<code>yarn add type-fest --dev
</code>```

And use like so:

```<code>type ServerData = AsyncReturnType<typeof getServerData>
</code>```

Title: Resolve a promise in a TypeScript type

Body:
This is a continuation of a question about resolving return types. I'm so close to what I'm looking to do (which is to have a common function to build model instances based on validated data) and it works fine in JS, but I can't figure out the final part for the TS typing.

The key is the return for my Init type - specifically the Builder<T[K]> part. I understand why that results in Builder<(id: number) => Promise<Test>> as the returned type, but I can't for the life of me figure out how to tell TS that in fact it is just Test being returned, not the function that returns a Promise of Test.

The following can be copy / pasted into VSCode (or whatever) to show the issue. The ter1 variable should be an instance of Test, and when compiled to JS it is, but TS doesn't see that.

export interface Builder<T> {
    (values: any, db: any): Promise<T>
}

export interface Wrapper {
    <T, TId>(
        construct: (id: TId, db: any | null) => Promise<T>,
        idSrc: string | string[],
        errorMsg: string
    ): Builder<T>
}

let builder: Wrapper = function (construct, idSrc, errorMsg ) {
    // A function that can be used to construct the instance
    return async function(values: any, db: any | null) {
        let id = null;
        let inst = await construct(id, db);

        if (!inst) {
            throw new Error(errorMsg);
        }

        return inst;
    };
}

class Test {
    is1 = true;

    static async fromId( id: number ) {
        var inst = new Test();
        // Some async action (e.g. a db read)
        return inst;
    }
}
class Test2 {
    is2 = true;

    static async fromId( id: number ) {
        var inst = new Test2();
        // Some async action (e.g. a db read)
        return inst;
    }
}

type Config<T extends {}> = {
    inputs?: {[index:string]: any},
    inst?: T;
};

type Init = <T extends {[key:string]: any}>(
    db: any,
    config: Config<T>
) => Promise<{[K in keyof T]: Builder<T[K]>}>; // ???

let init: Init = async function ( db, config ) {
    let ret: any = {};

    if ( config.inst ) {
        for (let [key, value] of Object.entries(config.inst)) {
            let res = await value( {}, {} );
            ret[ key ] = res;
        }
    }

    return ret;
}

async function allan () {
    let { ter1, ter2 } = await init( null, {
        inst: {
            ter1: Test.fromId,
            ter2: Test2.fromId
        }
    } );

    console.log( ter1.is1, ter1.is2 ); // should be `true undefined`

    // Test `builder` typing
    var t1Wrapper = builder( Test.fromId, 'id', 'test');
    var t2Wrapper = builder( Test2.fromId, 'id', 'test');

    var t1 = await t1Wrapper({}, {});
    var t2 = await t2Wrapper({}, {});

    t1.is1;
    t2.is2;
}

allan();

Thank you!

Body:
Just use AsyncReturnType from type-fest!

type-fest has something identical to @jcalz's Unpromise - it's simply named PromiseValue instead.

AsyncReturnType<FOO> is basically just PromiseValue<ReturnType<FOO>>

So, go ahead:

npm install type-fest --save-dev

yarn add type-fest --dev

And use like so:

type ServerData = AsyncReturnType<typeof getServerData>


问:
PHP Print statement works only in Firefox
The site is built in drupal. The following code calls some data for the page:

```<code><span class="bold caps">Length: </span><?php print $node->field_length[0]['view'];?>
</code>```

The right information shows up when viewing the page in Firefox but that's it. Chrome, IE & Safari are all missing the info. The rendered HTML is fine but for the lack of the right data coming through.

Here is a link to the page in question

Any ideas?

答:
If you view source in each browser you should find that the source looks exactly the same in every browser.

Here are the validation errors on your page.

http://validator.w3.org/check?uri=http%3A%2F%2Fmsvehicles.com%2Fgsa%2Fmobile-mammography-clinic-msv-m-4000-102-40-b&charset=%28detect+automatically%29&doctype=Inline&group=0

Fix all of these and your problem will probably fix itself.

Body:
The site is built in drupal. The following code calls some data for the page:

Length: <?php print $node->field_length[0]['view'];?>

The right information shows up when viewing the page in Firefox but that's it. Chrome, IE & Safari are all missing the info. The rendered HTML is fine but for the lack of the right data coming through.

Here is a link to the page in question

Any ideas?


问:
Unhandled Runtime Error while executing a JS code
On my Localhost:3000, when I am running the code, I am getting an error saying:

```<code>Unhandled Runtime Error
TypeError: Cannot read properties of undefined (reading 'id')
</code>```

For the Source part, it is showing a certain section of my code, which is:-

```<code>    ;(async () => {
  20 |     setSelectedMarketNft(
> 21 |       listings.find((marketNft) => marketNft.asset?.id === selectedNft.id)
     |                                                                       ^
  22 |     )
  23 |   })()
  24 | }, [selectedNft, listings, isListed])
</code>```

There are certain questions of the similar type on stackOverflow, but I am unable to find any answers from any of them. I am making a web3 project, where I am using next.js, sanity and thirweb.

The source code that contains this is:-

```<code> const MakeOffer = ({ isListed, selectedNft, listings, marketPlaceModule }) => {
  const [selectedMarketNft, setSelectedMarketNft] = useState()
  const [enableButton, setEnableButton] = useState(false)

  useEffect(() => {
    if (!listings || isListed === 'false') return
    ;(async () => {
      setSelectedMarketNft(
        listings.find((marketNft) => marketNft.asset?.id === selectedNft.id)
      )
    })()
  }, [selectedNft, listings, isListed])

  useEffect(() => {
    if (!selectedMarketNft || !selectedNft) return

    setEnableButton(true)
  }, [selectedMarketNft, selectedNft])
</code>```

Link to the full source code of the file where this error is occuring is:-
https://github.com/hemang-h/Standard-Demo-Marketplace-and-Minting/blob/main/components/nft/Purchase.js

Can anyone guide me what I am doing wrong here?

EXTRAS
Just for a better understanding, this is the full source code of the file where I am facing this error:

```<code>import { useEffect, useState } from 'react'

import { HiTag } from 'react-icons/hi'
import { IoMdWallet } from 'react-icons/io'
import toast, { Toaster } from 'react-hot-toast'

const style = {
  button: `mr-8 flex items-center py-2 px-12 rounded-lg cursor-pointer`,
  buttonIcon: `text-xl`,
  buttonText: `ml-2 text-lg font-semibold`,
}

const MakeOffer = ({ isListed, selectedNft, listings, marketPlaceModule }) => {
  const [selectedMarketNft, setSelectedMarketNft] = useState()
  const [enableButton, setEnableButton] = useState(false)

  useEffect(() => {
    if (!listings || isListed === 'false') return
    ;(async () => {
      setSelectedMarketNft(
        listings.find((marketNft) => marketNft.asset?.id === selectedNft.id)
      )
    })()
  }, [selectedNft, listings, isListed])

  useEffect(() => {
    if (!selectedMarketNft || !selectedNft) return

    setEnableButton(true)
  }, [selectedMarketNft, selectedNft])

  const confirmPurchase = (toastHandler = toast) =>
    toastHandler.success(`Purchase successful!`, {
      style: {
        background: '#04111d',
        color: '#fff',
      },
    })

  const buyItem = async (
    listingId = selectedMarketNft.id,
    quantityDesired = 1,
    module = marketPlaceModule
  ) => {
    console.log(listingId, quantityDesired, module, 'david')
    // yo RAZA lets goooo!!!
    //yo Qazi, ok
    // sure okay about to run it...
    // just clicked buy now...
    // still error
    // where can i see the contract address of the marketplace module
    // in [nftId.js]
    await module
      .buyoutDirectListing({
        listingId: listingId,
        quantityDesired: quantityDesired,
      })
      .catch((error) => console.error(error))

    confirmPurchase()
  }

  return (
    <div className="flex h-20 w-full items-center rounded-lg border border-[#151c22] bg-[#303339] px-12">
      <Toaster position="bottom-left" reverseOrder={false} />
      {isListed === 'true' ? (
        <>
          <div
            onClick={() => {
              enableButton ? buyItem(selectedMarketNft.id, 1) : null
            }}
            className={`${style.button} bg-[#2081e2] hover:bg-[#42a0ff]`}
          >
            <IoMdWallet className={style.buttonIcon} />
            <div className={style.buttonText}>Buy Now</div>
          </div>
          <div
            className={`${style.button} border border-[#151c22]  bg-[#363840] hover:bg-[#4c505c]`}
          >
            <HiTag className={style.buttonIcon} />
            <div className={style.buttonText}>Make Offer</div>
          </div>
        </>
      ) : (
        <div className={`${style.button} bg-[#2081e2] hover:bg-[#42a0ff]`}>
          <IoMdWallet className={style.buttonIcon} />
          <div className={style.buttonText}>List Item</div>
        </div>
      )}
    </div>
  )
}

export default MakeOffer
</code>```

答:
The error is solved, turns out that I just had to add

```<code>if(!selectedNft) return;
</code>```

to successfully run my code. Final code will be as:

```<code>import { useEffect, useState } from 'react'

import { HiTag } from 'react-icons/hi'
import { IoMdWallet } from 'react-icons/io'
import toast, { Toaster } from 'react-hot-toast'

const style = {
  button: `mr-8 flex items-center py-2 px-12 rounded-lg cursor-pointer`,
  buttonIcon: `text-xl`,
  buttonText: `ml-2 text-lg font-semibold`,
}

const MakeOffer = ({ isListed, selectedNft, listings, marketPlaceModule }) => {
  const [selectedMarketNft, setSelectedMarketNft] = useState()
  const [enableButton, setEnableButton] = useState(false)

  useEffect(() => {
    if(!selectedNft) return;
    if (!listings || isListed === 'false') return
    ;(async () => {
      setSelectedMarketNft(
        listings.find((marketNft) => marketNft.asset?.id === selectedNft.id)
      )
    })()
  }, [selectedNft, listings, isListed])

  useEffect(() => {
    if (!selectedMarketNft || !selectedNft) return

    setEnableButton(true)
  }, [selectedMarketNft, selectedNft])

  const confirmPurchase = (toastHandler = toast) =>
    toastHandler.success(`Purchase successful!`, {
      style: {
        background: '#04111d',
        color: '#fff',
      },
    })

  const buyItem = async (
    listingId = selectedMarketNft.id,
    quantityDesired = 1,
    module = marketPlaceModule
  ) => {
    console.log(listingId, quantityDesired, module, 'david')
    // yo RAZA lets goooo!!!
    //yo Qazi, ok
    // sure okay about to run it...
    // just clicked buy now...
    // still error
    // where can i see the contract address of the marketplace module
    // in [nftId.js]
    await module
      .buyoutDirectListing({
        listingId: listingId,
        quantityDesired: quantityDesired,
      })
      .catch((error) => console.error(error))

    confirmPurchase()
  }

  return (
    <div className="flex h-20 w-full items-center rounded-lg border border-[#151c22] bg-[#303339] px-12">
      <Toaster position="bottom-left" reverseOrder={false} />
      {isListed === 'true' ? (
        <>
          <div
            onClick={() => {
              enableButton ? buyItem(selectedMarketNft.id, 1) : null
            }}
            className={`${style.button} bg-[#2081e2] hover:bg-[#42a0ff]`}
          >
            <IoMdWallet className={style.buttonIcon} />
            <div className={style.buttonText}>Buy Now</div>
          </div>
          <div
            className={`${style.button} border border-[#151c22]  bg-[#363840] hover:bg-[#4c505c]`}
          >
            <HiTag className={style.buttonIcon} />
            <div className={style.buttonText}>Make Offer</div>
          </div>
        </>
      ) : (
        <div className={`${style.button} bg-[#2081e2] hover:bg-[#42a0ff]`}>
          <IoMdWallet className={style.buttonIcon} />
          <div className={style.buttonText}>List Item</div>
        </div>
      )}
    </div>
  )
}

export default MakeOffer
</code>```

Body:
On my Localhost:3000, when I am running the code, I am getting an error saying:

Unhandled Runtime Error
TypeError: Cannot read properties of undefined (reading 'id')

For the Source part, it is showing a certain section of my code, which is:-

    ;(async () => {
  20 |     setSelectedMarketNft(
> 21 |       listings.find((marketNft) => marketNft.asset?.id === selectedNft.id)
     |                                                                       ^
  22 |     )
  23 |   })()
  24 | }, [selectedNft, listings, isListed])

There are certain questions of the similar type on stackOverflow, but I am unable to find any answers from any of them. I am making a web3 project, where I am using next.js, sanity and thirweb.

The source code that contains this is:-

 const MakeOffer = ({ isListed, selectedNft, listings, marketPlaceModule }) => {
  const [selectedMarketNft, setSelectedMarketNft] = useState()
  const [enableButton, setEnableButton] = useState(false)

  useEffect(() => {
    if (!listings || isListed === 'false') return
    ;(async () => {
      setSelectedMarketNft(
        listings.find((marketNft) => marketNft.asset?.id === selectedNft.id)
      )
    })()
  }, [selectedNft, listings, isListed])

  useEffect(() => {
    if (!selectedMarketNft || !selectedNft) return

    setEnableButton(true)
  }, [selectedMarketNft, selectedNft])

Link to the full source code of the file where this error is occuring is:-
https://github.com/hemang-h/Standard-Demo-Marketplace-and-Minting/blob/main/components/nft/Purchase.js

Can anyone guide me what I am doing wrong here?

EXTRAS
Just for a better understanding, this is the full source code of the file where I am facing this error:

import { useEffect, useState } from 'react'

import { HiTag } from 'react-icons/hi'
import { IoMdWallet } from 'react-icons/io'
import toast, { Toaster } from 'react-hot-toast'

const style = {
  button: `mr-8 flex items-center py-2 px-12 rounded-lg cursor-pointer`,
  buttonIcon: `text-xl`,
  buttonText: `ml-2 text-lg font-semibold`,
}

const MakeOffer = ({ isListed, selectedNft, listings, marketPlaceModule }) => {
  const [selectedMarketNft, setSelectedMarketNft] = useState()
  const [enableButton, setEnableButton] = useState(false)

  useEffect(() => {
    if (!listings || isListed === 'false') return
    ;(async () => {
      setSelectedMarketNft(
        listings.find((marketNft) => marketNft.asset?.id === selectedNft.id)
      )
    })()
  }, [selectedNft, listings, isListed])

  useEffect(() => {
    if (!selectedMarketNft || !selectedNft) return

    setEnableButton(true)
  }, [selectedMarketNft, selectedNft])

  const confirmPurchase = (toastHandler = toast) =>
    toastHandler.success(`Purchase successful!`, {
      style: {
        background: '#04111d',
        color: '#fff',
      },
    })

  const buyItem = async (
    listingId = selectedMarketNft.id,
    quantityDesired = 1,
    module = marketPlaceModule
  ) => {
    console.log(listingId, quantityDesired, module, 'david')
    // yo RAZA lets goooo!!!
    //yo Qazi, ok
    // sure okay about to run it...
    // just clicked buy now...
    // still error
    // where can i see the contract address of the marketplace module
    // in [nftId.js]
    await module
      .buyoutDirectListing({
        listingId: listingId,
        quantityDesired: quantityDesired,
      })
      .catch((error) => console.error(error))

    confirmPurchase()
  }

  return (

      <Toaster position="bottom-left" reverseOrder={false} />
      {isListed === 'true' ? (
        <>

 {
              enableButton ? buyItem(selectedMarketNft.id, 1) : null
            }}
            className={`${style.button} bg-[#2081e2] hover:bg-[#42a0ff]`}
          >
            <IoMdWallet className={style.buttonIcon} />

Buy Now

          <div
            className={`${style.button} border border-[#151c22]  bg-[#363840] hover:bg-[#4c505c]`}
          >
            <HiTag className={style.buttonIcon} />

Make Offer

        </>
      ) : (
        <div className={`${style.button} bg-[#2081e2] hover:bg-[#42a0ff]`}>
          <IoMdWallet className={style.buttonIcon} />

List Item

      )}

  )
}

export default MakeOffer

Body:
The error is solved, turns out that I just had to add

if(!selectedNft) return;

to successfully run my code. Final code will be as:

import { useEffect, useState } from 'react'

import { HiTag } from 'react-icons/hi'
import { IoMdWallet } from 'react-icons/io'
import toast, { Toaster } from 'react-hot-toast'

const style = {
  button: `mr-8 flex items-center py-2 px-12 rounded-lg cursor-pointer`,
  buttonIcon: `text-xl`,
  buttonText: `ml-2 text-lg font-semibold`,
}

const MakeOffer = ({ isListed, selectedNft, listings, marketPlaceModule }) => {
  const [selectedMarketNft, setSelectedMarketNft] = useState()
  const [enableButton, setEnableButton] = useState(false)

  useEffect(() => {
    if(!selectedNft) return;
    if (!listings || isListed === 'false') return
    ;(async () => {
      setSelectedMarketNft(
        listings.find((marketNft) => marketNft.asset?.id === selectedNft.id)
      )
    })()
  }, [selectedNft, listings, isListed])

  useEffect(() => {
    if (!selectedMarketNft || !selectedNft) return

    setEnableButton(true)
  }, [selectedMarketNft, selectedNft])

  const confirmPurchase = (toastHandler = toast) =>
    toastHandler.success(`Purchase successful!`, {
      style: {
        background: '#04111d',
        color: '#fff',
      },
    })

  const buyItem = async (
    listingId = selectedMarketNft.id,
    quantityDesired = 1,
    module = marketPlaceModule
  ) => {
    console.log(listingId, quantityDesired, module, 'david')
    // yo RAZA lets goooo!!!
    //yo Qazi, ok
    // sure okay about to run it...
    // just clicked buy now...
    // still error
    // where can i see the contract address of the marketplace module
    // in [nftId.js]
    await module
      .buyoutDirectListing({
        listingId: listingId,
        quantityDesired: quantityDesired,
      })
      .catch((error) => console.error(error))

    confirmPurchase()
  }

  return (
    <div className="flex h-20 w-full items-center rounded-lg border border-[#151c22] bg-[#303339] px-12">
      <Toaster position="bottom-left" reverseOrder={false} />
      {isListed === 'true' ? (
        <>
          <div
            onClick={() => {
              enableButton ? buyItem(selectedMarketNft.id, 1) : null
            }}
            className={`${style.button} bg-[#2081e2] hover:bg-[#42a0ff]`}
          >
            <IoMdWallet className={style.buttonIcon} />
            <div className={style.buttonText}>Buy Now</div>
          </div>
          <div
            className={`${style.button} border border-[#151c22]  bg-[#363840] hover:bg-[#4c505c]`}
          >
            <HiTag className={style.buttonIcon} />
            <div className={style.buttonText}>Make Offer</div>
          </div>
        </>
      ) : (
        <div className={`${style.button} bg-[#2081e2] hover:bg-[#42a0ff]`}>
          <IoMdWallet className={style.buttonIcon} />
          <div className={style.buttonText}>List Item</div>
        </div>
      )}
    </div>
  )
}

export default MakeOffer


问:
CocoaPods could not find compatible versions for pod "FBSDKCoreKit"
I am having trouble using this library, I followed the instructions with the facebook guide that appears on the readMe and did all the steps.

Before this, I used the react-native-fbsdk library which is now deprecated due to facebook releasing a newer version (0.9) of the SDK. In the instructions here says that you can add the pod that you need in the podfile of ios but when I add them and then pod install I get this error:

```<code>[!] CocoaPods could not find compatible versions for pod "FBSDKCoreKit":
  In snapshot (Podfile.lock):
    FBSDKCoreKit (= 9.0.1, ~> 9.0.1)

  In Podfile:
    FacebookShare was resolved to 0.1.1, which depends on
      FBSDKCoreKit (~> 4.14)

react-native-fbsdk-next (from `../node_modules/react-native-fbsdk-next`) was resolved to 4.0.0, which depends on
  react-native-fbsdk-next/Core (= 4.0.0) was resolved to 4.0.0, which depends on
    FBSDKCoreKit (~> 9.0.1)

You have either:
 * out-of-date source repos which you can update with `pod repo update` or with `pod install --repo-update`.
 * changed the constraints of dependency `FBSDKCoreKit` inside your development pod `react-native-fbsdk-next`.

You should run `pod update FBSDKCoreKit` to apply changes you've made.
</code>```

Also, with this library you need to modify the appDelegate.m here but when I add that code it says I am missing an import, I know the import missing is FBSDKCoreKit or at least I think it is because the previous SDK used that one. To fix that you need to add the pod but when I add it the error above shows up.
I don't know if I need the other library because of that dependency. please help!

答:
Was facing the same issue in my Mac M1 & solved this by running this command.</p>
```<code>1- cd ios
2- arch -x86_64 pod install --repo-update
</code>```

Body:
I am having trouble using this library, I followed the instructions with the facebook guide that appears on the readMe and did all the steps.

Before this, I used the react-native-fbsdk library which is now deprecated due to facebook releasing a newer version (0.9) of the SDK. In the instructions here says that you can add the pod that you need in the podfile of ios but when I add them and then pod install I get this error:

[!] CocoaPods could not find compatible versions for pod "FBSDKCoreKit":
  In snapshot (Podfile.lock):
    FBSDKCoreKit (= 9.0.1, ~> 9.0.1)

  In Podfile:
    FacebookShare was resolved to 0.1.1, which depends on
      FBSDKCoreKit (~> 4.14)

react-native-fbsdk-next (from `../node_modules/react-native-fbsdk-next`) was resolved to 4.0.0, which depends on
  react-native-fbsdk-next/Core (= 4.0.0) was resolved to 4.0.0, which depends on
    FBSDKCoreKit (~> 9.0.1)

You have either:
 * out-of-date source repos which you can update with `pod repo update` or with `pod install --repo-update`.
 * changed the constraints of dependency `FBSDKCoreKit` inside your development pod `react-native-fbsdk-next`.

You should run `pod update FBSDKCoreKit` to apply changes you've made.

Also, with this library you need to modify the appDelegate.m here but when I add that code it says I am missing an import, I know the import missing is FBSDKCoreKit or at least I think it is because the previous SDK used that one. To fix that you need to add the pod but when I add it the error above shows up.
I don't know if I need the other library because of that dependency. please help!

Body:
Was facing the same issue in my Mac M1 & solved this by running this command.

1- cd ios
2- arch -x86_64 pod install --repo-update


问:
Regex - Recursion - nested matches with multiple ending
this is my first question on stackoverflow so please bare with me here. Also I am not a native english speaker.

(16.02.2022)
ANSWER (https://regex101.com/r/4FRznK/1 from Comment on Answer). Special thanks to Casimir et Hippolyte for your help! I wish I could reach out to you.

```<code>\[if \s+ (?<cond> [^]]* ) ]

(?<content> [^[]*+
        (?: (?R) [^[]*
          | \[ (?! /if] | else (?:if)?  \b) [^[]*
        )*+
)
(?<rest>
    (?: \[elseif \s+ [^]]* ] \g<content> )*+
    (?: \[else] \g<content> )?+
    \[/if]
)
</code>```

(15.02.2022) UPDATE:
I fiddled around with the solutions presented below and have gotten farther with it. Seems like there is a limit on string length to comfortably match without any catastophic backtracking.

I have updated my Regex101 to show the recent progress. Maybe one of you has an idea on how to tackle this. https://regex101.com/r/wYzA3e/4

SIDE NOTE:
I do have a working function for this, but my goal is to find a faster solution in terms of optimization and reliability. My current functions takes (in my opinion) way to long to complete the task and relies havily on strpos to get me there. I do not actually want to use third-party functions if there is a cheaper (in terms of performance) solution with PHPs internal functions.
So even if you advice me to use alternative approaches, please be kind and provide hints on which explicitly you mean by these. Thank you!

(14.02.2022) Original:
I am presented with the following difficulties with my regular expression:
This is the string ("true" and/or "false" are not actually in the string but it helps with simplification):

```<code>**[if true]**
    [if true]
        [if false]
        [else]
        [/if]
    *[elseif false]*
        [if true]
        [/if]
    [else]
    [/if]
**[elseif false]**
[/if]
**[if false]**
    [if false]
    [else]
    *[/if]*
**[else]**
    [if true]
    [/if]
[/if]
</code>```

I marked the wanted matches (**) and the ones i got (*)

In this situation I do only want to match the most outer parent [if XXXX].([else]|[elseif XXX]|[/if]) statement with its according end which can be [else], [elseif XXX] or [/if]. For now i do not care about the inner [if XXX] since when the parent is false i dont need to check for them.

When running my regex:

```<code>/\[if (.*?)\](((?R)|.)*?)(\[\/if\]|\[else\]|\[elseif )/gs
</code>```

it matches the parents [if XXX] and an incoherent combination of any [elseif XX], [else], [/if] in it.

As groups I do need the match > every X [if XXX] > the content between [if XXX] and the matching [END] as well as the [END].

Since i do not fully understand Recursion I´d appreciate your help. Many thanks in advance!

You can try the regex here (updated):
https://regex101.com/r/wYzA3e/4

答:
When a pattern starts to be a little complicated, it's possible to use two features:

the verbose mode (x modifier)

references to subpatterns or better references to named subpatterns ( \g<name> )

Often with these two features things become more clear and the pattern is easier to build:

```<code>~
\[if \s+ [^]]* ]

(?<content> [^[]*+ (?: (?R) [^[]* )*+ )
(?: \[elseif \s+ [^]]* ] \g<content> )*+
(?: \[else] \g<content> )?+

\[/if]
~x
</code>```

demo

Note that (?R) is nothing more that a reference to a subpattern except that this time the subpattern is the whole pattern.

Body:
this is my first question on stackoverflow so please bare with me here. Also I am not a native english speaker.

(16.02.2022)
ANSWER (https://regex101.com/r/4FRznK/1 from Comment on Answer). Special thanks to Casimir et Hippolyte for your help! I wish I could reach out to you.

\[if \s+ (?<cond> [^]]* ) ]

(?<content> [^[]*+
        (?: (?R) [^[]*
          | \[ (?! /if] | else (?:if)?  \b) [^[]*
        )*+
)
(?<rest>
    (?: \[elseif \s+ [^]]* ] \g<content> )*+
    (?: \[else] \g<content> )?+
    \[/if]
)

(15.02.2022) UPDATE:
I fiddled around with the solutions presented below and have gotten farther with it. Seems like there is a limit on string length to comfortably match without any catastophic backtracking.

I have updated my Regex101 to show the recent progress. Maybe one of you has an idea on how to tackle this. https://regex101.com/r/wYzA3e/4

SIDE NOTE:
I do have a working function for this, but my goal is to find a faster solution in terms of optimization and reliability. My current functions takes (in my opinion) way to long to complete the task and relies havily on strpos to get me there. I do not actually want to use third-party functions if there is a cheaper (in terms of performance) solution with PHPs internal functions.
So even if you advice me to use alternative approaches, please be kind and provide hints on which explicitly you mean by these. Thank you!

(14.02.2022) Original:
I am presented with the following difficulties with my regular expression:
This is the string ("true" and/or "false" are not actually in the string but it helps with simplification):

**[if true]**
    [if true]
        [if false]
        [else]
        [/if]
    *[elseif false]*
        [if true]
        [/if]
    [else]
    [/if]
**[elseif false]**
[/if]
**[if false]**
    [if false]
    [else]
    *[/if]*
**[else]**
    [if true]
    [/if]
[/if]

I marked the wanted matches (**) and the ones i got (*)

In this situation I do only want to match the most outer parent [if XXXX].([else]|[elseif XXX]|[/if]) statement with its according end which can be [else], [elseif XXX] or [/if]. For now i do not care about the inner [if XXX] since when the parent is false i dont need to check for them.

When running my regex:

/\[if (.*?)\](((?R)|.)*?)(\[\/if\]|\[else\]|\[elseif )/gs

it matches the parents [if XXX] and an incoherent combination of any [elseif XX], [else], [/if] in it.

As groups I do need the match > every X [if XXX] > the content between [if XXX] and the matching [END] as well as the [END].

Since i do not fully understand Recursion I´d appreciate your help. Many thanks in advance!

You can try the regex here (updated):
https://regex101.com/r/wYzA3e/4

Body:
When a pattern starts to be a little complicated, it's possible to use two features:

the verbose mode (x modifier)

references to subpatterns or better references to named subpatterns ( \g<name> )

Often with these two features things become more clear and the pattern is easier to build:

~
\[if \s+ [^]]* ]

(?<content> [^[]*+ (?: (?R) [^[]* )*+ )
(?: \[elseif \s+ [^]]* ] \g<content> )*+
(?: \[else] \g<content> )?+

\[/if]
~x

demo

Note that (?R) is nothing more that a reference to a subpattern except that this time the subpattern is the whole pattern.