问:
how to return promise from an async code block
I want to send an http request and return the result using typescript, before send the http request, I want to get the token from google chrome local storage and put the token into http header. This is my typescript code looks like:

```<code>api_post:<T>(url: string, data: any): Promise<T> => {
    chrome.storage.local.get("token", function (result:any) {
        return fetch(url, {
            method: 'POST',
            headers: {
                'Content-type': 'application/json',
                'x-access-token': result,
            },
            body: JSON.stringify(data),
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(response.statusText);
                }
                return response.json() as Promise<T>;
            });
    });
},
</code>```

the problem is the promise return from the inner of an async code block, this function shows error:

```<code>interface Promise<T>
Represents the completion of an asynchronous operation

A function whose declared type is neither 'void' nor 'any' must return a value.ts(2355)
</code>```

what should I do to return the promise inside the chrome local storage get and make the code works?

答:
I would use the Promise constructor. Then, resolve the final desired value in the chain, and reject any errors.</p>
```<code>const api_post = <T>(url: string, data: any): Promise<T> => {
    return new Promise((resolve, reject) => {
        chrome.storage.local.get("token", function (result: any) {
            return fetch(url, {
                method: "POST",
                headers: {
                    "Content-type": "application/json",
                    "x-access-token": result,
                },
                body: JSON.stringify(data),
            }).then((response) => {
                if (!response.ok) {
                    reject(new Error(response.statusText));
                    return;
                }
                resolve(response.json() as Promise<T>);
            });
        });
    });
};
</code>```

Body:
I want to send an http request and return the result using typescript, before send the http request, I want to get the token from google chrome local storage and put the token into http header. This is my typescript code looks like:

api_post:<T>(url: string, data: any): Promise<T> => {
    chrome.storage.local.get("token", function (result:any) {
        return fetch(url, {
            method: 'POST',
            headers: {
                'Content-type': 'application/json',
                'x-access-token': result,
            },
            body: JSON.stringify(data),
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(response.statusText);
                }
                return response.json() as Promise<T>;
            });
    });
},

the problem is the promise return from the inner of an async code block, this function shows error:

interface Promise<T>
Represents the completion of an asynchronous operation

A function whose declared type is neither 'void' nor 'any' must return a value.ts(2355)

what should I do to return the promise inside the chrome local storage get and make the code works?

Body:
I would use the Promise constructor. Then, resolve the final desired value in the chain, and reject any errors.

const api_post = <T>(url: string, data: any): Promise<T> => {
    return new Promise((resolve, reject) => {
        chrome.storage.local.get("token", function (result: any) {
            return fetch(url, {
                method: "POST",
                headers: {
                    "Content-type": "application/json",
                    "x-access-token": result,
                },
                body: JSON.stringify(data),
            }).then((response) => {
                if (!response.ok) {
                    reject(new Error(response.statusText));
                    return;
                }
                resolve(response.json() as Promise<T>);
            });
        });
    });
};


来源: stackexchange

问:
Faster matrix power than numpy?
I needed to compute Q^N for quite a lot of various values of N (between 1 to 10000) and Numpy was a bit too slow.

I've asked on math.stackexchange.com if I could avoid to compute Q^N for my specific need and someone answered me that computing Q^N should be quite fast using the P D^N P^-1 method.

So basically, instead of doing:

```<code>import numpy as np
from numpy import linalg as LA
...
LA.matrix_power(m, N)
</code>```

I've tried :

```<code>diag, P = LA.eig(m)
DN = np.diag(diag**N)
P1 = LA.inv(P)

P*DN*P1
</code>```

And I obtain the same matrix as result (tried on a single example)

On a more complex matrix, Q:

```<code>% timeit.Timer('Q**10000', setup=setup).repeat(2, 100)
[5.87254786491394, 5.863131046295166]

% timeit.Timer('diag, P = linalg.eig(Q); DN=np.diag(diag**10000);P1=linalg.inv(P); P*DN*P1', setup=setup).repeat(2, 100)
[2.0032401084899902, 2.018735885620117]
</code>```

And regarding my initial problem, the second method allows me to compute P, diag and P1only once and use it thousands of times. It's 8 times faster using this method.

My questions are:

In which case it is not possible to use this last method to compute Q^N?

Is it fine to use it in my case (matrix Q as given here)?

Is there in numpy a function that already does it?

Edit:

It appears that for another matrix, P is not invertible. So I am adding a new question: how can I change the matrix P so it becomes invertible but the resulting matrix is not too altered? I mean, it's ok if the values are close to the real result, by close I mean ~0.0001.

答:
In question:

In which case it is not possible to use this last method to compute Q^N?

The key idea is to tell whether Q is diagonalizable. Equivalently, we should tell whether Q has n (number of its rows/columns) linearly independent eigenvectors. Note that distinct eigenvalues are just sufficient but not necessary condition of diagonalizability.

ContentLicense: CC BY-SA 3.0

Title: Faster matrix power than numpy?

Body:
I needed to compute Q^N for quite a lot of various values of N (between 1 to 10000) and Numpy was a bit too slow.

I've asked on math.stackexchange.com if I could avoid to compute Q^N for my specific need and someone answered me that computing Q^N should be quite fast using the P D^N P^-1 method.

So basically, instead of doing:

import numpy as np
from numpy import linalg as LA
...
LA.matrix_power(m, N)

I've tried :

diag, P = LA.eig(m)
DN = np.diag(diag**N)
P1 = LA.inv(P)

P*DN*P1

And I obtain the same matrix as result (tried on a single example)

On a more complex matrix, Q:

% timeit.Timer('Q**10000', setup=setup).repeat(2, 100)
[5.87254786491394, 5.863131046295166]

% timeit.Timer('diag, P = linalg.eig(Q); DN=np.diag(diag**10000);P1=linalg.inv(P); P*DN*P1', setup=setup).repeat(2, 100)
[2.0032401084899902, 2.018735885620117]

And regarding my initial problem, the second method allows me to compute P, diag and P1only once and use it thousands of times. It's 8 times faster using this method.

My questions are:

In which case it is not possible to use this last method to compute Q^N?

Is it fine to use it in my case (matrix Q as given here)?

Is there in numpy a function that already does it?

Edit:

It appears that for another matrix, P is not invertible. So I am adding a new question: how can I change the matrix P so it becomes invertible but the resulting matrix is not too altered? I mean, it's ok if the values are close to the real result, by close I mean ~0.0001.

ContentLicense: CC BY-SA 4.0


问:
Django - How to set ForeignKey to a model that itself has a one-to-one relationship to User?
Here's my class:

from django.db import models
from django.contrib.auth.models import User

class CredsKeychain(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    def __str__(self) -> str:
        return f"{self.user.username}'s credentials"

class CredKey(models.Model):
    keychain = models.ForeignKey(CredsKeychain, on_delete=models.CASCADE)
    tag = models.CharField(max_length=100)
    username = models.CharField(max_length=100)
    enc_password = models.CharField(max_length=100)
    last_used_successfully = models.DateTimeField(default=None)

    def __str__(self) -> str:
        return f"{self.keychain.user.username}'s credentials for {self.tag} [{self.username}]"
```
<p>I'm trying to have the relationship set up such that each user has a <code>CredsKeychain</code> that has multiple <code>CredKey</code> objects. I'm having a hard time trying to reference CredsKeychain from CredKey. I can directly link the user, via:</p>
```keychain = models.ForeignKey(User, on_delete=models.CASCADE)
```
<p>But that's not what I need. I actually need to have a ForeignKey relationship to the CredsKeychain that has a one-to-one relationship with the current user (who submits the page in Django admin).</p>
<p>When I try to migrate this model (in its current state), I get the error:</p>
<blockquote>
<p>It is impossible to add a non-nullable field 'keychain' to credkey without specifying a default. This is because the database needs something to populate existing rows.
Please select a fix:</p>
<ol>
<li>Provide a one-off default now (will be set on all existing rows with a null value for this column)</li>
<li>Quit and manually define a default value in models.py.</li>
</ol>
</blockquote>
<p>How can I reference the <code>user.credskeychain</code>?</p>
<hr />
<p>Update: I already have a signal setup so that everytime a user is created, it automatically creates a <code>CredsKeychain</code> for that user.</p>
```@receiver(post_save, sender=User)
def setup_keychain(sender, instance:User, created, **kwargs):
    if created:
        CredsKeychain.objects.create(user = instance)
```
<p>Update 2: Model works just fine as-is once I dropped the DB and deleted the old migrations (nuked the DB). Now that I start again, it migrates just fine. So what was the problem earlier?!</p>
```(env) PS C:\Users\somsinha\scripts\djpu-keystore> python manage.py makemigrations
Migrations for 'keystore':
  keystore\migrations\0001_initial.py
    - Create model CredsKeychain
    - Create model CredKey
(env) PS C:\Users\somsinha\scripts\djpu-keystore> python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, keystore, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying auth.0012_alter_user_first_name_max_length... OK
  Applying keystore.0001_initial... OK
  Applying sessions.0001_initial... OK
```

答:
if you want to add any new fields to your models make sure that you don't have any previously added records in the DB. if you have any records you should out some default values in the model field. because when you try to migrate new fields without any default value what should DB do ? how should it fill for the previous records? so there is 2 way to fix it as it says:

Provide a one-off default now (will be set on all existing rows with a null value for this column)

Quit and manually define a default value in models.py.

so you can select option 1 and write a python command to fill the previous records or select option 2 and define the default value in the model field manually

Body:
Here's my class:

from django.db import models
from django.contrib.auth.models import User

class CredsKeychain(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    def __str__(self) -> str:
        return f"{self.user.username}'s credentials"

class CredKey(models.Model):
    keychain = models.ForeignKey(CredsKeychain, on_delete=models.CASCADE)
    tag = models.CharField(max_length=100)
    username = models.CharField(max_length=100)
    enc_password = models.CharField(max_length=100)
    last_used_successfully = models.DateTimeField(default=None)

    def __str__(self) -> str:
        return f"{self.keychain.user.username}'s credentials for {self.tag} [{self.username}]"

I'm trying to have the relationship set up such that each user has a CredsKeychain that has multiple CredKey objects. I'm having a hard time trying to reference CredsKeychain from CredKey. I can directly link the user, via:

keychain = models.ForeignKey(User, on_delete=models.CASCADE)

But that's not what I need. I actually need to have a ForeignKey relationship to the CredsKeychain that has a one-to-one relationship with the current user (who submits the page in Django admin).

When I try to migrate this model (in its current state), I get the error:

It is impossible to add a non-nullable field 'keychain' to credkey without specifying a default. This is because the database needs something to populate existing rows.
Please select a fix:

Provide a one-off default now (will be set on all existing rows with a null value for this column)

Quit and manually define a default value in models.py.

How can I reference the user.credskeychain?

Update: I already have a signal setup so that everytime a user is created, it automatically creates a CredsKeychain for that user.

@receiver(post_save, sender=User)
def setup_keychain(sender, instance:User, created, **kwargs):
    if created:
        CredsKeychain.objects.create(user = instance)

Update 2: Model works just fine as-is once I dropped the DB and deleted the old migrations (nuked the DB). Now that I start again, it migrates just fine. So what was the problem earlier?!

(env) PS C:\Users\somsinha\scripts\djpu-keystore> python manage.py makemigrations
Migrations for 'keystore':
  keystore\migrations\0001_initial.py
    - Create model CredsKeychain
    - Create model CredKey
(env) PS C:\Users\somsinha\scripts\djpu-keystore> python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, keystore, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying auth.0012_alter_user_first_name_max_length... OK
  Applying keystore.0001_initial... OK
  Applying sessions.0001_initial... OK


问:
Is there any scope to increment digit in excel?
I have created a UDF in excel. Here is the function with cell reference as arguments:

```<code>=getInfo($A$3,B2,3)
</code>```

In the above arguments, "3" is actually the row number which will be used for a calculation. Now if I drag this UDF over rows, the B2 is incremented as it is a cell reference (Range) but 3 is not incremented as it is a digit only. I need to use this third argument sometimes fixed (which is actually works in current condition), but sometimes I need to increment this argument while dragging.

My query is, is there any scope/option to increment the only digit in UDF without passing an additional optional argument for increment (eg: 3+1 or let's say I put 3 in any cell and use that cell to increment it by 1 for every row dragging)?

答:
You can use Row() function. Try-

```<code>=getInfo($A$3,B2,Row(A3))
</code>```

When you drag it to 1 cell down then formula will =getInfo($A$3,B3,Row(A4)) means row argument 4.

Body:
I have created a UDF in excel. Here is the function with cell reference as arguments:

=getInfo($A$3,B2,3)

In the above arguments, "3" is actually the row number which will be used for a calculation. Now if I drag this UDF over rows, the B2 is incremented as it is a cell reference (Range) but 3 is not incremented as it is a digit only. I need to use this third argument sometimes fixed (which is actually works in current condition), but sometimes I need to increment this argument while dragging.

My query is, is there any scope/option to increment the only digit in UDF without passing an additional optional argument for increment (eg: 3+1 or let's say I put 3 in any cell and use that cell to increment it by 1 for every row dragging)?

Body:
You can use Row() function. Try-

=getInfo($A$3,B2,Row(A3))

When you drag it to 1 cell down then formula will =getInfo($A$3,B3,Row(A4)) means row argument 4.


问:
Registry permissions problem
I need to install an application (SQL Server Denali, but this is irrelevant) and during the installation, I have a lot of problems with registry... a lot of pop-ups appear telling that i dont have permissions to modify that key of the registry.

I'm administration but seems that with some keys i dont have permission and i have to modify permissions manually. The problem is that there is a lot of registers giving problems.

What can I do? How can i add full control to all the keys of the registry?

I have Windows 7 64bits

Thanks

答:
What's your OS on which you are trying to install?

I have seen security features on Windows 2008 and Windows 7 (which is good but can be annoying as seen by you on popups for permissions). Even though the local user is as administrator with which you are trying to install, on these systems its best to right click and choose "Run as Administrator"

Also you can choose to lower the security level on "user account control settings" (click on start menu button in Windows 7 / 2008) and in the search bar type uac, and lower the security to never notify and bring it back up after the installation.

Hope this helps...

Title: Registry permissions problem


问:
Excel formula, calculate product of values in each column of dynamic array
I'm working on a formula for a "result" column in a table that looks up data in another table based on some criteria in the main one, then displays it.  Of the point where I'm getting stumped at, it is returning a dynamic 2D array (row returns are variable dependent on an FILTER/MATCH lookup).  Example (4 columns x 3 rows) return value: {1,2,3,4;1,2,3,4;1,2,3,4}

I want to get the product of the values in each column such that the output from the formula using the example return value above would be this: {1,8,27,64}

(Which is the equivalent of doing this: {1,2,3,4} * {1,2,3,4} * {1,2,3,4})

How do I accomplish this using only formula functions?

All of my google searches have been coming back with methods that assume static table size, multiply the columns against each other, and/or the table "existing" within a sheet somewhere (and still don't give the result I'm looking for).

I've already figured this out via VBA, but due to the nature of how I'm using the sheet, waiting for the updates to run via VBA are too slow.  It's not that it takes forever - it's only about 3-4 seconds for ~60 rows - but rather that I make a change to my lookup table, wait for the update to the result column in the main table, check the results, make another change, rinse & repeat 50 some odd times while I fine tune things to look the way I want them to, and the delays are wearing on me.

I'm also unsure that I can use helper rows/columns as the results would need to be packed too close together and would just display #SPILL, which results in the formulas referencing it just showing the same thing.  So it looks like this needs to be self contained.

Plugins are an absolute no.

(Other little edit: Whoops, I put INDEX/MATCH above when I meant FILTER/MATCH.)

EDIT: Hopefully this will help clarify?

Here's the structure of my main table where this formula resides:

My Formula takes the words from ColA and ColB and uses FILTER/MATCH to do a lookup that 1) returns multiple results, 2) the return results are entire rows, and 3) is an exact match (it returns nothing for words in ColA and ColB that don't exist in the lookup table).

This means that, as of the current state of the formula, I'm getting 2D arrays back for most of the rows in the main table.  AFAICT, I'm not going to be able to stick these into a helper column somewhere as they'll overlap and just cause #SPILL which then won't evaluate in whatever formulas then reference them.

I need to turn these into 1D arrays that are 1 row x same-#-as-source columns where the result in each column is the product of only that column's contents.  I'm then going to continue building off from this formula with more formula to achieve my final result that will fit nicely in the single cell.  (I already have that piece solved.  It's just going from the 2D -> 1D product array I need help with.)

答:
So:

EDIT based on comment:
If the sumproduct is in the wrong order, then the alternative is simple:

```<code>=SUMPRODUCT(D10:F10,D11:F11,D12:F12,D13:F13)

=sumproduct(A1:A4,B1:B4,C1:C4)
</code>```

Then A1:A4 (and the other arrays) could be the index with match retrieving the data.

Or have the index and match in other cells and use those result in the sumproduct.

Had a play, making up some data as so:

In Cell D88:

```<code>=INDEX($B$2:$H$5,MATCH($C10,$A$2:$A$5,0),MATCH(D$9,$B$1:$H$1,0))
</code>```

In cell D15:

```<code>=SUMPRODUCT(D10:D13,E10:E13,F10:F13)
</code>```

In cells D9:F9 is data validation to choose the column heading A:G.

Body:
So:

EDIT based on comment:
If the sumproduct is in the wrong order, then the alternative is simple:

=SUMPRODUCT(D10:F10,D11:F11,D12:F12,D13:F13)

=sumproduct(A1:A4,B1:B4,C1:C4)

Then A1:A4 (and the other arrays) could be the index with match retrieving the data.

Or have the index and match in other cells and use those result in the sumproduct.

Had a play, making up some data as so:

In Cell D88:

=INDEX($B$2:$H$5,MATCH($C10,$A$2:$A$5,0),MATCH(D$9,$B$1:$H$1,0))

In cell D15:

=SUMPRODUCT(D10:D13,E10:E13,F10:F13)

In cells D9:F9 is data validation to choose the column heading A:G.


问:
Golang: Can channels be closed in a deferred function?
I was working on some Go code and wanted to close a channel at the end of it. However, I wanted to test if it'd actually close the channel if I use an anonymous function, passing the channel as an argument and use the function with the defer keyword.

```<code>channel := make(chan string, 2)

defer func (channel chan string) {
        close(channel)
        value, ok := <-channel
        fmt.Println("Value:", value, "Open channel?", ok)
    }(channel)
</code>```

To my understanding everything in Go is passed by value and not by reference, and make's documentation says that it returns a channel when used to spawn a channel, not a pointer to a channel. Does this imply that if I pass the channel as argument to a function and close the channel within that function, the channel outside the function would remain open? If so, I'm guessing I'd need to pass the channel as a pointer to the function to achieve that behavior?

I'm new to Go, so I'd appreciate if you can explain me the "why" rather than "Oh, just swap this chunk for this other chunk of code" just so I can better understand how it's actually working:)

Thanks!

答:
Does this imply that if I pass the channel as argument to a function and close the channel within that function, the channel outside the function would remain open?

No. Copying a chan variable doesn't produce a copy of the channel itself. Variables of type chan are handles to the underlying channel created by make. Closing any copy of the chan variable closes the channel.

Body:
I was working on some Go code and wanted to close a channel at the end of it. However, I wanted to test if it'd actually close the channel if I use an anonymous function, passing the channel as an argument and use the function with the defer keyword.

channel := make(chan string, 2)

defer func (channel chan string) {
        close(channel)
        value, ok := <-channel
        fmt.Println("Value:", value, "Open channel?", ok)
    }(channel)

To my understanding everything in Go is passed by value and not by reference, and make's documentation says that it returns a channel when used to spawn a channel, not a pointer to a channel. Does this imply that if I pass the channel as argument to a function and close the channel within that function, the channel outside the function would remain open? If so, I'm guessing I'd need to pass the channel as a pointer to the function to achieve that behavior?

I'm new to Go, so I'd appreciate if you can explain me the "why" rather than "Oh, just swap this chunk for this other chunk of code" just so I can better understand how it's actually working:)

Thanks!


问:
Entry and exit 1 day before condition is met
I am new to pine and am trying to test a simple MACD strategy. Thing is I want to enter and exit 1 day earlier in the backtesting.

```<code>//Strategy: Long when MACD line above Signal line and above SMA20
if crossover(macdline, signalline)
    // Buy when MACD crosses Signal from beneath
    strategy.entry("macd", long =true)
if crossunder(macdline, signalline) or crossunder(close, sma20)
    // Sell when MACD crosses Signal from above or of closing price below MA20
    strategy.close("macd")
</code>```

When you take a look at the enter and exit, they are actually one day later than the condition is met.

Any knows how to do this?

答:
That is because the execution model of the pinescript.

You can add process_orders_on_close=true to your strategy() call to execute orders after a bar closes and strategy calculations are completed.

```<code>strategy("My strategy", overlay=true, margin_long=100, margin_short=100, process_orders_on_close=true)
</code>```

Body:
I am new to pine and am trying to test a simple MACD strategy. Thing is I want to enter and exit 1 day earlier in the backtesting.

//Strategy: Long when MACD line above Signal line and above SMA20
if crossover(macdline, signalline)
    // Buy when MACD crosses Signal from beneath
    strategy.entry("macd", long =true)
if crossunder(macdline, signalline) or crossunder(close, sma20)
    // Sell when MACD crosses Signal from above or of closing price below MA20
    strategy.close("macd")

When you take a look at the enter and exit, they are actually one day later than the condition is met.

Any knows how to do this?

Body:
That is because the execution model of the pinescript.

You can add process_orders_on_close=true to your strategy() call to execute orders after a bar closes and strategy calculations are completed.

strategy("My strategy", overlay=true, margin_long=100, margin_short=100, process_orders_on_close=true)


问:
Model Manager; TypeError: isinstance() arg 2 must be a type or tuple of types
I'm trying to test a method within a custom model manager by_week(). Upon debugging it, I've come across an issue of trying to query all objects within the method with profile.questions.all() and self.model.objects.all() where self.model is the Question model. Yet both raise the following error: *** TypeError: isinstance() arg 2 must be a type or tuple of types. Why is this error being raised?

As background info: I created test data by creating instances through the admin interface and dumped everything in the database into a JSON file.

models.py

```<code>class QuestionSearchManager(Manager):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def by_week(self, profile):
        # today = datetime.date.today()
        # weekago = today - datetime.timedelta(days=7)
        questions = self.model.objects.all()
        user_tags = profile.questions.all()
        x = self.model.objects.filter(
            tags__name__in=user_tags
        )
        return x

class Post(Model):

    body = TextField()
    date = DateField(default=datetime.date.today)
    comment = ForeignKey('Comment', on_delete=CASCADE, null=True)
    profile = ForeignKey(
        'authors.Profile', on_delete=SET_NULL, null=True,
        related_name='%(class)ss',
        related_query_name="%(class)s"
    )
    score = GenericRelation(
        'Vote', related_query_name="%(class)s"
    )

    class Meta:
        abstract = True

class Question(Post):

    title = CharField(max_length=75)
    tags = ManyToManyField(
        'Tag', related_name="questions", related_query_name="question"
    )
    objects = Manager()
    postings = QuestionSearchManager()
</code>```

python manage.py shell

```<code>>>> from authors.models import Profile
>>> p = Profile.objects.get(id=2)
>>> p.questions.all()
<QuerySet [<Question: Question object (13)>]>
>>> from posts.models import Question
>>> Question.objects.all()
<QuerySet [<Question: Question object (9)>, <Question: Question object (10)>, <Question: Question object (11)>, <Question: Question object (12)>, <Question: Question object (13)>, <Question: Question object (14)>]>
</code>```

答:
In your above example, the questions object is never used. But as a side note, instead of self.model.objects.all() you probably want to use self.get_queryset() to query the model which is being managed by the manager, then use that to filter the questions.

Something like

    questions = self.get_queryset()
    user_tags = profile.questions.all()
    x = questions.filter(
        tags__name__in=user_tags
    )

```

The error you're seeing is confusing because what is happening is that you're invoking the custom __getattr__, which in turn is using isinstance with bad arguments. The type of the items given to tags__name__in= must match that of the tags__name field. Presumably, strings, not Question instances.

So, the fix would be to fix the value of user_tags to match the type expected for tags__name.

Body:
I'm trying to test a method within a custom model manager by_week(). Upon debugging it, I've come across an issue of trying to query all objects within the method with profile.questions.all() and self.model.objects.all() where self.model is the Question model. Yet both raise the following error: *** TypeError: isinstance() arg 2 must be a type or tuple of types. Why is this error being raised?

As background info: I created test data by creating instances through the admin interface and dumped everything in the database into a JSON file.

models.py

class QuestionSearchManager(Manager):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def by_week(self, profile):
        # today = datetime.date.today()
        # weekago = today - datetime.timedelta(days=7)
        questions = self.model.objects.all()
        user_tags = profile.questions.all()
        x = self.model.objects.filter(
            tags__name__in=user_tags
        )
        return x

class Post(Model):

    body = TextField()
    date = DateField(default=datetime.date.today)
    comment = ForeignKey('Comment', on_delete=CASCADE, null=True)
    profile = ForeignKey(
        'authors.Profile', on_delete=SET_NULL, null=True,
        related_name='%(class)ss',
        related_query_name="%(class)s"
    )
    score = GenericRelation(
        'Vote', related_query_name="%(class)s"
    )

    class Meta:
        abstract = True

class Question(Post):

    title = CharField(max_length=75)
    tags = ManyToManyField(
        'Tag', related_name="questions", related_query_name="question"
    )
    objects = Manager()
    postings = QuestionSearchManager()

python manage.py shell

>>> from authors.models import Profile
>>> p = Profile.objects.get(id=2)
>>> p.questions.all()
<QuerySet [<Question: Question object (13)>]>
>>> from posts.models import Question
>>> Question.objects.all()
<QuerySet [<Question: Question object (9)>, <Question: Question object (10)>, <Question: Question object (11)>, <Question: Question object (12)>, <Question: Question object (13)>, <Question: Question object (14)>]>

Body:
In your above example, the questions object is never used. But as a side note, instead of self.model.objects.all() you probably want to use self.get_queryset() to query the model which is being managed by the manager, then use that to filter the questions.

Something like

    questions = self.get_queryset()
    user_tags = profile.questions.all()
    x = questions.filter(
        tags__name__in=user_tags
    )

The error you're seeing is confusing because what is happening is that you're invoking the custom __getattr__, which in turn is using isinstance with bad arguments. The type of the items given to tags__name__in= must match that of the tags__name field. Presumably, strings, not Question instances.

So, the fix would be to fix the value of user_tags to match the type expected for tags__name.


问:
Input field that only allows numbers but doesn't allow a single 0 in ReactJS
I need an input form that works with money. You can't type text, symbols, or anything besides numbers but you also shouldn't be able to put $0. It should be $1 and up. When I put /^[0-9\b]+$/ it only allows numbers but you can put $0. When I use /^[1-9\b]+$/ it doesn't let you put in a zero but if you type 1 and try to put a zero it won't let you. When I try /^[1-9\b]+/, it doesn't allow zero but now you can type text and characters. Is there a better way to do this?

const re = /^[0-9\b]+$/ is the current regex I'm using.

This is in ReactJS

答:
Try this</p>
```<code><input type="number" min="1" step="any" />
</code>```

Body:
Try this

<input type="number" min="1" step="any" />


问:
snowflake help to create 3rd variable while grouping
I have a dataset as below, for which i need to group by it by 3 variables also shown as below:

result needed as below:

答:
I'm sure you I know how to group by month and channel and do a count so the only tricky thing here is to work out the "both"

If you group by token and take a look at the min vs max channel you'll either see the minmax be the same or different. If they're different it's "both"

```<code>SELECT
  MONTH(date) as mnth,
  CASE WHEN min(channel) = max(channel) THEN min(channel) ELSE 'both' END as channel
FROM t
  GROUP BY MONTH(date), token
</code>```

When the token is 1, the min is "email" and the max is "text" -  because they differ it will become "both". For token 3 the min and max are the same "email", so we just use the min value to deliver "email". The end result is a unique set of token values and either email/text/both. Even if there are repeated values so long as there are no typos then it works out (but if you have a token=3,channel=emial then the method cannot work; clean your data)

You can feed the results of this query into another grouping that does your month/channel/count (put all this query as a sub query or CTE of a query that does another group by)

Body:
I'm sure you I know how to group by month and channel and do a count so the only tricky thing here is to work out the "both"

If you group by token and take a look at the min vs max channel you'll either see the minmax be the same or different. If they're different it's "both"

SELECT
  MONTH(date) as mnth,
  CASE WHEN min(channel) = max(channel) THEN min(channel) ELSE 'both' END as channel
FROM t
  GROUP BY MONTH(date), token

When the token is 1, the min is "email" and the max is "text" -  because they differ it will become "both". For token 3 the min and max are the same "email", so we just use the min value to deliver "email". The end result is a unique set of token values and either email/text/both. Even if there are repeated values so long as there are no typos then it works out (but if you have a token=3,channel=emial then the method cannot work; clean your data)

You can feed the results of this query into another grouping that does your month/channel/count (put all this query as a sub query or CTE of a query that does another group by)


问:
Read static files with express got "Cannot Get /"
I tried to learn how to read static files with express from a reliable website. And then I found that not know why, my terminal tell me I'm success but website show me "Cannot Get /"(as following image show). I had found a lot of solution (e.g. in my html file, I add script src to socket.io) but still fail. Where can I start to deal with it? Please help me...

terminal show success

website show error

And the following is my code:

C:\...\1-on-1-webrtc\server.js

```<code>const express = require('express')
const app = express()
const http = require('http').createServer(app)

// static data
app.use('/', express.static(__dirname + '/public/'))

// TODO: Signaling

//start server listen 8080 port
http.listen(8080, () => {
    console.log(`Server running in 8080`)
})
</code>```

C:\...\1-on-1-webrtc\pubilc\index.html

(origin)

```<code>"hello"
</code>```

(after)

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>111</title>
    <script src="https://cdn.socket.io/socket.io-3.0.5.js"></script>
</head>
<body>
<h1>"hello"</h1>
<script>
    var socket = io();
</script>
</body>
</html>
</code>```

答:
I change Your code a little and here is my solution:

Firstly change your name of public folder to correct. Not "pubilc" only "public".

Folder & File Structure:

server.js :

```<code>const express = require("express");
const app = express();
const port = 8080;
// const http = require("http").createServer(app);

// static data
app.use("/", express.static(__dirname + "/public"));

//start server listen 8080 port
app.listen(port, () => {
  console.log(`Server is  listening at http://localhost:${port}`);
});
</code>```

index.html (without any changes) :

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>111</title>
    <script src="https://cdn.socket.io/socket.io-3.0.5.js"></script>
  </head>
  <body>
    <h1>"hello"</h1>
    <script>
      var socket = io();
    </script>
  </body>
</html>
</code>```

Output :

Tested with: express 4.17.2 node 16.13.0 Linux Ubuntu 20.04 and Win10

Body:
I tried to learn how to read static files with express from a reliable website. And then I found that not know why, my terminal tell me I'm success but website show me "Cannot Get /"(as following image show). I had found a lot of solution (e.g. in my html file, I add script src to socket.io) but still fail. Where can I start to deal with it? Please help me...

terminal show success

website show error

And the following is my code:

C:\...\1-on-1-webrtc\server.js

const express = require('express')
const app = express()
const http = require('http').createServer(app)

// static data
app.use('/', express.static(__dirname + '/public/'))

// TODO: Signaling

//start server listen 8080 port
http.listen(8080, () => {
    console.log(`Server running in 8080`)
})

C:\...\1-on-1-webrtc\pubilc\index.html

(origin)

"hello"

(after)

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>111</title>

"hello"

Body:
I change Your code a little and here is my solution:

Firstly change your name of public folder to correct. Not "pubilc" only "public".

Folder & File Structure:

server.js :

const express = require("express");
const app = express();
const port = 8080;
// const http = require("http").createServer(app);

// static data
app.use("/", express.static(__dirname + "/public"));

//start server listen 8080 port
app.listen(port, () => {
  console.log(`Server is  listening at http://localhost:${port}`);
});

index.html (without any changes) :

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>111</title>
    <script src="https://cdn.socket.io/socket.io-3.0.5.js"></script>
  </head>
  <body>
    <h1>"hello"</h1>
    <script>
      var socket = io();
    </script>
  </body>
</html>

Output :

Tested with: express 4.17.2 node 16.13.0 Linux Ubuntu 20.04 and Win10


问:
Visualizing 3d models with textures
I have a textured 3d model which has an obj file , mtl file and a png image for textures .
I can visualize them without textures using trimesh and vtkplotter as :

```<code>//trimesh//
m = trimesh.load("3dmodel.obj")

//vtkplotter//
m = load("3dmodel.obj")

</code>```

But  they display the 3d models as plain meshes .
I want to see them along with textures .

Can anyone please help me View the 3d models along with textures .
Any small help would  be greatly helpful .

答:
you can act like this:

```<code>import numpy as np
import trimesh
from PIL import Image

im = Image.open("Lmobl/texture.png")
mesh = trimesh.load('Lmobl/raw_model.obj',process=False)
tex = trimesh.visual.TextureVisuals(image=im)
mesh.visual.texture = tex
mesh.show()
</code>```

and here the result:

and for without texture, you'll find answer here

Title: Visualizing 3d models with textures

Body:
I have a textured 3d model which has an obj file , mtl file and a png image for textures .
I can visualize them without textures using trimesh and vtkplotter as :

//trimesh//
m = trimesh.load("3dmodel.obj")

//vtkplotter//
m = load("3dmodel.obj")

But  they display the 3d models as plain meshes .
I want to see them along with textures .

Can anyone please help me View the 3d models along with textures .
Any small help would  be greatly helpful .

Body:
you can act like this:

import numpy as np
import trimesh
from PIL import Image

im = Image.open("Lmobl/texture.png")
mesh = trimesh.load('Lmobl/raw_model.obj',process=False)
tex = trimesh.visual.TextureVisuals(image=im)
mesh.visual.texture = tex
mesh.show()

and here the result:

and for without texture, you'll find answer here


问:
P4 protect rights for subfolders
I want to make certain folders read-only for the developers while some subfolders in that folder as write also.

For example, consider the folder structure:

```<code>Meeting/Jan/DevInfo/
Meeting/Feb/DevInfo/
Meeting/March/DevInfo/
Meeting/April/DevInfo/
Meeting/May/DevInfo/
</code>```

I want the developers to have read permission to //Meeting/ but write permission to //Meeting/.../DevInfo/...

Can I use the following code?

```<code>read group developers * //Meeting/...
write group developers * //Meeting/.../DevInfo/...
</code>```

I think it should be correct, but visual in P4 shows that the whole structure of //Meeting/ is write-allowed for developers.

答:
Change the write access line to:

```<code>write group developers * //Meeting/*/DevInfo/...
</code>```

The * character means "all files within the Meeting directory, excluding subdirectories".

The ... entry that you had before means "all files and subdirectories under //Meeting", so it overrode the following DevInfo/... section.

Try running the following to check what the protection levels are:

```<code>p4 protects //Meeting/...
</code>```

Title: P4 protect rights for subfolders

Body:
I want to make certain folders read-only for the developers while some subfolders in that folder as write also.

For example, consider the folder structure:

Meeting/Jan/DevInfo/
Meeting/Feb/DevInfo/
Meeting/March/DevInfo/
Meeting/April/DevInfo/
Meeting/May/DevInfo/

I want the developers to have read permission to //Meeting/ but write permission to //Meeting/.../DevInfo/...

Can I use the following code?

read group developers * //Meeting/...
write group developers * //Meeting/.../DevInfo/...

I think it should be correct, but visual in P4 shows that the whole structure of //Meeting/ is write-allowed for developers.

Body:
Change the write access line to:

write group developers * //Meeting/*/DevInfo/...

The * character means "all files within the Meeting directory, excluding subdirectories".

The ... entry that you had before means "all files and subdirectories under //Meeting", so it overrode the following DevInfo/... section.

Try running the following to check what the protection levels are:

p4 protects //Meeting/...


问:
After the page is reloaded, the url created with useHistory push is deleted
I have such a code, but the url is reset after the page is refreshed. Is there any solution to this? I want the page to reload after the url changes to " localhost:3000/?chain=ETH ", but after the reload the url is reset. so only "localhost:3000" remains. How can I prevent this?

```<code>  const handleClickEthereum = async () => {
    try {
      await handleNetworkSwitch("ethereum");
      navigate({
        pathname: "/",
        search: "?chain=ETH",
      });
      window.location.reload(false);
      setVisible(false);
    } catch (error) {
      console.log(error);
    }
  };
</code>```

Maybe the whole code on the relevant page can help. I wanted to share the other codes on the page.
All codes page

```<code>import React, { useState, useContext, useEffect } from "react";
import { Modal, Button } from "antd";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import BinanceCSS from "./modals.module.css";
import { useNavigate } from "react-router-dom";
import { useLocation } from "react-router-dom";
import { ReactSVG } from "react-svg";
import BinanceLogo from "../../assets/svg/binance.svg";
import PolygonLogo from "../../assets/svg/polygon.svg";
import EthereumLogo from "../../assets/svg/ethereum.svg";
//CONTEXT API
import BinanceContext from "../../context/BinanceContext";

const BinanceModal = () => {
  const { t } = useTranslation();

  const navigate = useNavigate();
  const location = useLocation();

  const [error, setError] = useState("hata var");

  const { visible, setVisible, handleNetworkSwitch, switchUrlState } =
    useContext(BinanceContext);

  const handleClickPolygon = async () => {
    try {
      await handleNetworkSwitch("polygon");
      navigate({
        pathname: "/",
        search: "?chain=Matic",
      });
      window.location.replace("/?chain=Matic");
      setVisible(false);
      console.log("sonuç", switchUrlState[0]);
    } catch (error) {
      console.log(error);
    }
  };

  const handleClickBinance = async () => {
    try {
      await handleNetworkSwitch("bsc");
      navigate({
        pathname: "/",
        search: "?chain=BSC",
      });
      window.location.replace("/?chain=BSC");
      setVisible(false);
    } catch (error) {
      console.log(error);
    }
  };

  const handleClickEthereum = async () => {
    try {
      await handleNetworkSwitch("ethereum");
      navigate({
        pathname: "/",
        search: "?chain=ETH",
      });

      setVisible(false);
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <>
      <Modal
        title={t("binance_modal_title")}
        centered
        visible={visible}
        onOk={() => setVisible(false)}
        onCancel={() => setVisible(false)}
        width={800}
        footer={null}
      >
        <div className={BinanceCSS.modalContainer}>
          {/* -----BSC----- */}
          <Wrapper onClick={() => handleClickBinance()}>
            <ReactSVG className={BinanceCSS.binanceIcon} src={BinanceLogo} />
            <h2>{t("binance")}</h2>
          </Wrapper>
          {/* -----POLYGON----- */}
          <Wrapper onClick={() => handleClickPolygon()}>
            <ReactSVG className={BinanceCSS.polygonIcon} src={PolygonLogo} />
            <h2>{t("polygon")}</h2>
          </Wrapper>
          {/* -----ETHEREUM----- */}
          <Wrapper onClick={() => handleClickEthereum()}>
            <ReactSVG className={BinanceCSS.ethereumIcon} src={EthereumLogo} />
            <h2>{t("ethereum")}</h2>
          </Wrapper>
        </div>
      </Modal>
    </>
  );
};

const Wrapper = styled.div`
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 12rem;
  height: 10rem;
  border-radius: 1.5rem;
  border: 1px solid #e2e2e2;
  cursor: pointer;
  padding-top: 1rem;
  transition: all 0.3s ease-in-out;
  margin-bottom: 2.5rem;
  &:hover {
    background: #ebeaea;
  }
`;

export default BinanceModal;
</code>```

答:
Hmm, can you share a little more code?
How did you use the router etc?
Which version of the package did you use?
I put the same code in the random react app from my local machine and works perfectly, so looks that something else is wrong.</p>

Body:
I have such a code, but the url is reset after the page is refreshed. Is there any solution to this? I want the page to reload after the url changes to " localhost:3000/?chain=ETH ", but after the reload the url is reset. so only "localhost:3000" remains. How can I prevent this?

  const handleClickEthereum = async () => {
    try {
      await handleNetworkSwitch("ethereum");
      navigate({
        pathname: "/",
        search: "?chain=ETH",
      });
      window.location.reload(false);
      setVisible(false);
    } catch (error) {
      console.log(error);
    }
  };

Maybe the whole code on the relevant page can help. I wanted to share the other codes on the page.
All codes page

import React, { useState, useContext, useEffect } from "react";
import { Modal, Button } from "antd";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import BinanceCSS from "./modals.module.css";
import { useNavigate } from "react-router-dom";
import { useLocation } from "react-router-dom";
import { ReactSVG } from "react-svg";
import BinanceLogo from "../../assets/svg/binance.svg";
import PolygonLogo from "../../assets/svg/polygon.svg";
import EthereumLogo from "../../assets/svg/ethereum.svg";
//CONTEXT API
import BinanceContext from "../../context/BinanceContext";

const BinanceModal = () => {
  const { t } = useTranslation();

  const navigate = useNavigate();
  const location = useLocation();

  const [error, setError] = useState("hata var");

  const { visible, setVisible, handleNetworkSwitch, switchUrlState } =
    useContext(BinanceContext);

  const handleClickPolygon = async () => {
    try {
      await handleNetworkSwitch("polygon");
      navigate({
        pathname: "/",
        search: "?chain=Matic",
      });
      window.location.replace("/?chain=Matic");
      setVisible(false);
      console.log("sonuç", switchUrlState[0]);
    } catch (error) {
      console.log(error);
    }
  };

  const handleClickBinance = async () => {
    try {
      await handleNetworkSwitch("bsc");
      navigate({
        pathname: "/",
        search: "?chain=BSC",
      });
      window.location.replace("/?chain=BSC");
      setVisible(false);
    } catch (error) {
      console.log(error);
    }
  };

  const handleClickEthereum = async () => {
    try {
      await handleNetworkSwitch("ethereum");
      navigate({
        pathname: "/",
        search: "?chain=ETH",
      });

      setVisible(false);
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <>
      <Modal
        title={t("binance_modal_title")}
        centered
        visible={visible}
        onOk={() => setVisible(false)}
        onCancel={() => setVisible(false)}
        width={800}
        footer={null}
      >

          {/* -----BSC----- */}
          <Wrapper onClick={() => handleClickBinance()}>
            <ReactSVG className={BinanceCSS.binanceIcon} src={BinanceLogo} />

{t("binance")}

          </Wrapper>
          {/* -----POLYGON----- */}
          <Wrapper onClick={() => handleClickPolygon()}>
            <ReactSVG className={BinanceCSS.polygonIcon} src={PolygonLogo} />

{t("polygon")}

          </Wrapper>
          {/* -----ETHEREUM----- */}
          <Wrapper onClick={() => handleClickEthereum()}>
            <ReactSVG className={BinanceCSS.ethereumIcon} src={EthereumLogo} />

{t("ethereum")}

          </Wrapper>

      </Modal>
    </>
  );
};

const Wrapper = styled.div`
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 12rem;
  height: 10rem;
  border-radius: 1.5rem;
  border: 1px solid #e2e2e2;
  cursor: pointer;
  padding-top: 1rem;
  transition: all 0.3s ease-in-out;
  margin-bottom: 2.5rem;
  &:hover {
    background: #ebeaea;
  }
`;

export default BinanceModal;


问:
How to enable both wipe able tabview and bottom navigator in swiftUi
I am new with iOS and swiftUi. I got stuck when try to make tabview display as default but also want my tabview is wipeable.
I already know that we can make tabview swipe able by adding tabViewStyle but the navigator in the bottom will be disappeared.

```<code>        .tabViewStyle(.page(indexDisplayMode: .never))
</code>```

The solution that I can think of is add a new View in the bottom and custom like a navigator, hope that someone know other better solution than that.
Thank you !

答:
A possible approach is to use two synchronised TabView for this purpose by matching selections and aligned content height. See also comments inline.

Tested with Xcode 13.2 / iOS 15.2

```<code>struct TestTwoTabViews: View {
    @State private var selection1: Int = 1
    @State private var selection2: Int = 1

    // to make 2d TabView as height as content view of 1st TabView
    @State private var viewHeight = CGFloat.infinity

    var body: some View {
        ZStack(alignment: .top) {

            // responsible for bottom Tabs
            TabView(selection: $selection1) {
                Color.clear
                    .background(GeometryReader {
                        // read 1st content height
                        Color.clear.preference(key: ViewHeightKey.self,
                                               value: $0.frame(in: .local).size.height)
                    })
                    .tabItem{Image(systemName: "1.square")}.tag(1)
                Color.clear
                    .tabItem{Image(systemName: "2.square")}.tag(2)
                Color.clear
                    .tabItem{Image(systemName: "3.square")}.tag(3)
            }

            // responsible for paging
            TabView(selection: $selection2) {
                Color.yellow.overlay(Text("First"))
                    .tag(1)
                Color.green.overlay(Text("Second"))
                    .tag(2)
                Color.blue.overlay(Text("Third"))
                    .tag(3)
            }
            .tabViewStyle(.page(indexDisplayMode: .never))
            .frame(maxHeight: viewHeight)   // content height
        }
        .onPreferenceChange(ViewHeightKey.self) {
            self.viewHeight = $0  // apply content height
        }
        .onChange(of: selection1) {
            selection2 = $0  // sync second
        }
        .onChange(of: selection2) {
            selection1 = $0  // sync first
        }
    }
}

struct ViewHeightKey: PreferenceKey {
    static var defaultValue: CGFloat { 0 }
    static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
        value = value + nextValue()
    }
}

</code>```

Body:
I am new with iOS and swiftUi. I got stuck when try to make tabview display as default but also want my tabview is wipeable.
I already know that we can make tabview swipe able by adding tabViewStyle but the navigator in the bottom will be disappeared.

        .tabViewStyle(.page(indexDisplayMode: .never))

The solution that I can think of is add a new View in the bottom and custom like a navigator, hope that someone know other better solution than that.
Thank you !

Body:
A possible approach is to use two synchronised TabView for this purpose by matching selections and aligned content height. See also comments inline.

Tested with Xcode 13.2 / iOS 15.2

struct TestTwoTabViews: View {
    @State private var selection1: Int = 1
    @State private var selection2: Int = 1

    // to make 2d TabView as height as content view of 1st TabView
    @State private var viewHeight = CGFloat.infinity

    var body: some View {
        ZStack(alignment: .top) {

            // responsible for bottom Tabs
            TabView(selection: $selection1) {
                Color.clear
                    .background(GeometryReader {
                        // read 1st content height
                        Color.clear.preference(key: ViewHeightKey.self,
                                               value: $0.frame(in: .local).size.height)
                    })
                    .tabItem{Image(systemName: "1.square")}.tag(1)
                Color.clear
                    .tabItem{Image(systemName: "2.square")}.tag(2)
                Color.clear
                    .tabItem{Image(systemName: "3.square")}.tag(3)
            }

            // responsible for paging
            TabView(selection: $selection2) {
                Color.yellow.overlay(Text("First"))
                    .tag(1)
                Color.green.overlay(Text("Second"))
                    .tag(2)
                Color.blue.overlay(Text("Third"))
                    .tag(3)
            }
            .tabViewStyle(.page(indexDisplayMode: .never))
            .frame(maxHeight: viewHeight)   // content height
        }
        .onPreferenceChange(ViewHeightKey.self) {
            self.viewHeight = $0  // apply content height
        }
        .onChange(of: selection1) {
            selection2 = $0  // sync second
        }
        .onChange(of: selection2) {
            selection1 = $0  // sync first
        }
    }
}

struct ViewHeightKey: PreferenceKey {
    static var defaultValue: CGFloat { 0 }
    static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
        value = value + nextValue()
    }
}


问:
MySQL synchronisation between 2 db
I am currently looking for a quick way to sync my production db and my dev-db.

I was thinking of doing it with something like this :

```<code>mysqladmin -u <user> -p<password> <dev-db_name> | mysqldump -u <user> -p<password> --databases <production-db-name> --add-drop-table
</code>```

but it seems that it just prints all of the drump on the screen instead of piping it to the mysqladmin util. Would there be any suggestion to improve this ?

答: You could also look into the master / slave replication paradigm... if you just need to read from the dev-db, this is perfect...</p>

OwnerDisplayName: Erick

ContentLicense: CC BY-SA 2.5

Title: MySQL synchronisation between 2 db

Body:
I am currently looking for a quick way to sync my production db and my dev-db.

I was thinking of doing it with something like this :

mysqladmin -u <user> -p<password> <dev-db_name> | mysqldump -u <user> -p<password> --databases <production-db-name> --add-drop-table

but it seems that it just prints all of the drump on the screen instead of piping it to the mysqladmin util. Would there be any suggestion to improve this ?

OwnerDisplayName: Varkhan


问:
Why do we need "MultiOutputClassifier" if we can get same results without it?
I am learning about multi-label multi-classification examples

It is when you have a case like this

```<code>Year   Actor     Budget      |   Genre
------------------------------------------------
2004   Tom C.    40,000,000  |   Action, Darama
2016   Mel G.    54,000,000  |   Comedy, Action, Family
2021   Eva K.    3,000,000   |   Comedy, Romance
</code>```

I saw an example using MultiOutputClassifier but I do not see a value of using this classifier as models still work without it, without any problem.

Here is the example, you will see that at line (1) which is without MultiOutputClassifier, the results are similar to line (2) with MultiOutputClassifier

so in that case why would anyone use MultiOutputClassifier?

```<code>from sklearn.datasets import make_classification
from sklearn.multioutput import MultiOutputClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.utils import shuffle
import numpy as np
import datetime

def time_to_sec(dt):
   ms = (dt.days * 24 * 60 * 60 + dt.seconds) * 1000 + dt.microseconds / 1000.0
   ms = ms / 1000.0
   return ms

X, y1 = make_classification(n_samples=100000, n_features=100, n_informative=30, n_classes=3, random_state=1)
y2 = shuffle(y1, random_state=1)
y3 = shuffle(y1, random_state=2)
Y = np.vstack((y1, y2, y3)).T
n_samples, n_features = X.shape # 10,100
n_outputs = Y.shape[1] # 3
n_classes = 3

forest = RandomForestClassifier(random_state=1)
Tx = datetime.datetime.now()
forest.fit(X, Y).predict(X)  # <------------------------------- (1)
Ty = datetime.datetime.now()
Sec1 = time_to_sec(Tx-Ty)

multi_target_forest = MultiOutputClassifier(forest, n_jobs=-1)
Tx = datetime.datetime.now()
multi_target_forest.fit(X, Y).predict(X)  # <------------------ (2)
Ty = datetime.datetime.now()
Sec2 = time_to_sec(Tx-Ty)

print("Time spend for line (1) = " + str(Sec1))
print("Time spend for line (2) = " + str(Sec2))
</code>```

答:
Not every model supports multi-output supervised learning. MultiOutputClassifier is a convenient way to train independent single-output models so that you don't have to manually for-loop through every output and clone your base model. You also benefit from parallelization (see n_jobs parameter).

Note that RandomForestClassifier takes into account possible relationship between outputs by calculating the average reduction across all outputs. So it is not equivalent to MultiOutputClassifier as it creates only one, overall model.

Body:
I am learning about multi-label multi-classification examples

It is when you have a case like this

Year   Actor     Budget      |   Genre
------------------------------------------------
2004   Tom C.    40,000,000  |   Action, Darama
2016   Mel G.    54,000,000  |   Comedy, Action, Family
2021   Eva K.    3,000,000   |   Comedy, Romance

I saw an example using MultiOutputClassifier but I do not see a value of using this classifier as models still work without it, without any problem.

Here is the example, you will see that at line (1) which is without MultiOutputClassifier, the results are similar to line (2) with MultiOutputClassifier

so in that case why would anyone use MultiOutputClassifier?

from sklearn.datasets import make_classification
from sklearn.multioutput import MultiOutputClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.utils import shuffle
import numpy as np
import datetime

def time_to_sec(dt):
   ms = (dt.days * 24 * 60 * 60 + dt.seconds) * 1000 + dt.microseconds / 1000.0
   ms = ms / 1000.0
   return ms

X, y1 = make_classification(n_samples=100000, n_features=100, n_informative=30, n_classes=3, random_state=1)
y2 = shuffle(y1, random_state=1)
y3 = shuffle(y1, random_state=2)
Y = np.vstack((y1, y2, y3)).T
n_samples, n_features = X.shape # 10,100
n_outputs = Y.shape[1] # 3
n_classes = 3

forest = RandomForestClassifier(random_state=1)
Tx = datetime.datetime.now()
forest.fit(X, Y).predict(X)  # <------------------------------- (1)
Ty = datetime.datetime.now()
Sec1 = time_to_sec(Tx-Ty)

multi_target_forest = MultiOutputClassifier(forest, n_jobs=-1)
Tx = datetime.datetime.now()
multi_target_forest.fit(X, Y).predict(X)  # <------------------ (2)
Ty = datetime.datetime.now()
Sec2 = time_to_sec(Tx-Ty)

print("Time spend for line (1) = " + str(Sec1))
print("Time spend for line (2) = " + str(Sec2))


答:
With regex you can use that:

^[^0]\d+"
And add the rest of your usage, this will avoid 0 being in the begining.
[^] match any character that is not in the set - so putting 0 inside will avoid the first char to be 0 (with [^0]).

Title: Input field that only allows numbers but doesn't allow a single 0 in ReactJS

Body:
I need an input form that works with money. You can't type text, symbols, or anything besides numbers but you also shouldn't be able to put $0. It should be $1 and up. When I put /^[0-9\b]+$/ it only allows numbers but you can put $0. When I use /^[1-9\b]+$/ it doesn't let you put in a zero but if you type 1 and try to put a zero it won't let you. When I try /^[1-9\b]+/, it doesn't allow zero but now you can type text and characters. Is there a better way to do this?

const re = /^[0-9\b]+$/ is the current regex I'm using.

This is in ReactJS


问:
Process communication in Python
What is the best way to establish communication between two processes in python? After some googling, I tried to do so:

```<code>parent_pipe, child_pipe = Pipe()
p = Process(target = instance_tuple.instance.run(), \
    args = (parent_pipe, child_pipe,))
p.start()
</code>```

Sending data to the child process:

```<code>command = Command(command_name, args)
parent_pipe.send(command)
</code>```

Process target function:

```<code>while True:
    if (self.parent_pipe.poll()):
        command = parent_pipe.recv()
        if (command.name == 'init_model'):
            self.init_model()
        elif (command.name == 'get_tree'):
            tree = self.get_fidesys_tree(*command.args)
            result = CommandResult(command.name, tree)
            self.child_pipe.send(result)
        elif(command.name == 'set_variable'):
            name = command.args[0]
            value = command.args[1]
            self.config[name] = value
</code>```

But it doesn't seem to work (child process doesn't receive anything through parent_pipe). How can I fix it?

Thanks in advance.

答:
If I understand the documentation, in child process you should read from the child part of the pipe.</p>

```<code># Process Target function

while True:
        # poll(None) because you don't want to go through the loop fast between commands
        if (self.child_pipe.poll(None)):
            command = child_pipe.recv()
            if (command.name == 'init_model'):
                self.init_model()
            elif (command.name == 'get_tree'):
                tree = self.get_fidesys_tree(*command.args)
                result = CommandResult(command.name, tree)
                self.child_pipe.send(result)
            elif(command.name == 'set_variable'):
                name = command.args[0]
                value = command.args[1]
                self.config[name] = value
</code>```

Title: Process communication in Python

Body:
What is the best way to establish communication between two processes in python? After some googling, I tried to do so:

parent_pipe, child_pipe = Pipe()
p = Process(target = instance_tuple.instance.run(), \
    args = (parent_pipe, child_pipe,))
p.start()

Sending data to the child process:

command = Command(command_name, args)
parent_pipe.send(command)

Process target function:

while True:
    if (self.parent_pipe.poll()):
        command = parent_pipe.recv()
        if (command.name == 'init_model'):
            self.init_model()
        elif (command.name == 'get_tree'):
            tree = self.get_fidesys_tree(*command.args)
            result = CommandResult(command.name, tree)
            self.child_pipe.send(result)
        elif(command.name == 'set_variable'):
            name = command.args[0]
            value = command.args[1]
            self.config[name] = value

But it doesn't seem to work (child process doesn't receive anything through parent_pipe). How can I fix it?

Thanks in advance.

Body:
If I understand the documentation, in child process you should read from the child part of the pipe.

# Process Target function

while True:
        # poll(None) because you don't want to go through the loop fast between commands
        if (self.child_pipe.poll(None)):
            command = child_pipe.recv()
            if (command.name == 'init_model'):
                self.init_model()
            elif (command.name == 'get_tree'):
                tree = self.get_fidesys_tree(*command.args)
                result = CommandResult(command.name, tree)
                self.child_pipe.send(result)
            elif(command.name == 'set_variable'):
                name = command.args[0]
                value = command.args[1]
                self.config[name] = value


问:
How to use `Environ("USERPROFILE")` to open workbook on desktop , while desktop location changed to another drive (D)?
On my work PC, I have no write on system drive (c).

So, I have used properties of desktop folder and changed location of it to another drive (d).

From windows 10,  I am using my desktop from that drive (d) similarly as it was on drive (c).

Problem: I tried this vba code to open workbook on my desktop

```<code>Dim wb1 As Workbook: Set wb1 = Workbooks.Open(Environ("USERPROFILE") & "\Desktop\Query1.xls")
</code>```

,but I got this error

Run-time error 1004:Sorry, we couldn't find C:\Users\Waleed\Desktop\Query1.xls. Is it possible it was moved, renamed or deleted?

I am asking this question, as I use excel files on my work pc and my laptop (no restriction) interchangeably

And it is hard to change my vba codes every time I change my machine.

As always , thanks for any help.

答:
Use vbscript SpecialFolders.

```<code>   Set objShell = Wscript.CreateObject("Wscript.Shell")
   strPath = objShell.SpecialFolders("Desktop")
</code>```

See full list here.

```<code>Function Desktop() As String
'returns the path to Desktop
    Desktop = CreateObject("wscript.shell").specialfolders("desktop")
End Function
</code>```

Body:
On my work PC, I have no write on system drive (c).

So, I have used properties of desktop folder and changed location of it to another drive (d).

From windows 10,  I am using my desktop from that drive (d) similarly as it was on drive (c).

Problem: I tried this vba code to open workbook on my desktop

Dim wb1 As Workbook: Set wb1 = Workbooks.Open(Environ("USERPROFILE") & "\Desktop\Query1.xls")

,but I got this error

Run-time error 1004:Sorry, we couldn't find C:\Users\Waleed\Desktop\Query1.xls. Is it possible it was moved, renamed or deleted?

I am asking this question, as I use excel files on my work pc and my laptop (no restriction) interchangeably

And it is hard to change my vba codes every time I change my machine.

As always , thanks for any help.

Body:
Use vbscript SpecialFolders.

   Set objShell = Wscript.CreateObject("Wscript.Shell")
   strPath = objShell.SpecialFolders("Desktop")

See full list here.

Function Desktop() As String
'returns the path to Desktop
    Desktop = CreateObject("wscript.shell").specialfolders("desktop")
End Function


问:
Vue project cannot resolve '@'
My vue-cli version is 4.5.15, but it cannot resolve @ as ./src and all paths using '@' are not found. Why did this happen and how could I solve it?

答:
I have known what the problem is. It's because I used 'Index.vue' as the name before and git is insensitive to capital. So it cannot find the path.
Vue has supported

```<code>import xxx from "@/xxx"
</code>```

if the name of your file you want to import is "index.vue".

Thanks a lot for your answers!

Title: Vue project cannot resolve '@'

Body:
I have known what the problem is. It's because I used 'Index.vue' as the name before and git is insensitive to capital. So it cannot find the path.
Vue has supported

import xxx from "@/xxx"

if the name of your file you want to import is "index.vue".

Thanks a lot for your answers!


问:
How to check specifications of a base64 image before upload for secure uploading
I am posting a base64 image with ajax to PHP...But I wanna check specs before move to image to folder...

how to check if image is base64 image or not...

how to check if image is larger than 1Mbyte...

or anything else to secure upload... Here is my php upload code:

```<code> $img_teknik_1   = $_POST["base64image_1"];
 $img_teknik_1   = str_replace('data:image/png;base64,', '', $img_teknik_1);
 $img_teknik_1   = str_replace(' ', '+', $img_teknik_1);
 $data_teknik_1  = base64_decode($img_teknik_1);
 $file_teknik_1  = UPLOAD_DIR . $resim_kodu . '_teknik_1.png';
 $success_1      = file_put_contents($file_teknik_1, $data_teknik_1);}
</code>```

答:
You can simply use:

```<code>strlen($_POST["base64image_1"]) <= 1048576
</code>```

to check the size of the image (1 KiB = 1024 Bytes)

```<code>base64_decode($_POST["base64image_1"]) !== false;
</code>```

to check the encoding.

Body:
I am posting a base64 image with ajax to PHP...But I wanna check specs before move to image to folder...

how to check if image is base64 image or not...

how to check if image is larger than 1Mbyte...

or anything else to secure upload... Here is my php upload code:

 $img_teknik_1   = $_POST["base64image_1"];
 $img_teknik_1   = str_replace('data:image/png;base64,', '', $img_teknik_1);
 $img_teknik_1   = str_replace(' ', '+', $img_teknik_1);
 $data_teknik_1  = base64_decode($img_teknik_1);
 $file_teknik_1  = UPLOAD_DIR . $resim_kodu . '_teknik_1.png';
 $success_1      = file_put_contents($file_teknik_1, $data_teknik_1);}

Body:
You can simply use:

strlen($_POST["base64image_1"]) <= 1048576

to check the size of the image (1 KiB = 1024 Bytes)

base64_decode($_POST["base64image_1"]) !== false;

to check the encoding.


问:
Change default location of vimrc
In Vim, is it possible to change the default location of the user vimrc file, i.e., from $HOME/.vimrc to some other location ?</p>

答: Another solution might be to create a symlink to you preferred location. I have my .vimrc in $HOME/.vim/.vimrc and symlink to it. This way I can have it in a git repo and backup it.

Title: Change default location of vimrc


问:
Exclude S3 folders from bucket.objects.filter(Prefix=prefix)
I have a python boto3 code which lists all the objects under s3 folder/prefix. This code will return all the objects i.e.

temp/test/date=17-09-2019/

temp/test/date=17-09-2019/100.json

I want to exclude temp/test/date=17-09-2019/ key from the response. I know that concept of folder does not exist in s3. Please find my code below:

```<code>bucket_name = 'temp-bucket'
prefix = 'temp/test/date=17-09-2019'

bucket = s3_resource.Bucket(bucket_name)
s3_files = list(bucket.objects.filter(Prefix=prefix))

for file in s3_files:
    print(file)
</code>```

Is there a way to exclude folder's from the response ?

Thanks

答:
You can check item.size, as directories has size=0:

```<code>for item in response:
    if item.size > 0:
        print(item.key)
</code>```

Body:
I have a python boto3 code which lists all the objects under s3 folder/prefix. This code will return all the objects i.e.

temp/test/date=17-09-2019/

temp/test/date=17-09-2019/100.json

I want to exclude temp/test/date=17-09-2019/ key from the response. I know that concept of folder does not exist in s3. Please find my code below:

bucket_name = 'temp-bucket'
prefix = 'temp/test/date=17-09-2019'

bucket = s3_resource.Bucket(bucket_name)
s3_files = list(bucket.objects.filter(Prefix=prefix))

for file in s3_files:
    print(file)

Is there a way to exclude folder's from the response ?

Thanks

Body:
You can check item.size, as directories has size=0:

for item in response:
    if item.size > 0:
        print(item.key)


问:
Regex for capturing a block of variable assignments
I have tokens that I need to parse and would like to have a regex that captures them. Here is how the tokens look

```<code>EVAL
INPUT A = 5;
INPUT B = 6;
...
INPUT LongVariableName = 10;
</code>```

I want to validate that every EVAL block is formatted correctly for parsing. A naive approach I have is to take these tokens and build a string out of them like so:

"EVAL:INPUT A = 5;#...#INPUT EXAMPLE = 10;#" where we signify that we have an EVAL with a : separating it from the inputs. Each input is then delimited by a #.

Or getting into the spirit of regex, EVAL:(INPUT ID = NUM;#)+,

where ID begins with an alphabetic character but can contain any amount of alphanumeric characters after,  and

NUM is any nonnegative integer.

there must always be at least one INPUT.

I want this regex to make sure that within the string that we build, each input is instantiated (with INPUT), named (with ID), assigned a value and terminated with  = NUM;, and delimited correctly (with #).

I am however having trouble how to design the regex so that we are able to capture variable names of any length greater than one.

答:
I am however having trouble how to design the regex so that we are able to capture variable names of any length greater than one

I suggest that you construct a state machine for this.
You could define states in which your lexer is currently in and based on that process the strings.

You could use a loop and inside you construct several if statements to detect the state of the lexer and have the corresponding action in it.

So initially your lexer's state would be set to read # followed by a string INPUT then after reading it the lexer's state would be set to read ID. For this you could use sub-states (say readID), i.e initially the lexer's readID state would be set to a constant READ_FIRST_CHAR(that you define as a macro or enum) which would be any of the alphabetic character, right after reading the first character of ID you set the readID state to read READ_INTERIOR_CHAR, which is any alphanumeric character.

I hope you get the idea. The language you defined is very simple and I don't think you would need a parser for it.

Body:
I have tokens that I need to parse and would like to have a regex that captures them. Here is how the tokens look

EVAL
INPUT A = 5;
INPUT B = 6;
...
INPUT LongVariableName = 10;

I want to validate that every EVAL block is formatted correctly for parsing. A naive approach I have is to take these tokens and build a string out of them like so:

"EVAL:INPUT A = 5;#...#INPUT EXAMPLE = 10;#" where we signify that we have an EVAL with a : separating it from the inputs. Each input is then delimited by a #.

Or getting into the spirit of regex, EVAL:(INPUT ID = NUM;#)+,

where ID begins with an alphabetic character but can contain any amount of alphanumeric characters after,  and

NUM is any nonnegative integer.

there must always be at least one INPUT.

I want this regex to make sure that within the string that we build, each input is instantiated (with INPUT), named (with ID), assigned a value and terminated with  = NUM;, and delimited correctly (with #).

I am however having trouble how to design the regex so that we are able to capture variable names of any length greater than one.


问:
Algorithm to determine whether a point lies within a bounded area
How does one determine whether one or more points lie within an area whose boundary is given? For instance, in the following figure, three blue points lie within the area bounded in red, two red points lie within the area bounded in blue, and there are three points - two blue and one red - which do not lie within either of the indicated areas.

答:
look here

It's C, but code/algorithm can be converted to C# with ease.


问:
Loading Data using hugging_face load_dataset from common voices giving error
I am working on voice dataset using facebook hugging-face transformer but unable to load data from commonvoice forum

```<code>from datasets import load_dataset, load_metric
common_voice_train = load_dataset("common_voice", "id", split="train+validation")
common_voice_test = load_dataset("common_voice", "id", split="test")
</code>```

it gives following error

```<code>  Couldn't find file locally at common_voice/common_voice.py, or remotely at https://raw.githubusercontent.com/huggingface/datasets/1.4.1/datasets/common_voice/common_voice.py.
The file was picked from the master branch on github instead at https://raw.githubusercontent.com/huggingface/datasets/master/datasets/common_voice/common_voice.py.
</code>```

答:
You are using the Hugging Face lightweight datasets library to load the Common Voice repository dataset. The id parameter must be replaced with the builder configuration parameter, for instance, if you want to load the English dataset from the Common Voice corpus, the builder configuration parameter is en.

You can check the parameter on the Common Voice repository. It is prefixed where the version is mentioned.

Body:
I am working on voice dataset using facebook hugging-face transformer but unable to load data from commonvoice forum

from datasets import load_dataset, load_metric
common_voice_train = load_dataset("common_voice", "id", split="train+validation")
common_voice_test = load_dataset("common_voice", "id", split="test")

it gives following error

  Couldn't find file locally at common_voice/common_voice.py, or remotely at https://raw.githubusercontent.com/huggingface/datasets/1.4.1/datasets/common_voice/common_voice.py.
The file was picked from the master branch on github instead at https://raw.githubusercontent.com/huggingface/datasets/master/datasets/common_voice/common_voice.py.


问:
Skip a page when the back button is pressed, WP7
In the current released version of WP7 you have no programmatic control over the page stack.

I start at A, go to B, and then C.  B is the data entry page for new items, so coming back from C I want to logically land at A.  Currently I listen for navigation on B that comes from C and force another back onto A.  However, the event doesn't happen soon enough to stop the page from displaying on-screen.

A -> B -> C

C -> A

A is the top level list page.  B is the new item page.  C is the item detail page.

This only occurs on one form so far so my workaround is to override OnNavigatedTo in the page I want to skip, and call "go back" programmatically.  However, this has the undesired effect of briefly showing the page and then immediately navigating off of it.

Is there a workable way to stop the flicker?

Should my workaround instead be to take full control of page navigation, including go backs?  This will leave the page stack is a strange state, but that would be hidden from the user if I control all navigation.

I know there is a new feature in Mango to pop a page from the page stack programmatically, but I'm curious to know if there is a solution to the problem in the released version.

Another motivation for this is I don't know what version will be best to target, the latest, or the one that is just enough for the app.  For the time being I'm sticking with the live version.

答: You should read this blog post on solving circular navigation issues and you can download this recipe code which demonstrates non-linear navigation.</p>


答:
This code is navigating to http://localhost:3000/?chain=ETH and then reload the page. And url also not reset to http://localhost:3000

```<code>export default function Home() {
  const [visible, setVisible] = useState(true);
  const navigate = useNavigate();

  const handleClickEthereum = () => (e) => {
    navigate({
      pathname: "/",
      search: "?chain=ETH"
    });
    window.location.reload();
    setVisible(false);
  };
  return (
    <div>
      {JSON.stringify(visible)}
      <button onClick={handleClickEthereum()}>Click ETH</button>
    </div>
  );
}
</code>```

Title: After the page is reloaded, the url created with useHistory push is deleted

Body:
I have such a code, but the url is reset after the page is refreshed. Is there any solution to this? I want the page to reload after the url changes to " localhost:3000/?chain=ETH ", but after the reload the url is reset. so only "localhost:3000" remains. How can I prevent this?

  const handleClickEthereum = async () => {
    try {
      await handleNetworkSwitch("ethereum");
      navigate({
        pathname: "/",
        search: "?chain=ETH",
      });
      window.location.reload(false);
      setVisible(false);
    } catch (error) {
      console.log(error);
    }
  };

Maybe the whole code on the relevant page can help. I wanted to share the other codes on the page.
All codes page

import React, { useState, useContext, useEffect } from "react";
import { Modal, Button } from "antd";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import BinanceCSS from "./modals.module.css";
import { useNavigate } from "react-router-dom";
import { useLocation } from "react-router-dom";
import { ReactSVG } from "react-svg";
import BinanceLogo from "../../assets/svg/binance.svg";
import PolygonLogo from "../../assets/svg/polygon.svg";
import EthereumLogo from "../../assets/svg/ethereum.svg";
//CONTEXT API
import BinanceContext from "../../context/BinanceContext";

const BinanceModal = () => {
  const { t } = useTranslation();

  const navigate = useNavigate();
  const location = useLocation();

  const [error, setError] = useState("hata var");

  const { visible, setVisible, handleNetworkSwitch, switchUrlState } =
    useContext(BinanceContext);

  const handleClickPolygon = async () => {
    try {
      await handleNetworkSwitch("polygon");
      navigate({
        pathname: "/",
        search: "?chain=Matic",
      });
      window.location.replace("/?chain=Matic");
      setVisible(false);
      console.log("sonuç", switchUrlState[0]);
    } catch (error) {
      console.log(error);
    }
  };

  const handleClickBinance = async () => {
    try {
      await handleNetworkSwitch("bsc");
      navigate({
        pathname: "/",
        search: "?chain=BSC",
      });
      window.location.replace("/?chain=BSC");
      setVisible(false);
    } catch (error) {
      console.log(error);
    }
  };

  const handleClickEthereum = async () => {
    try {
      await handleNetworkSwitch("ethereum");
      navigate({
        pathname: "/",
        search: "?chain=ETH",
      });

      setVisible(false);
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <>
      <Modal
        title={t("binance_modal_title")}
        centered
        visible={visible}
        onOk={() => setVisible(false)}
        onCancel={() => setVisible(false)}
        width={800}
        footer={null}
      >

          {/* -----BSC----- */}
          <Wrapper onClick={() => handleClickBinance()}>
            <ReactSVG className={BinanceCSS.binanceIcon} src={BinanceLogo} />

{t("binance")}

          </Wrapper>
          {/* -----POLYGON----- */}
          <Wrapper onClick={() => handleClickPolygon()}>
            <ReactSVG className={BinanceCSS.polygonIcon} src={PolygonLogo} />

{t("polygon")}

          </Wrapper>
          {/* -----ETHEREUM----- */}
          <Wrapper onClick={() => handleClickEthereum()}>
            <ReactSVG className={BinanceCSS.ethereumIcon} src={EthereumLogo} />

{t("ethereum")}

          </Wrapper>

      </Modal>
    </>
  );
};

const Wrapper = styled.div`
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 12rem;
  height: 10rem;
  border-radius: 1.5rem;
  border: 1px solid #e2e2e2;
  cursor: pointer;
  padding-top: 1rem;
  transition: all 0.3s ease-in-out;
  margin-bottom: 2.5rem;
  &:hover {
    background: #ebeaea;
  }
`;

export default BinanceModal;

Body:
This code is navigating to http://localhost:3000/?chain=ETH and then reload the page. And url also not reset to http://localhost:3000

export default function Home() {
  const [visible, setVisible] = useState(true);
  const navigate = useNavigate();

  const handleClickEthereum = () => (e) => {
    navigate({
      pathname: "/",
      search: "?chain=ETH"
    });
    window.location.reload();
    setVisible(false);
  };
  return (
    <div>
      {JSON.stringify(visible)}
      <button onClick={handleClickEthereum()}>Click ETH</button>
    </div>
  );
}


问:
App not installed
I'm having problems when i try to install my apk in release mode, if I donwload the debug file, it works ok, but if I try to install the release file, it just says me "App not installed", image:

that is my manifest file:

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="PACKAGE" >

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".ReportActivity"
            android:label="@string/title_activity_report" >
        </activity>

        <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
        <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="@string/google_maps_key"/>

        <service
            android:name=".Services.PositioningService"
            android:enabled="true"
            android:exported="true" >
        </service>

        <receiver
            android:name=".Receiver.PositioningBroadcastReceiver"
            android:enabled="true"
            android:exported="true" >
        </receiver>

    </application>

</manifest>
</code>```

I had already checked this link, but it didn't work!
App Not Installed error
Thank you folks!

答:
in your build.gradle app module , set  minifyEnabled to false. the minify may obfuscate your code making it not so usable.
like so</p>
```<code> buildTypes {
    release {
        //debuggable true
        minifyEnabled false // specify minify enabled to false
        signingConfig signingConfigs.release

        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
</code>```

Title: App not installed

Body:
I'm having problems when i try to install my apk in release mode, if I donwload the debug file, it works ok, but if I try to install the release file, it just says me "App not installed", image:

that is my manifest file:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="PACKAGE" >

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".ReportActivity"
            android:label="@string/title_activity_report" >
        </activity>

        <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
        <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="@string/google_maps_key"/>

        <service
            android:name=".Services.PositioningService"
            android:enabled="true"
            android:exported="true" >
        </service>

        <receiver
            android:name=".Receiver.PositioningBroadcastReceiver"
            android:enabled="true"
            android:exported="true" >
        </receiver>

    </application>

</manifest>

I had already checked this link, but it didn't work!
App Not Installed error
Thank you folks!

Body:
in your build.gradle app module , set  minifyEnabled to false. the minify may obfuscate your code making it not so usable.
like so

 buildTypes {
    release {
        //debuggable true
        minifyEnabled false // specify minify enabled to false
        signingConfig signingConfigs.release

        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }


答:
For validation you can match the string to the following regular expression to determine which blocks are formatted correctly:

```<code>^EVAL *\r?\n(?:INPUT +[a-z][a-z\d]* += +\d+; *\r?\n)+
</code>```

Demo

For formatting replacing matches of the following regular expression with a space will get you close:

```<code>\r?\n(?!EVAL\b)
</code>```

Demo

If the string looks like this:

```<code>EVAL
INPUT A = 5;
INPUT B = 6;
INPUT LongVariableName = 10;
EVAL
INPUT Dog = 55;
INPUT Cat9Lives = 6;
</code>```

the following string will be result:

```<code>EVAL INPUT A = 5;  INPUT B = 6;  INPUT LongVariableName = 10;
EVAL INPUT Dog = 55;  INPUT Cat9Lives = 6;
</code>```

Title: Regex for capturing a block of variable assignments

Body:
For validation you can match the string to the following regular expression to determine which blocks are formatted correctly:

^EVAL *\r?\n(?:INPUT +[a-z][a-z\d]* += +\d+; *\r?\n)+

Demo

For formatting replacing matches of the following regular expression with a space will get you close:

\r?\n(?!EVAL\b)

Demo

If the string looks like this:

EVAL
INPUT A = 5;
INPUT B = 6;
INPUT LongVariableName = 10;
EVAL
INPUT Dog = 55;
INPUT Cat9Lives = 6;

the following string will be result:

EVAL INPUT A = 5;  INPUT B = 6;  INPUT LongVariableName = 10;
EVAL INPUT Dog = 55;  INPUT Cat9Lives = 6;


问:
Is there a way to resolve repeated server error problem in LaTex (Overleaf)?
I ran into this error while trying to compile my overleaf latex;

"Server Error Sorry, something went wrong and your project could not be compiled. Please try again in a few moments".

Your response will be helpful. Thanks

答: This problem may arise as a result of the internet connection. The simple way to resolve this problem is to reload the Overleaf editor by refreshing your browser.</p>