问:
Using Selenium and Chromedriver in Google Colab
I'm using following code to extract the reviews from amazon product page. I am running it in Google colab. The code runs fine and does not show any error. But it does not open chrome and perform the function. Please check what's the error?</p>
```<code># install selenium
!pip install selenium

# install chromedriver
!apt-get update
!apt install chromium-chromedriver
!cp /usr/lib/chromium-browser/chromedriver /usr/bin

# set options to be headless, ..
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')

# open it, go to a website, and get results
driver = webdriver.Chrome('chromedriver',options=options)
driver.get("https://www.amazon.com/Under-Armour-Charged-Assert-Black/dp/B087TQBBXD/")

# wait for the page to load
driver.implicitly_wait(5)

# locate all elements with the specified xpath
elements = driver.find_elements(by='xpath', value="//span[@class='a-size-base review-text']")

# print the text of each element
for element in elements:
  print(element.text)

# close the driver
driver.quit()

</code>```

Body:
I'm using following code to extract the reviews from amazon product page. I am running it in Google colab. The code runs fine and does not show any error. But it does not open chrome and perform the function. Please check what's the error?

# install selenium
!pip install selenium

# install chromedriver
!apt-get update
!apt install chromium-chromedriver
!cp /usr/lib/chromium-browser/chromedriver /usr/bin

# set options to be headless, ..
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')

# open it, go to a website, and get results
driver = webdriver.Chrome('chromedriver',options=options)
driver.get("https://www.amazon.com/Under-Armour-Charged-Assert-Black/dp/B087TQBBXD/")

# wait for the page to load
driver.implicitly_wait(5)

# locate all elements with the specified xpath
elements = driver.find_elements(by='xpath', value="//span[@class='a-size-base review-text']")

# print the text of each element
for element in elements:
  print(element.text)

# close the driver
driver.quit()


来源: stackexchange

问:
On GitHub Actions, what is the difference between using a container or recreating the environment on the Runner?
I'm trying to understand the difference between 2 practices when using Github Runner: copying code from a Dockerfile and recreating the environment on the Runner, or using containers.

Imagine that we have a Dockerfile with some app:

```<code>FROM ubuntu
...
</code>```

It's not important what the app is, the important part is that it runs on Ubuntu like our workflow.

Is it better use this Dockerfile to create an image and push it
to a Docker registry and then use it like this:

on: push
jobs:
  first-job:
    runs-on: ubuntu-latest
    container: container:latest
    steps:
      - name: checks-out repo
        uses: actions/checkout@v3
      - name: Greetings
        run: echo Hello World
```
<p>Or, rewrite the workflow so you don't need an image, instead
recreate this environment by youself:</p>
<pre class="lang-yaml prettyprint-override"><code>on: push
jobs:
  first-job:
    runs-on: ubuntu-latest
    steps:
      - name: recreate container
        run:|
          ....
      - name: checks-out repo
        uses: actions/checkout@v3
      - name: Greetings
        run: echo Hello World
</code>```

I can ask this question in another way. I need to setup
latex, but on github.com/action we don't have anything
to do so ( uses: actions/set-up-latex..). But I already have an image pushed to the registry https://hub.docker.com/r/blang/latex.

Is it preferred to use this image or to recreate the environment on
the runner (VM)?

I appreciate if you explain this concept explicitly with details.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to understand the difference between 2 practices when using Github Runner: copying code from a Dockerfile and recreating the environment on the Runner, or using containers.

Imagine that we have a Dockerfile with some app:

FROM ubuntu
...

It's not important what the app is, the important part is that it runs on Ubuntu like our workflow.

Is it better use this Dockerfile to create an image and push it
to a Docker registry and then use it like this:

on: push
jobs:
  first-job:
    runs-on: ubuntu-latest
    container: container:latest
    steps:
      - name: checks-out repo
        uses: actions/checkout@v3
      - name: Greetings
        run: echo Hello World

Or, rewrite the workflow so you don't need an image, instead
recreate this environment by youself:

on: push
jobs:
  first-job:
    runs-on: ubuntu-latest
    steps:
      - name: recreate container
        run:|
          ....
      - name: checks-out repo
        uses: actions/checkout@v3
      - name: Greetings
        run: echo Hello World

I can ask this question in another way. I need to setup
latex, but on github.com/action we don't have anything
to do so ( uses: actions/set-up-latex..). But I already have an image pushed to the registry https://hub.docker.com/r/blang/latex.

Is it preferred to use this image or to recreate the environment on
the runner (VM)?

I appreciate if you explain this concept explicitly with details.


问:
Fall of black pixels in a Quadtree
Hello I am trying to create a function Gravity that make all the black pixels of a Quadtree to "fall" if they can (if there is a white pixel under).
for instance Gravity(Qt1) gives Qt2 :

The Quadtree class:

```<code>typedef struct Qtree{
    bool allblack;
    struct Qtree * son[4];
}Qtree;
</code>```

I have made some auxiliariy functions:
create a black pixel

```<code>Qtree* create_Black(){
    Qtree* I -> malloc(sizeof(Qtree));
    I->son[0] = I->son[1] = I->son[2] = I->son[3] = NULL
    return I;
</code>```

create a white pixel

```<code>Qtree* create_White(){
    return NULL;
</code>```

create a Qtree based on 4 sons

```<code>Qtree* create_Comp(Qtree* i0, Qtree* i1, Qtree* i2, Qtree i3){
    Qtree* I = malloc(sizeof(Qtree));
    I->son[0] = i0;
    ...
    return I;
}
</code>```

I already have done some code that exchanges black pixel but I can obtain the result wanted :(
If some guys could help me, I can't find any ressources on internet

Title: Fall of black pixels in a Quadtree

Body:
Hello I am trying to create a function Gravity that make all the black pixels of a Quadtree to "fall" if they can (if there is a white pixel under).
for instance Gravity(Qt1) gives Qt2 :

The Quadtree class:

typedef struct Qtree{
    bool allblack;
    struct Qtree * son[4];
}Qtree;

I have made some auxiliariy functions:
create a black pixel

Qtree* create_Black(){
    Qtree* I -> malloc(sizeof(Qtree));
    I->son[0] = I->son[1] = I->son[2] = I->son[3] = NULL
    return I;

create a white pixel

Qtree* create_White(){
    return NULL;

create a Qtree based on 4 sons

Qtree* create_Comp(Qtree* i0, Qtree* i1, Qtree* i2, Qtree i3){
    Qtree* I = malloc(sizeof(Qtree));
    I->son[0] = i0;
    ...
    return I;
}

I already have done some code that exchanges black pixel but I can obtain the result wanted :(
If some guys could help me, I can't find any ressources on internet


问:
Create one table out of multiple temp tables using SQL
If it is possible, how to create one table/temp table out of multiple temp tables using SQL? Because creating a view is unfortunately not possible with temp tables.

For example, I have 3/more temp tables:

```<code>WITH a_table AS (
    SELECT *
    FROM a
    JOIN b
    WHERE ...
   )
, b_table AS (
    SELECT *
    FROM c
    JOIN d
    WHERE ...
   )
, c_table AS (
    SELECT *
    FROM c
    JOIN d
    WHERE ...
   )

SELECT * FROM a_table
UNION
SELECT * FROM b_table
UNION
SELECT * FROM c_table
</code>```

How do I create just one table instead? Or have one view for all these unioned temp tables?

Tried to create a view but that is not possible with temp tables and the query that I have has like 50 temp tables.

Body:
If it is possible, how to create one table/temp table out of multiple temp tables using SQL? Because creating a view is unfortunately not possible with temp tables.

For example, I have 3/more temp tables:

WITH a_table AS (
    SELECT *
    FROM a
    JOIN b
    WHERE ...
   )
, b_table AS (
    SELECT *
    FROM c
    JOIN d
    WHERE ...
   )
, c_table AS (
    SELECT *
    FROM c
    JOIN d
    WHERE ...
   )

SELECT * FROM a_table
UNION
SELECT * FROM b_table
UNION
SELECT * FROM c_table

How do I create just one table instead? Or have one view for all these unioned temp tables?

Tried to create a view but that is not possible with temp tables and the query that I have has like 50 temp tables.


问:
display an error message when the record is not set within the many2many odoo studio
I have a many2many that shows invoice records and a many2one where I select the invoices that
are established within that many2many so that they are transferred to a second many2many

the records are translated correctly but I need to show a message when the selected record in
the many2one is not set to the first many2many.

```<code>    '''This is what I did in an automated action:'''
    for facturas in record.x_studio_many2one_field_GPKc7:
      for rec in record.x_studio_factura_cliente_2:
        if record.x_studio_factura_cliente_2 and facturas.name in rec.name:
          record['x_studio_procesado_factura_3'] = [(4,facturas.id, 0)]
          record['x_studio_factura_cliente_2'] = [(2,facturas.id)]
        else:
          raise UserError('Error')
</code>```

Body:
I have a many2many that shows invoice records and a many2one where I select the invoices that
are established within that many2many so that they are transferred to a second many2many

the records are translated correctly but I need to show a message when the selected record in
the many2one is not set to the first many2many.

    '''This is what I did in an automated action:'''
    for facturas in record.x_studio_many2one_field_GPKc7:
      for rec in record.x_studio_factura_cliente_2:
        if record.x_studio_factura_cliente_2 and facturas.name in rec.name:
          record['x_studio_procesado_factura_3'] = [(4,facturas.id, 0)]
          record['x_studio_factura_cliente_2'] = [(2,facturas.id)]
        else:
          raise UserError('Error')


问:
I tried to run the App, But Gradle is throwing this error
`
FAILURE: Build failed with an exception.

Where:
Build file '/Users/theroushan/Documents/NextSchool/android/app/build.gradle' line: 32

What went wrong:
A problem occurred evaluating project ':app'.

No signature of method: build_4a37y44n4qcdao4l4d5njw5b5.android() is applicable for argument types: (build_4a37y44n4qcdao4l4d5njw5b5$_run_closure2) values: [build_4a37y44n4qcdao4l4d5njw5b5$_run_closure2@73288fd8]

Try:

Run with --stacktrace option to get the stack trace.
Run with --info or --debug option to get more log output.
Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 1s
Exception: Gradle task assembleDebug failed with exit code 1`

I tried to run the app, but I am getting this error in flutter?


问:
Scroll down appium robot framework fails
I am trying to scroll down through settings section in an android the android opens the settings but fails and error message ValueError: Element locator '//android.widget.LinearLayout[@index="14"]' did not match any elements.
and I am sure of the xpath as i tried it for click element and it worked without problems
Here is the code

```<code> open application    http://localhost:4723/wd/hub    platformName=Android    platformVersion=10  deviceName=emulator-5554    appPackage=com.android.settings     appActivity=com.android.settings.Settings
     scroll down     //android.widget.LinearLayout[@index="14"]
</code>```

Body:
I am trying to scroll down through settings section in an android the android opens the settings but fails and error message ValueError: Element locator '//android.widget.LinearLayout[@index="14"]' did not match any elements.
and I am sure of the xpath as i tried it for click element and it worked without problems
Here is the code

 open application    http://localhost:4723/wd/hub    platformName=Android    platformVersion=10  deviceName=emulator-5554    appPackage=com.android.settings     appActivity=com.android.settings.Settings
     scroll down     //android.widget.LinearLayout[@index="14"]


问:
How can I use System.Reflection.Emit to generate a delegate with special input and get the return value?
For example, we have such a class:

public class Message
{
    public SayType Say(string name)
    {
        Console.Write("Hello," + name);
        return SayType.Name;
    }
}

public enum SayType
{
    Name
}
```
<p>And this is my emit code:</p>
<pre class="lang-cs prettyprint-override"><code>DynamicMethod dynamicMethod =
    new DynamicMethod("Say",typeof(SayType),new Type[]{typeof(string)});
var il = dynamicMethod.GetILGenerator();
il.Emit(OpCodes.Ldarg_1);//Non-static
il.Emit(OpCodes.Callvirt,typeof(Message).GetMethods()[0]);
il.Emit(OpCodes.Ret);
System.Delegate delegates = dynamicMethod.CreateDelegate(typeof(Func<string, SayType>));
List<System.Delegate> list = new List<System.Delegate>();
list.Add(delegates);
foreach (var func in list.Cast<Func<string,SayType>>())
{
    func("e");
}
</code>```

And I got the errors:

Unhandled exception. System.InvalidProgramException: Common Language Runtime det
ected an invalid program.
   at Say(String )
```
<p>And I aslo tried use such a statement.</p>
<pre class="lang-cs prettyprint-override"><code>System.Delegate delegates = dynamicMethod.CreateDelegate(typeof(Func<string, SayType>));
delegates.DynamicInvoke("ha");
</code>```

I aslo get the errors:

```<code>Unhandled exception. System.Reflection.TargetInvocationException: Exception has
been thrown by the target of an invocation.
 ---> System.InvalidProgramException: Common Language Runtime detected an invali
d program.
   at Say(String )
</code>```

Why I get these errors?

And how can I solve the errors and get the delegate of Message.Say?

Body:
For example, we have such a class:

public class Message
{
    public SayType Say(string name)
    {
        Console.Write("Hello," + name);
        return SayType.Name;
    }
}

public enum SayType
{
    Name
}

And this is my emit code:

DynamicMethod dynamicMethod =
    new DynamicMethod("Say",typeof(SayType),new Type[]{typeof(string)});
var il = dynamicMethod.GetILGenerator();
il.Emit(OpCodes.Ldarg_1);//Non-static
il.Emit(OpCodes.Callvirt,typeof(Message).GetMethods()[0]);
il.Emit(OpCodes.Ret);
System.Delegate delegates = dynamicMethod.CreateDelegate(typeof(Func<string, SayType>));
List<System.Delegate> list = new List<System.Delegate>();
list.Add(delegates);
foreach (var func in list.Cast<Func<string,SayType>>())
{
    func("e");
}

And I got the errors:

Unhandled exception. System.InvalidProgramException: Common Language Runtime det
ected an invalid program.
   at Say(String )

And I aslo tried use such a statement.

System.Delegate delegates = dynamicMethod.CreateDelegate(typeof(Func<string, SayType>));
delegates.DynamicInvoke("ha");

I aslo get the errors:

Unhandled exception. System.Reflection.TargetInvocationException: Exception has
been thrown by the target of an invocation.
 ---> System.InvalidProgramException: Common Language Runtime detected an invali
d program.
   at Say(String )

Why I get these errors?

And how can I solve the errors and get the delegate of Message.Say?


问:
Error when calling URL using SoapLibrary library
I'm automating tests with Robot Framework using SoapLibrary, Collections, OperatingSystem, XML and Process Libraries.

When I send my XML on a Soap endpoint I get the following error:

XMLSyntaxError: Invalid XML content received (Opening and ending tag
mismatch: META line 1 and head, line 22, column 8)

I realized that the problem is not the XML sent, but the URL. But the URL is the same as the one sent via Soap (and via Soap it goes successfully).

How do I send an XML to my address?

```<code>*** Variables ***
    ${URL}    http://localhost:81/WS/DLL/JDSPB_WS_IntegraLegado.dll/soap/IJDSPBCAB

*** Test Cases ***

Test Call Soap

    Create Soap Client    ${URL}

    ${response}    Call SOAP Method With XML    ${CURDIR}/FILETEST.xml
</code>```

If I replace "soap" in the URL with "wsdl", it works! But the call is not made. Only documentation is returned, just like SOAP.

Can you help me?

Body:
I'm automating tests with Robot Framework using SoapLibrary, Collections, OperatingSystem, XML and Process Libraries.

When I send my XML on a Soap endpoint I get the following error:

XMLSyntaxError: Invalid XML content received (Opening and ending tag
mismatch: META line 1 and head, line 22, column 8)

I realized that the problem is not the XML sent, but the URL. But the URL is the same as the one sent via Soap (and via Soap it goes successfully).

How do I send an XML to my address?

*** Variables ***
    ${URL}    http://localhost:81/WS/DLL/JDSPB_WS_IntegraLegado.dll/soap/IJDSPBCAB

*** Test Cases ***

Test Call Soap

    Create Soap Client    ${URL}

    ${response}    Call SOAP Method With XML    ${CURDIR}/FILETEST.xml

If I replace "soap" in the URL with "wsdl", it works! But the call is not made. Only documentation is returned, just like SOAP.

Can you help me?


问:
Run Makefile command using Sed
I need to run this Makefile command, changing the path dynamically.

```<code>autogf:
 @bash -c 'echo ;\
 echo EJ. flutter pub run build_runner build --build-filter "lib/auth/core/domain/main.dart"; \
 read -p "[Path to file] " path; \
 echo flutter pub run build_runner build --build-filter $$path | sed -e "s/^\(.\{1,\}\/\).*\([.]dart\)$/\1**\2/"; \
 flutter pub run build_runner build --build-filter $$path | sed -e "s/^\(.\{1,\}\/\).*\([.]dart\)$/\1**\2/"; \
 echo ;\
 '
</code>```

But the command on line 5 (starting with flutter) is not working and throws the following error.

I appreciate if someone knows how to make this Makefile command work with this dynamic relative path.

Title: Run Makefile command using Sed

Body:
I need to run this Makefile command, changing the path dynamically.

autogf:
 @bash -c 'echo ;\
 echo EJ. flutter pub run build_runner build --build-filter "lib/auth/core/domain/main.dart"; \
 read -p "[Path to file] " path; \
 echo flutter pub run build_runner build --build-filter $$path | sed -e "s/^\(.\{1,\}\/\).*\([.]dart\)$/\1**\2/"; \
 flutter pub run build_runner build --build-filter $$path | sed -e "s/^\(.\{1,\}\/\).*\([.]dart\)$/\1**\2/"; \
 echo ;\
 '

But the command on line 5 (starting with flutter) is not working and throws the following error.

I appreciate if someone knows how to make this Makefile command work with this dynamic relative path.


问:
catch disjonction case exception
I have 2 classes:

```<code>class MyException extends Exception implements ExceptionManager{
    MyException addMessage(String message){...}
}
</code>```

and

```<code>class MyRuntimeException extends RuntimeException implements ExceptionManager {
    MyRuntimeException addMessage(String message){...}
}
</code>```

where

```<code>interface ExceptionManager{
    ExceptionManager addMessage(String message);
}
</code>```

I want to do this:

```<code>void foo() throws MyException {
    try {
        ...
    } catch (MyException | MyRuntimeException e){
        throw e.addMessage(...);
    }
}
</code>```

but it doesn't work ; I tried setting ExceptionManager<T extends Exception & ExceptionManager> and T addMessage(String message); or other things but still doesn't work...

Obviously I don't want foo to throw Exception nor set 2 catches and the project is java 11 so no scealed types.

Can't the compiler understand that there's only 2 possibilities for the exception to be thrown, one runtime so I only must declare the other ? Can someone tell me how to do or confirm that it's impossible ?

Thanks

Title: catch disjonction case exception

Body:
I have 2 classes:

class MyException extends Exception implements ExceptionManager{
    MyException addMessage(String message){...}
}

and

class MyRuntimeException extends RuntimeException implements ExceptionManager {
    MyRuntimeException addMessage(String message){...}
}

where

interface ExceptionManager{
    ExceptionManager addMessage(String message);
}

I want to do this:

void foo() throws MyException {
    try {
        ...
    } catch (MyException | MyRuntimeException e){
        throw e.addMessage(...);
    }
}

but it doesn't work ; I tried setting ExceptionManager<T extends Exception & ExceptionManager> and T addMessage(String message); or other things but still doesn't work...

Obviously I don't want foo to throw Exception nor set 2 catches and the project is java 11 so no scealed types.

Can't the compiler understand that there's only 2 possibilities for the exception to be thrown, one runtime so I only must declare the other ? Can someone tell me how to do or confirm that it's impossible ?

Thanks


问:
"+[CATransaction synchronize] called within transaction" with NSSavePanel
Starting with macOS Ventura (or maybe with the latest Xcode version), I'm getting log messages in my Mac app:

+[CATransaction synchronize] called within transaction

whenever the app displays an NSSavePanel (or subclass). For instance:

```<code>    NSOpenPanel* panel = [NSOpenPanel openPanel];
    panel.prompt = @"Import";
    panel.canChooseDirectories = NO;
    panel.allowsMultipleSelection = YES;
    panel.message = @"Choose chromatogram files to import into the selected folder.";
    panel.allowedFileTypes = @[@"com.appliedbiosystems.abif.fsa", @"com.appliedbiosystems.abif.hid"];
    [panel beginSheetModalForWindow:self.parentWindow completionHandler:^(NSInteger result){
        if (result == NSModalResponseOK) {
            [self addSamplesFromFiles:[panel.URLs valueForKeyPath:@"@unionOfObjects.path"] toFolder:selectedFolder];
            }
    }];
</code>```

Here, beginSheetModalForWindow triggers the warning.

If I spawn the panel with beginWithCompletionHandler (i.e., not as a sheet), the message is posted as well. In fact, it also gets posted whenever I resize the panel.

This doesn't occur with other windows or with NSAlert sheets, but this occur with all open/save panels in my app. I have checked that these panels are not used within CATransaction blocks. They are spawned from the main thread.

All panels behave normally to the user, but I'd like to know what I'm doing wrong and why this started happening.

Body:
Starting with macOS Ventura (or maybe with the latest Xcode version), I'm getting log messages in my Mac app:

+[CATransaction synchronize] called within transaction

whenever the app displays an NSSavePanel (or subclass). For instance:

    NSOpenPanel* panel = [NSOpenPanel openPanel];
    panel.prompt = @"Import";
    panel.canChooseDirectories = NO;
    panel.allowsMultipleSelection = YES;
    panel.message = @"Choose chromatogram files to import into the selected folder.";
    panel.allowedFileTypes = @[@"com.appliedbiosystems.abif.fsa", @"com.appliedbiosystems.abif.hid"];
    [panel beginSheetModalForWindow:self.parentWindow completionHandler:^(NSInteger result){
        if (result == NSModalResponseOK) {
            [self addSamplesFromFiles:[panel.URLs valueForKeyPath:@"@unionOfObjects.path"] toFolder:selectedFolder];
            }
    }];

Here, beginSheetModalForWindow triggers the warning.

If I spawn the panel with beginWithCompletionHandler (i.e., not as a sheet), the message is posted as well. In fact, it also gets posted whenever I resize the panel.

This doesn't occur with other windows or with NSAlert sheets, but this occur with all open/save panels in my app. I have checked that these panels are not used within CATransaction blocks. They are spawned from the main thread.

All panels behave normally to the user, but I'd like to know what I'm doing wrong and why this started happening.


问:
Python can't execute query on Access DB with MySQL linked table
I'm struggling with an issue using pyodbc: I've created an Access database with some linked tables on MySQL (we're migrating the company DB's), this DB is accessed by MS Access ODBC Driver through pyodbc, and in the python code we execute some queries on that DB. It works normally when INSERTING data in a linked table, but when we have to UPDATE an access table using data from a linked mysql table, pyodbc delivers this message:

```<code>('HY000', '[HY000] [Microsoft][Driver ODBC Microsoft Access] The Microsoft access database engine stopped the process because you and another user are attempting to change the same data at the same time. (-1611) (SQLExecDirectW)')
</code>```

The same UPDATE query works normally when executed directly in Access, this issue only happens when pyodbc tries to execute it.

I've found a topic on StackOverFlow about it, someone said that the problem is with Office 365. We have a test system working fine on Office 2019, with the same queries and the same DB, problem is: we can't migrate the system to Access 2019 on production.

Body:
I'm struggling with an issue using pyodbc: I've created an Access database with some linked tables on MySQL (we're migrating the company DB's), this DB is accessed by MS Access ODBC Driver through pyodbc, and in the python code we execute some queries on that DB. It works normally when INSERTING data in a linked table, but when we have to UPDATE an access table using data from a linked mysql table, pyodbc delivers this message:

('HY000', '[HY000] [Microsoft][Driver ODBC Microsoft Access] The Microsoft access database engine stopped the process because you and another user are attempting to change the same data at the same time. (-1611) (SQLExecDirectW)')

The same UPDATE query works normally when executed directly in Access, this issue only happens when pyodbc tries to execute it.

I've found a topic on StackOverFlow about it, someone said that the problem is with Office 365. We have a test system working fine on Office 2019, with the same queries and the same DB, problem is: we can't migrate the system to Access 2019 on production.


问:
importing mongodb results in error that is not related to mongodb when running the script using node command
I have a stand alone script that I am using to create an admin user. There will always be only one admin user. However, when I run the standalone script using node command in my nextjs project, I get this weird error below

```<code>node indexUser.js
/Users/nabeel.77.dev/Documents/portfolio/node_modules/whatwg-url/lib/utils.js:50
var AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf( /*#__PURE__*/_wrapAsyncGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
                                    ^

TypeError: Cannot convert undefined or null to object
    at Function.getPrototypeOf (<anonymous>)
    at Object.<anonymous> (/Users/nabeel.77.dev/Documents/portfolio/node_modules/whatwg-url/lib/utils.js:34:39)
    at Module._compile (node:internal/modules/cjs/loader:1218:14)
    at Module._compile (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:136:24)
    at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
    at Object.newLoader [as .js] (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:141:7)
    at Module.load (node:internal/modules/cjs/loader:1081:32)
    at Function.Module._load (node:internal/modules/cjs/loader:922:12)
    at Module.require (node:internal/modules/cjs/loader:1105:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at Object.<anonymous> (/Users/nabeel.77.dev/Documents/portfolio/node_modules/whatwg-url/lib/URL.js:4:15)
    at Module._compile (node:internal/modules/cjs/loader:1218:14)
    at Module._compile (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:136:24)
    at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
    at Object.newLoader [as .js] (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:141:7)
    at Module.load (node:internal/modules/cjs/loader:1081:32)
    at Function.Module._load (node:internal/modules/cjs/loader:922:12)
    at Module.require (node:internal/modules/cjs/loader:1105:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at Object.<anonymous> (/Users/nabeel.77.dev/Documents/portfolio/node_modules/whatwg-url/webidl2js-wrapper.js:3:13)
    at Module._compile (node:internal/modules/cjs/loader:1218:14)
    at Module._compile (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:136:24)
    at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
    at Object.newLoader [as .js] (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:141:7)
    at Module.load (node:internal/modules/cjs/loader:1081:32)
    at Function.Module._load (node:internal/modules/cjs/loader:922:12)
    at Module.require (node:internal/modules/cjs/loader:1105:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at Object.<anonymous> (/Users/nabeel.77.dev/Documents/portfolio/node_modules/whatwg-url/index.js:3:34)
    at Module._compile (node:internal/modules/cjs/loader:1218:14)
    at Module._compile (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:136:24)
    at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
    at Object.newLoader [as .js] (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:141:7)
    at Module.load (node:internal/modules/cjs/loader:1081:32)
    at Function.Module._load (node:internal/modules/cjs/loader:922:12)
    at Module.require (node:internal/modules/cjs/loader:1105:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at Object.<anonymous> (../src/index.ts:1:1)
    at Module._compile (node:internal/modules/cjs/loader:1218:14)
    at Module._compile (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:136:24)
    at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
    at Object.newLoader [as .js] (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:141:7)
    at Module.load (node:internal/modules/cjs/loader:1081:32)
    at Function.Module._load (node:internal/modules/cjs/loader:922:12)
    at Module.require (node:internal/modules/cjs/loader:1105:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at Object.<anonymous> (../src/connection_string.ts:3:1)
    at Module._compile (node:internal/modules/cjs/loader:1218:14)
    at Module._compile (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:136:24)
    at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)

Node.js v19.3.0

</code>```

The script I am running has the below code:

```<code>import bcrypt from 'bcryptjs';
import MongoClientConnection from '../db';
import readline from 'readline';
import { logger } from '../logger';

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

rl.question('Enter username: ', (username) => {
  rl.question('Enter email: ', (email) => {
    rl.question('Enter password: ', async (password) => {
      const hashedPassword = await bcrypt.hash(password, 10);
      const adminUserData = { username, email, hashedPassword };
      try {
        const db = await MongoClientConnection.Get();
        const res = await db.insert(adminUserData);
      } catch (e) {
        logger.error(e);
      }
      rl.close();
    });
  });
});

</code>```

In the code above, when I remove import MongoClientConnection from '../db'; the script works fine so, I believe the error is because of mongodb. I am using singleton connection for mongodb and have the below code for that

```<code>import { MongoClient } from 'mongodb';

const MongoClientConnection = (() => {
  let db = null;
  let instance = 0;

  const DbConnect = async () => {
    try {
      let url = process.env.DB_URL;
      let mongoClient = await MongoClient.connect(url, {
        useUnifiedTopology: true,
      });
      const mongoDbInstance = mongoClient.db(process.env.DB);
      return mongoDbInstance;
    } catch (e) {
      return e;
    }
  };

  const Get = async () => {
    try {
      instance++; // this is just to count how many times our singleton is called.
      console.log(`DbConnection called ${instance} times`);

      if (db != null) {
        console.log(`db connection is already alive`);
        return db;
      } else {
        console.log(`getting new db connection`);
        db = await DbConnect();
        return db;
      }
    } catch (e) {
      return e;
    }
  };

  return {
    Get: Get,
  };
})();

export default MongoClientConnection;
</code>```

Cannot really find any solution to this.

Body:
I have a stand alone script that I am using to create an admin user. There will always be only one admin user. However, when I run the standalone script using node command in my nextjs project, I get this weird error below

node indexUser.js
/Users/nabeel.77.dev/Documents/portfolio/node_modules/whatwg-url/lib/utils.js:50
var AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf( /*#__PURE__*/_wrapAsyncGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
                                    ^

TypeError: Cannot convert undefined or null to object
    at Function.getPrototypeOf (<anonymous>)
    at Object.<anonymous> (/Users/nabeel.77.dev/Documents/portfolio/node_modules/whatwg-url/lib/utils.js:34:39)
    at Module._compile (node:internal/modules/cjs/loader:1218:14)
    at Module._compile (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:136:24)
    at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
    at Object.newLoader [as .js] (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:141:7)
    at Module.load (node:internal/modules/cjs/loader:1081:32)
    at Function.Module._load (node:internal/modules/cjs/loader:922:12)
    at Module.require (node:internal/modules/cjs/loader:1105:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at Object.<anonymous> (/Users/nabeel.77.dev/Documents/portfolio/node_modules/whatwg-url/lib/URL.js:4:15)
    at Module._compile (node:internal/modules/cjs/loader:1218:14)
    at Module._compile (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:136:24)
    at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
    at Object.newLoader [as .js] (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:141:7)
    at Module.load (node:internal/modules/cjs/loader:1081:32)
    at Function.Module._load (node:internal/modules/cjs/loader:922:12)
    at Module.require (node:internal/modules/cjs/loader:1105:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at Object.<anonymous> (/Users/nabeel.77.dev/Documents/portfolio/node_modules/whatwg-url/webidl2js-wrapper.js:3:13)
    at Module._compile (node:internal/modules/cjs/loader:1218:14)
    at Module._compile (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:136:24)
    at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
    at Object.newLoader [as .js] (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:141:7)
    at Module.load (node:internal/modules/cjs/loader:1081:32)
    at Function.Module._load (node:internal/modules/cjs/loader:922:12)
    at Module.require (node:internal/modules/cjs/loader:1105:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at Object.<anonymous> (/Users/nabeel.77.dev/Documents/portfolio/node_modules/whatwg-url/index.js:3:34)
    at Module._compile (node:internal/modules/cjs/loader:1218:14)
    at Module._compile (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:136:24)
    at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
    at Object.newLoader [as .js] (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:141:7)
    at Module.load (node:internal/modules/cjs/loader:1081:32)
    at Function.Module._load (node:internal/modules/cjs/loader:922:12)
    at Module.require (node:internal/modules/cjs/loader:1105:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at Object.<anonymous> (../src/index.ts:1:1)
    at Module._compile (node:internal/modules/cjs/loader:1218:14)
    at Module._compile (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:136:24)
    at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
    at Object.newLoader [as .js] (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:141:7)
    at Module.load (node:internal/modules/cjs/loader:1081:32)
    at Function.Module._load (node:internal/modules/cjs/loader:922:12)
    at Module.require (node:internal/modules/cjs/loader:1105:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at Object.<anonymous> (../src/connection_string.ts:3:1)
    at Module._compile (node:internal/modules/cjs/loader:1218:14)
    at Module._compile (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:136:24)
    at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)

Node.js v19.3.0

The script I am running has the below code:

import bcrypt from 'bcryptjs';
import MongoClientConnection from '../db';
import readline from 'readline';
import { logger } from '../logger';

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

rl.question('Enter username: ', (username) => {
  rl.question('Enter email: ', (email) => {
    rl.question('Enter password: ', async (password) => {
      const hashedPassword = await bcrypt.hash(password, 10);
      const adminUserData = { username, email, hashedPassword };
      try {
        const db = await MongoClientConnection.Get();
        const res = await db.insert(adminUserData);
      } catch (e) {
        logger.error(e);
      }
      rl.close();
    });
  });
});

In the code above, when I remove import MongoClientConnection from '../db'; the script works fine so, I believe the error is because of mongodb. I am using singleton connection for mongodb and have the below code for that

import { MongoClient } from 'mongodb';

const MongoClientConnection = (() => {
  let db = null;
  let instance = 0;

  const DbConnect = async () => {
    try {
      let url = process.env.DB_URL;
      let mongoClient = await MongoClient.connect(url, {
        useUnifiedTopology: true,
      });
      const mongoDbInstance = mongoClient.db(process.env.DB);
      return mongoDbInstance;
    } catch (e) {
      return e;
    }
  };

  const Get = async () => {
    try {
      instance++; // this is just to count how many times our singleton is called.
      console.log(`DbConnection called ${instance} times`);

      if (db != null) {
        console.log(`db connection is already alive`);
        return db;
      } else {
        console.log(`getting new db connection`);
        db = await DbConnect();
        return db;
      }
    } catch (e) {
      return e;
    }
  };

  return {
    Get: Get,
  };
})();

export default MongoClientConnection;

Cannot really find any solution to this.


问:
Noughts and Crosses: replace numbers on the board with an empty space
I am developing a noughts and crosses game and I have to create a code to set all elements of the board to one space '  '

All integers have to be replaced by an empty space so when I print the output, it will show an empty board.

See the picture below for reference. The code I used for a populated board is as follows:

```<code>def draw_board(board):

    # Display board
    board = ["1", "2", "3",
             "4", "5", "6",
             "7", "8", "9"]
    print(" ----------- ")
    print("| " + board[0] + " | " + board[1] + " | " + board[2] + " | ")
    print(" ----------- ")
    print("| " + board[3] + " | " + board[4] + " | " + board[5] + " | ")
    print(" ----------- ")
    print("| " + board[6] + " | " + board[7] + " | " + board[8] + " | ")
    print(" ----------- ")
    text = "When prompted, enter the number corresponding to the square you want."
    print(text)

    pass
</code>```

(https://i.stack.imgur.com/s3YcL.png)

I've tried using join(), .split, .replace, and .append however, after 2 days and lots of time spent researching I couldn't figure out how to replace the numbers inside the list with an empty space.

Almost everything I tried returned a typeError: list indices must be integers or slices, not str.

I just want to print out the board without the numbers or hyphens.
I should also mention I'm a newbie at this so any help is much appreciated!

So I managed to fix it, which is great! However, another issue has arisen: see image emptyboard

Body:
I am developing a noughts and crosses game and I have to create a code to set all elements of the board to one space '  '

All integers have to be replaced by an empty space so when I print the output, it will show an empty board.

See the picture below for reference. The code I used for a populated board is as follows:

def draw_board(board):

    # Display board
    board = ["1", "2", "3",
             "4", "5", "6",
             "7", "8", "9"]
    print(" ----------- ")
    print("| " + board[0] + " | " + board[1] + " | " + board[2] + " | ")
    print(" ----------- ")
    print("| " + board[3] + " | " + board[4] + " | " + board[5] + " | ")
    print(" ----------- ")
    print("| " + board[6] + " | " + board[7] + " | " + board[8] + " | ")
    print(" ----------- ")
    text = "When prompted, enter the number corresponding to the square you want."
    print(text)

    pass

(https://i.stack.imgur.com/s3YcL.png)

I've tried using join(), .split, .replace, and .append however, after 2 days and lots of time spent researching I couldn't figure out how to replace the numbers inside the list with an empty space.

Almost everything I tried returned a typeError: list indices must be integers or slices, not str.

I just want to print out the board without the numbers or hyphens.
I should also mention I'm a newbie at this so any help is much appreciated!

So I managed to fix it, which is great! However, another issue has arisen: see image emptyboard


问:
How do I switch a landscape page in Microsoft Word to 90 degrees view
I want to switch a landscape page view in Microsoft Word to horizontal. I have tried to save the table as picture to switch 270 degrees and etc. But even so, I cant seem to make the whole landscape page to rotate at 270 degrees just as shown in the picture where the header and footer and its contents all flips 270 degrees.
View Image

Would really appreciate for everyone's help, thank you!


问:
System.InvalidOperationException: 'The LINQ expression how I Use my Type REferencesType
In the base document, I have a field that inherits from the BaseReferencesType class. It's virtual, why can't I do anything when I'm busy.
This field which i want get

public virtual ReferenceType ReferenceType { get; }
```
<p>And my script:</p>
<pre class="lang-cs prettyprint-override"><code>var document = await _context.BaseDocuments
    .Where(x => bulkPostDto.Documents.Contains(x.ReferenceType) &&
                x.CreatedDate.Value.Date >= bulkPostDto.Start.Date &&
                x.CreatedDate.Value.Date <= bulkPostDto.Finish)
    .OrderBy(x => x.DocumentDate)
    .ToListAsync();
</code>```

Now my problem looks like this@

System.InvalidOperationException: 'The expression 'x.ReferenceType' is invalid inside an 'Include' operation, since it does not represent a property access: 't => t.MyProperty'. To target navigations declared on derived types, use casting ('t => ((Derived)t).MyProperty') or the 'as' operator ('t => (t as Derived).MyProperty'). Collection navigation access can be filtered by composing Where, OrderBy(Descending), ThenBy(Descending), Skip or Take operations. For more information on including related data, see http://go.microsoft.com/fwlink/?LinkID=746393.'

I transferred data through the service, but received an error

{
  "documents": [
    0
  ],
  "start": "2022-01-05T13:16:31.289Z",
  "finish": "2023-01-05T13:16:31.289Z",
  "repostAlreadyPosted": true,
  "postUnposted": true,
  "interruptWhenPostFailed": true
}
```

Photo class ReferenceType

Body:
In the base document, I have a field that inherits from the BaseReferencesType class. It's virtual, why can't I do anything when I'm busy.
This field which i want get

public virtual ReferenceType ReferenceType { get; }

And my script:

var document = await _context.BaseDocuments
    .Where(x => bulkPostDto.Documents.Contains(x.ReferenceType) &&
                x.CreatedDate.Value.Date >= bulkPostDto.Start.Date &&
                x.CreatedDate.Value.Date <= bulkPostDto.Finish)
    .OrderBy(x => x.DocumentDate)
    .ToListAsync();

Now my problem looks like this@

System.InvalidOperationException: 'The expression 'x.ReferenceType' is invalid inside an 'Include' operation, since it does not represent a property access: 't => t.MyProperty'. To target navigations declared on derived types, use casting ('t => ((Derived)t).MyProperty') or the 'as' operator ('t => (t as Derived).MyProperty'). Collection navigation access can be filtered by composing Where, OrderBy(Descending), ThenBy(Descending), Skip or Take operations. For more information on including related data, see http://go.microsoft.com/fwlink/?LinkID=746393.'

I transferred data through the service, but received an error

{
  "documents": [
    0
  ],
  "start": "2022-01-05T13:16:31.289Z",
  "finish": "2023-01-05T13:16:31.289Z",
  "repostAlreadyPosted": true,
  "postUnposted": true,
  "interruptWhenPostFailed": true
}

Photo class ReferenceType


问:
Android can't parse java.sql.Timestamp
My Rest API has the following field:

```<code>@JsonProperty(access = JsonProperty.Access.READ_ONLY)
   @Column(name = "timestamp")
   @CreationTimestamp
   private Timestamp timestamp;
</code>```

When the following JSON is returned as a response from the API to Android:

```<code>{"timestamp":"2023-01-05T12:33:32.883+00:00"}
</code>```

I am parsing it like this:

```<code>x.setTimestamp(java.sql.Timestamp.valueOf(arr.getJSONObject(i).getString("timestamp")));
</code>```

While the field is of type java.sql.Timestamp on both API and Android, i am getting the following exception:

```<code>java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]
</code>```

Title: Android can't parse java.sql.Timestamp

Body:
My Rest API has the following field:

@JsonProperty(access = JsonProperty.Access.READ_ONLY)
   @Column(name = "timestamp")
   @CreationTimestamp
   private Timestamp timestamp;

When the following JSON is returned as a response from the API to Android:

{"timestamp":"2023-01-05T12:33:32.883+00:00"}

I am parsing it like this:

x.setTimestamp(java.sql.Timestamp.valueOf(arr.getJSONObject(i).getString("timestamp")));

While the field is of type java.sql.Timestamp on both API and Android, i am getting the following exception:

java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]


问:
Using Pandas to_sql With SQLAlchemy 2.0
I am currently using: Pandas version 1.5.1 & SQLAlchemy version: 1.4.46 (With Furure=True)

Since upgrading my python code to be compatible with SQLAlchemy 2.0, the df.to_sql is not committing the data to SQL. Previously, I was using auto-commit on the engine, but this is no longer available in SQLAlchemy 2.0.

```<code>df.to_sql(
    'Employees',
    engine,
    schema = 'dbo',
    if_exists = 'replace',
    chunksize = 1000,
    index = False
)
</code>```

The code is executed successfully, but there is no data being committed to the table.

So, my question is, how do you use df.to_sql and commit with SQLAlchemy 2.0?

Title: Using Pandas to_sql With SQLAlchemy 2.0

Body:
I am currently using: Pandas version 1.5.1 & SQLAlchemy version: 1.4.46 (With Furure=True)

Since upgrading my python code to be compatible with SQLAlchemy 2.0, the df.to_sql is not committing the data to SQL. Previously, I was using auto-commit on the engine, but this is no longer available in SQLAlchemy 2.0.

df.to_sql(
    'Employees',
    engine,
    schema = 'dbo',
    if_exists = 'replace',
    chunksize = 1000,
    index = False
)

The code is executed successfully, but there is no data being committed to the table.

So, my question is, how do you use df.to_sql and commit with SQLAlchemy 2.0?


问:
Registering error message from backend to frontend with Axios, but in the same time the success message occurs
coming with a short question.

I've been trying to retrieve the error from the backend by fetching the API data through Axios GET method to display on the frontend, that the email has already been registered, and it works, but the issue is the success message is also showing up. Therefore I'm looking for other solution to display the error when the error occurs, and the success when the form is submitted correctly.

For backend I'm using PHP, and for frontend I'm using ReactJS, with Axios to be able to connect the frontend to backend.

I tried with .then(successMessage) to reset with an empty string, and .catch(errorMessage) to display the error, but even after completing the form correctly, the error keeps showing up in that way. The code and the input can be seen down below.

```<code>const handleSubmitForm = (event) => {
    event.preventDefault();

    if (validationForm()) {

      const object = {
        full_name: full_name,
        email: email,
        type_of_inquiry: type_of_inquiry,
        inquiry_description: inquiry_description,
      }

        axios.post("http://localhost/bachelor_exam/api-contact.php", object)
        .then(setSuccessMessage("Your contact details has been registered, we'll get in touch as fast as you say fish! ;D"))
        .catch(setErrorMessage(""));

        axios.get("http://localhost/bachelor_exam/api-contact.php", object)
        .catch(setErrorMessage("The email has already been registered!"))

  }
}
</code>```

The input

Thank you for your time!

Body:
coming with a short question.

I've been trying to retrieve the error from the backend by fetching the API data through Axios GET method to display on the frontend, that the email has already been registered, and it works, but the issue is the success message is also showing up. Therefore I'm looking for other solution to display the error when the error occurs, and the success when the form is submitted correctly.

For backend I'm using PHP, and for frontend I'm using ReactJS, with Axios to be able to connect the frontend to backend.

I tried with .then(successMessage) to reset with an empty string, and .catch(errorMessage) to display the error, but even after completing the form correctly, the error keeps showing up in that way. The code and the input can be seen down below.

const handleSubmitForm = (event) => {
    event.preventDefault();

    if (validationForm()) {

      const object = {
        full_name: full_name,
        email: email,
        type_of_inquiry: type_of_inquiry,
        inquiry_description: inquiry_description,
      }

        axios.post("http://localhost/bachelor_exam/api-contact.php", object)
        .then(setSuccessMessage("Your contact details has been registered, we'll get in touch as fast as you say fish! ;D"))
        .catch(setErrorMessage(""));

        axios.get("http://localhost/bachelor_exam/api-contact.php", object)
        .catch(setErrorMessage("The email has already been registered!"))

  }
}

The input

Thank you for your time!


问:
I want the top navigation in a screen of bottom navigation bar in react native? I will be thankful if any one tell me that one. new in React native
How can i use the  top navigation  in a screen of bottom navigation bar in react native?
I created the tab bar navigation in and makes two tabs in it now i want to use the the top tab navigation of three tab in the 2nd tab of bottom tab navigation in react native?</p>


问:
Django Rest Framework: Delete multiple Cookies with same name but different domain?
I have an application running on different shards and each shard has a different domain. I am setting that domain as a domain for our cookies for respective environments. And the problem I am facing is that sometimes cookies from previous sessions (might be from different environments)  are present in the browser.

So When I try to perform certain actions then a cookie from the different session is used and validation failed. So now I want to delete those cookies with the same name.

What I am doing is

```<code>response.delete_cookie('profileActionId')
</code>```

But after this the cookies were something like this:

```<code>profileActionID: 'cookie_value' :: domain: 'usa.example.com/'
profileActionID: ''             :: domain:  'example.com/'
</code>```

So this doesn't delete cookies with the same name which have a different domain and I don't have a way to access that different domain from the code and also can't hardcode it as It will change according to different environments. Also I can't change the domain for cookies for different environments.

So Is there a way in Django by which we can delete all cookies with the same name irrespective of there domains or paths?

Body:
I have an application running on different shards and each shard has a different domain. I am setting that domain as a domain for our cookies for respective environments. And the problem I am facing is that sometimes cookies from previous sessions (might be from different environments)  are present in the browser.

So When I try to perform certain actions then a cookie from the different session is used and validation failed. So now I want to delete those cookies with the same name.

What I am doing is

response.delete_cookie('profileActionId')

But after this the cookies were something like this:

profileActionID: 'cookie_value' :: domain: 'usa.example.com/'
profileActionID: ''             :: domain:  'example.com/'

So this doesn't delete cookies with the same name which have a different domain and I don't have a way to access that different domain from the code and also can't hardcode it as It will change according to different environments. Also I can't change the domain for cookies for different environments.

So Is there a way in Django by which we can delete all cookies with the same name irrespective of there domains or paths?


问:
Performance of database views having complex queries
I have to implement some SQL views for a third-party report engine.

Each view has a complex query that joins multiple tables (some tables contain millions of rows)

Some view queries have subqueries

Views are not accessed by the application (Only read by the report engine)

I have the following concerns

we have some doughts this will badly impact the current application (since the complex queries in the view are running every time when accessing the view)

What would be the performance impact of executing the complex views? (memory, time, etc)

These are some other solutions we have for now.

Use new tables instead of views and update the tables using triggers and stored procedures.

Use a replicated database and create those views on that table (So, it will not affect the current system)

Can you give me comments on the above concerns and the solutions, please? New suggestions are welcome.


问:
Unknown error getting started with Prisma
I've got an odd error, I've been googling to no end and have been unable to figure this out.

I've got a prisma.schema looking like this;

```<code>// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model Account {
  id                 String  @id @default(cuid())
  userId             String
  type               String
  provider           String
  providerAccountId  String
  refresh_token      String?  @db.Text
  access_token       String?  @db.Text
  expires_at         Int?
  token_type         String?
  scope              String?
  id_token           String?  @db.Text
  session_state      String?
  user User @relation(fields: [userId], references: [id], onDelete: Cascade)
  @@unique([provider, providerAccountId])
}

model Session {
  id           String   @id @default(cuid())
  sessionToken String   @unique
  userId       String
  expires      DateTime
  user         User     @relation(fields: [userId], references: [id], onDelete: Cascade)
}

model User {
  id            String    @id @default(cuid())
  name          String?
  email         String   @unique
  emailVerified DateTime?
  image         String?
  accounts      Account[]
  sessions      Session[]
}

model VerificationToken {
  identifier String
  token      String   @unique
  expires    DateTime
  @@unique([identifier, token])
}
</code>```

and a addUser.ts file looking like this...

```<code>// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import { User, PrismaClient } from '@prisma/client';
import type { NextApiRequest, NextApiResponse } from 'next';

type Data = {
  name: string;
};

const prisma = new PrismaClient();

export default async(req: NextApiRequest, res: NextApiResponse) => {
  const createUser: User = await prisma.user.create({
    data:{
        name: `${Math.random() * 10000}`,
        email: `${Math.random() * 10000}@gmail.com`,
    }
  });
  res.json('user created succesfully');
}
</code>```

Trouble is when I run the code I get this error....

```<code>Error:
Invalid `prisma.user.create()` invocation:

{
  data: {
    name: '8096.003938770688',
    email: '8343.394432092025@gmail.com'
    ~~~~~
  }
}

Unknown arg `email` in data.email for type UserCreateInput. Did you mean `name`? Available args:
type UserCreateInput {
  name: String
}
</code>```

But if I look at the UserCreateInput type (I haven't made any changes to this file, I've used prisma generate to match my schema when I've made changes to it) I can see this....

```<code>export type UserCreateInput = {
    id?: string
    name?: string | null
    email: string
    emailVerified?: Date | string | null
    image?: string | null
    accounts?: AccountCreateNestedManyWithoutUserInput
    sessions?: SessionCreateNestedManyWithoutUserInput
  }
</code>```

If I comment out the line email: ${Math.random() * 10000}@gmail.com, and set the schema to "email  String? @unique" it works fine and creates the entry into the DB as expected, so it seems to be something with my email field but I can't figure out what.

I have been following multiple guides but none of them seem to expect this issue or have any resolutions for it.

I should point out, I am fairly new to development, and I'm not a developer by trade, so this is more of a learning thing for me :)

Appreciate your time guys

Body:
I've got an odd error, I've been googling to no end and have been unable to figure this out.

I've got a prisma.schema looking like this;

// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model Account {
  id                 String  @id @default(cuid())
  userId             String
  type               String
  provider           String
  providerAccountId  String
  refresh_token      String?  @db.Text
  access_token       String?  @db.Text
  expires_at         Int?
  token_type         String?
  scope              String?
  id_token           String?  @db.Text
  session_state      String?
  user User @relation(fields: [userId], references: [id], onDelete: Cascade)
  @@unique([provider, providerAccountId])
}

model Session {
  id           String   @id @default(cuid())
  sessionToken String   @unique
  userId       String
  expires      DateTime
  user         User     @relation(fields: [userId], references: [id], onDelete: Cascade)
}

model User {
  id            String    @id @default(cuid())
  name          String?
  email         String   @unique
  emailVerified DateTime?
  image         String?
  accounts      Account[]
  sessions      Session[]
}

model VerificationToken {
  identifier String
  token      String   @unique
  expires    DateTime
  @@unique([identifier, token])
}

and a addUser.ts file looking like this...

// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import { User, PrismaClient } from '@prisma/client';
import type { NextApiRequest, NextApiResponse } from 'next';

type Data = {
  name: string;
};

const prisma = new PrismaClient();

export default async(req: NextApiRequest, res: NextApiResponse) => {
  const createUser: User = await prisma.user.create({
    data:{
        name: `${Math.random() * 10000}`,
        email: `${Math.random() * 10000}@gmail.com`,
    }
  });
  res.json('user created succesfully');
}

Trouble is when I run the code I get this error....

Error:
Invalid `prisma.user.create()` invocation:

{
  data: {
    name: '8096.003938770688',
    email: '8343.394432092025@gmail.com'
    ~~~~~
  }
}

Unknown arg `email` in data.email for type UserCreateInput. Did you mean `name`? Available args:
type UserCreateInput {
  name: String
}

But if I look at the UserCreateInput type (I haven't made any changes to this file, I've used prisma generate to match my schema when I've made changes to it) I can see this....

export type UserCreateInput = {
    id?: string
    name?: string | null
    email: string
    emailVerified?: Date | string | null
    image?: string | null
    accounts?: AccountCreateNestedManyWithoutUserInput
    sessions?: SessionCreateNestedManyWithoutUserInput
  }

If I comment out the line email: ${Math.random() * 10000}@gmail.com, and set the schema to "email  String? @unique" it works fine and creates the entry into the DB as expected, so it seems to be something with my email field but I can't figure out what.

I have been following multiple guides but none of them seem to expect this issue or have any resolutions for it.

I should point out, I am fairly new to development, and I'm not a developer by trade, so this is more of a learning thing for me :)

Appreciate your time guys


问:
Send image label to webhook from argoCD postSync
I am running ArgoCD to handle the applications deployed to my Kubernetes cluster.

The workflow goes like this:

The developer does the work and creates a pull request.

The PR is merged, and the pipeline runs, ending in an updated image pushed to our container registry.

A separate process then updates the K8s manifest that is tracked in a separate repo. This is done by changing the file and pushing it to the git repo. This commit has a commit_sha.

ArgoCD sees this update in the manifest repo and pulls the new image version from the container registry.

ArgoCD has events about this, but it only has the commit SHA from the manifest update, not the commit SHA from the developer's work.

I want to make a call to a webhook to a tool we are using to track the deployment of the changes the developers have made. For this, I need the commit SHA from the developer's PR.

What I have done to pass that SHA along is added it as a label to the docker image in the build step in the pipeline. This image has a tag that is the version number and the label commit_sha, which is the PR commit SHA from the developer work.

My question is, how do I access the commit_sha label of the image in the ArgoCD postSync hook to call the webhook with the details of the PR?

I am looking at the example for the basic idea, but I am unsure how to inspect the image and get the label value to use. I know I can do something like docker inspect --format '{{ index .Config.Labels "commit_sha"}}' <myimagereg/image:v1> to return just the value, but how can I use this in ArgoCD?


问:
How to save Terminal Output to image file with convert imagemagick
I wanted to save Terminal output to an image file so i googles alot but i didn't find alot then found some blogs that says you can save output in image using convert command provided by ImageMagick
so I tried the command

I tried the command

ip a | convert label:@- ip.png

but the image always created with"@"
see the below image for issue
Imagemagisk-Output

Then I tried to run script as well
but same issue

command: convert label:test.sh- ip3.png
Script-output


问:
How to upload a .net build project jenkins server to another server or prod server?
i am create a windows jenkins server and build a dotnet project. Its done successfully.But when i try to send build file jenkins server to another production server via ftp or ssh its shown file FTP: Transferred 0 file(s)
Finished: SUCCESS.

I need a help.How to build file sent a server to another server.


问:
How to use Logical Operators in Comparison?
I cant figure out how to use the logical OR in a comparison in Powershell.
My code looks kinda like this:

```<code>Get-Childitem -Path G:\Path\Blabla -Include *.sql* -File -Recurse -ErrorAction SilentlyContinue | Where {$_.Name -cmatch 'somefile1.sql' -or -cmatch 'somefile2.sql'}
</code>```

However, this code does not work
-> The goal is to find those files in a folder

Body:
I cant figure out how to use the logical OR in a comparison in Powershell.
My code looks kinda like this:

Get-Childitem -Path G:\Path\Blabla -Include *.sql* -File -Recurse -ErrorAction SilentlyContinue | Where {$_.Name -cmatch 'somefile1.sql' -or -cmatch 'somefile2.sql'}

However, this code does not work
-> The goal is to find those files in a folder


问:
incorrect username and password error in web application made in Django
for my web-application which is made in Django and I made a custom users app for users (so I am not using the Django's user). I managed to get the users app working and I created a superuser using this command:

```<code>python manage.py createsuperuser
</code>```

and got this message:

```<code>Superuser created successfully.
</code>```

but when I tried to log in as the superuser in the browser, it did not work and got this error message on the browser (I tried different browsers as well):

```<code> Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive.
</code>```

I paid attention to case-sensitive letters. do you know what the problem could be?
here is the models.py for the users app:

```<code>import random

from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.core import validators
from django.utils import timezone
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager, send_mail

class UserManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, username, password, phone_number, email, is_staff, is_superuser, **extra_fields):
        """
        Created and saves a User with the given username, email and password.
        """
        now = timezone.now()
        if not username:
            raise ValueError('The given username must be set')
        email = self.normalize_email(email)
        user = self.model(phone_number=phone_number,
                          username=username, email=email,
                          is_staff=is_staff, is_active=True,
                          is_superuser=is_superuser,
                          date_joined=now, **extra_fields)

        if not extra_fields.get('no_password'):
            user.set_password(password)

        user.save(using=self._db)
        return user

    def create_user(self, username=None, phone_number=None, email=None, password=None, **extra_fields):
        if username is None:
            if email:
                username = email.split('@', 1)[0]
            if phone_number:
                username = random.choice('abcdefghijklmnopqrstuvwxyz') + str(phone_number)[-7:]
            while User.objects.filter(username=username).exists():
                username += str(random.randint(10, 99))

        return self._create_user(username, phone_number, email, password, False, False, **extra_fields)

    def create_superuser(self, username, email, phone_number, password, **extra_fields):
        return self._create_user(username, email, phone_number, password, True, True, **extra_fields)

    def get_by_phone_number(self, phone_number):
        return self.get(**{'phone_number': phone_number})

class User(AbstractBaseUser, PermissionsMixin):
    username = models.CharField(_('username'), max_length=32, unique=True,
                                help_text=
                                    'Required. 30 characters or fewer starting with a letter. Letters, digits',
                                validators=[
                                    validators.RegexValidator(r'^[a-zA-Z][a-zA-Z0-9_\.]+$',
                                                              _('Enter a valid username starting with a-z.'
                                                                'This value may contain only letters and numbers'
                                                                'and underscore characters.'), 'invalid')
                                ],
                                error_messages={
                                    'unique':_('A user with that username already exists.'),
                                }
                                )
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    email = models.EmailField(_('email address'), unique=False, null=True, blank=True)
    phone_number = models.BigIntegerField(_('phone number'), unique=True, null=True, blank=True,
                                          validators=[
                                              validators.RegexValidator(r'^319[0-3,9]\d{8}$',
                                                                        ('Enter a valid mobile number.'), 'egrwfk')

                                          ],
                                          error_messages={
                                              'unique': _('A user with this mobile phone number already exits')
                                          }
                                          )
    is_staff = models.BooleanField(_('staff status'), default=False,
                                   help_text='designates whether this user can log into this admin site.')

    is_active = models.BooleanField(_('active'), default=True,
                                    help_text=_('designates whether this user should be treated as active'))

    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
    last_seen = models.DateTimeField(_('last seen date'), null=True)

    objects = UserManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email', 'phone_number']

    class Meta:
        db_table = 'users'
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def get_full_name(self):

        full_name = '%s %s' % (self.first_name, self.last_name)

        return full_name.strip()

    def get_short_name(self):

        return self.first_name

    def email_user(self, subject, message, from_email=None, **kwargs):

        send_mail(subject, message, from_email, [self.email], **kwargs)

    @property
    def is_loggedin_user(self):

        return self.phone_number is not None or self.email is not None

    def save(self, *args, **kwargs):
        if self.email is not None and self.email.strip() == '':
            self.email = None
        super().save(*args, **kwargs)

class UserProfile(models.Model):

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    nick_name = models.CharField(_('nick_name'), max_length=150, blank=True)
    avatar = models.ImageField(_('avatar'), blank=True)
    birthday = models.DateField(_('birthday'), null=True, blank=True)
    gender = models.BooleanField(_('gender'), null=True, help_text='femal is False, male is True, null is unset')
    province = models.ForeignKey(verbose_name=_('province'), to='Province', null=True, on_delete=models.SET_NULL)
    # email = models.EmailField(_('email_address'), blank=True)
    # phone_number = models.BigIntegerField(_('phone_number'), null=True, blank=True,
    #                                       validators=[
    #                                           validators=RegexValidators(r'^319[0-3,9]\d(8)$,
    #                                                                                _('Enter a valid mobile number'), 'invalid'),
    #                                           ],
    #                                           )
    class Meta:
        db_table = 'user_profiles'
        verbose_name = _('profile')
        verbose_name_plural = _('profiles')

    @property
    def get_first_name(self):
        return self.user.first_name

    @property
    def get_last_name(self):
        return self.user.last_name

    def get_nick_name(self):
        return self.nick_name if self.nick_name else self.user.username

class  Device(models.Model):
    WEB = 1
    IOS = 2
    ANDROID = 3
    DEVICE_TYPE_CHOICES = (
        (WEB, 'web'),
        (IOS, 'ios'),
        (ANDROID, 'android')
    )

    user = models.ForeignKey(User, related_name='devices', on_delete=models.CASCADE)
    device_uuid = models.UUIDField(_('Device UUID'), null=True)
    # notify_token = models.CharField(_('notification token'), max_length=200, blank=True,
    #                                 validators=[validators.RegexValidator(r'([a-z]|[A-z]|[0-9])\w+',
    #                                                                       _('Notify token is not valid'), 'invalid')]
    #                                 )
    last_login = models.DateTimeField(choices=DEVICE_TYPE_CHOICES, default=ANDROID)
    device_type = models.PositiveSmallIntegerField(choices=DEVICE_TYPE_CHOICES, default=ANDROID)
    device_os = models.CharField(_('device os'), max_length=20, blank=True)
    device_model = models.CharField(_('device model'), max_length=50, blank=True)
    app_version = models.CharField(_('app version'), max_length=20, blank=True)
    created_time = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'user_devices'
        verbose_name = _('device')
        verbose_name_plural = _('devices')
        unique_together = ('user', 'device_uuid',)

class Province(models.Model):
    name = models.CharField(max_length=50)
    is_valid = models.BooleanField(default=True)
    modified_at = models.DateTimeField(auto_now=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name
</code>```

I am also getting this message on the terminal:

```<code>[05/Jan/2023 13:38:44] "POST /admin/login/?next=/admin/ HTTP/1.1" 200 2374
</code>```

Body:
for my web-application which is made in Django and I made a custom users app for users (so I am not using the Django's user). I managed to get the users app working and I created a superuser using this command:

python manage.py createsuperuser

and got this message:

Superuser created successfully.

but when I tried to log in as the superuser in the browser, it did not work and got this error message on the browser (I tried different browsers as well):

 Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive.

I paid attention to case-sensitive letters. do you know what the problem could be?
here is the models.py for the users app:

import random

from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.core import validators
from django.utils import timezone
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager, send_mail

class UserManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, username, password, phone_number, email, is_staff, is_superuser, **extra_fields):
        """
        Created and saves a User with the given username, email and password.
        """
        now = timezone.now()
        if not username:
            raise ValueError('The given username must be set')
        email = self.normalize_email(email)
        user = self.model(phone_number=phone_number,
                          username=username, email=email,
                          is_staff=is_staff, is_active=True,
                          is_superuser=is_superuser,
                          date_joined=now, **extra_fields)

        if not extra_fields.get('no_password'):
            user.set_password(password)

        user.save(using=self._db)
        return user

    def create_user(self, username=None, phone_number=None, email=None, password=None, **extra_fields):
        if username is None:
            if email:
                username = email.split('@', 1)[0]
            if phone_number:
                username = random.choice('abcdefghijklmnopqrstuvwxyz') + str(phone_number)[-7:]
            while User.objects.filter(username=username).exists():
                username += str(random.randint(10, 99))

        return self._create_user(username, phone_number, email, password, False, False, **extra_fields)

    def create_superuser(self, username, email, phone_number, password, **extra_fields):
        return self._create_user(username, email, phone_number, password, True, True, **extra_fields)

    def get_by_phone_number(self, phone_number):
        return self.get(**{'phone_number': phone_number})

class User(AbstractBaseUser, PermissionsMixin):
    username = models.CharField(_('username'), max_length=32, unique=True,
                                help_text=
                                    'Required. 30 characters or fewer starting with a letter. Letters, digits',
                                validators=[
                                    validators.RegexValidator(r'^[a-zA-Z][a-zA-Z0-9_\.]+$',
                                                              _('Enter a valid username starting with a-z.'
                                                                'This value may contain only letters and numbers'
                                                                'and underscore characters.'), 'invalid')
                                ],
                                error_messages={
                                    'unique':_('A user with that username already exists.'),
                                }
                                )
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    email = models.EmailField(_('email address'), unique=False, null=True, blank=True)
    phone_number = models.BigIntegerField(_('phone number'), unique=True, null=True, blank=True,
                                          validators=[
                                              validators.RegexValidator(r'^319[0-3,9]\d{8}$',
                                                                        ('Enter a valid mobile number.'), 'egrwfk')

                                          ],
                                          error_messages={
                                              'unique': _('A user with this mobile phone number already exits')
                                          }
                                          )
    is_staff = models.BooleanField(_('staff status'), default=False,
                                   help_text='designates whether this user can log into this admin site.')

    is_active = models.BooleanField(_('active'), default=True,
                                    help_text=_('designates whether this user should be treated as active'))

    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
    last_seen = models.DateTimeField(_('last seen date'), null=True)

    objects = UserManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email', 'phone_number']

    class Meta:
        db_table = 'users'
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def get_full_name(self):

        full_name = '%s %s' % (self.first_name, self.last_name)

        return full_name.strip()

    def get_short_name(self):

        return self.first_name

    def email_user(self, subject, message, from_email=None, **kwargs):

        send_mail(subject, message, from_email, [self.email], **kwargs)

    @property
    def is_loggedin_user(self):

        return self.phone_number is not None or self.email is not None

    def save(self, *args, **kwargs):
        if self.email is not None and self.email.strip() == '':
            self.email = None
        super().save(*args, **kwargs)

class UserProfile(models.Model):

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    nick_name = models.CharField(_('nick_name'), max_length=150, blank=True)
    avatar = models.ImageField(_('avatar'), blank=True)
    birthday = models.DateField(_('birthday'), null=True, blank=True)
    gender = models.BooleanField(_('gender'), null=True, help_text='femal is False, male is True, null is unset')
    province = models.ForeignKey(verbose_name=_('province'), to='Province', null=True, on_delete=models.SET_NULL)
    # email = models.EmailField(_('email_address'), blank=True)
    # phone_number = models.BigIntegerField(_('phone_number'), null=True, blank=True,
    #                                       validators=[
    #                                           validators=RegexValidators(r'^319[0-3,9]\d(8)$,
    #                                                                                _('Enter a valid mobile number'), 'invalid'),
    #                                           ],
    #                                           )
    class Meta:
        db_table = 'user_profiles'
        verbose_name = _('profile')
        verbose_name_plural = _('profiles')

    @property
    def get_first_name(self):
        return self.user.first_name

    @property
    def get_last_name(self):
        return self.user.last_name

    def get_nick_name(self):
        return self.nick_name if self.nick_name else self.user.username

class  Device(models.Model):
    WEB = 1
    IOS = 2
    ANDROID = 3
    DEVICE_TYPE_CHOICES = (
        (WEB, 'web'),
        (IOS, 'ios'),
        (ANDROID, 'android')
    )

    user = models.ForeignKey(User, related_name='devices', on_delete=models.CASCADE)
    device_uuid = models.UUIDField(_('Device UUID'), null=True)
    # notify_token = models.CharField(_('notification token'), max_length=200, blank=True,
    #                                 validators=[validators.RegexValidator(r'([a-z]|[A-z]|[0-9])\w+',
    #                                                                       _('Notify token is not valid'), 'invalid')]
    #                                 )
    last_login = models.DateTimeField(choices=DEVICE_TYPE_CHOICES, default=ANDROID)
    device_type = models.PositiveSmallIntegerField(choices=DEVICE_TYPE_CHOICES, default=ANDROID)
    device_os = models.CharField(_('device os'), max_length=20, blank=True)
    device_model = models.CharField(_('device model'), max_length=50, blank=True)
    app_version = models.CharField(_('app version'), max_length=20, blank=True)
    created_time = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'user_devices'
        verbose_name = _('device')
        verbose_name_plural = _('devices')
        unique_together = ('user', 'device_uuid',)

class Province(models.Model):
    name = models.CharField(max_length=50)
    is_valid = models.BooleanField(default=True)
    modified_at = models.DateTimeField(auto_now=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

I am also getting this message on the terminal:

[05/Jan/2023 13:38:44] "POST /admin/login/?next=/admin/ HTTP/1.1" 200 2374


问:
ReportViewer 15.0.0.0 vertical scroll on opening a sub record
We have an MVC web application, and recently we migrated from Microsoft ReportViewer from 11.0.0.0 to 15.0.0.0 version.

We started having different issues in terms of UI, one of which is mentioned as below.

When we run the report from SSRS (SQL Server 2016), and click on the plus icon used to open the sub record (inner record), the vertical scroll bar maintains position and we can see the data clearly, as shown in below image

However, when the same report is run from MVC web application, using ReportViewer control, when we click on the plus button the scrollbar  scrolls to the expanded icon and it does not gives good look and feel to end user. Sometimes the scroll even hide half of the current record. E.g. below is the screenshot when we run report from MVC web application using ReportViewer control. 1st image shows before clicking on the plus icon, and 2nd image shows after clicking on the plus icon.

Image-1

Image-2

Has anyone come across such situation? How can I avoid such scrolling on opening a sub record ?

Following is code I have used in .aspx file of which uses ReportViewer control


问:
Cloud point shader with assigned colors map from model
I'm working on a project using threejs to make a 3D environment to navigate in space.I integrated my environment as GLTF object and instanced a sphere on its surface of it.Now I would use the texture to assign colors to each instance. I think using a shader would be the most performant method!
Does someone have a clue on how to make it?

here is an image of the concept i would recreate
enter image description here

here is the basic point were I'm stuck

```<code>// create the model that the points will be placed on
const model = new THREE.Mesh(
    new THREE.BoxGeometry(1, 1, 1),
    new THREE.MeshBasicMaterial({
        color: 0x00ff00
    })
);
scene.add(model);

// create the instanced geometry to hold the points

const geometry = new THREE.InstancedBufferGeometry();

// set the attributes for the points (such as position, color, etc.)
const positions = [];
const colors = [];
const modelViewMatrices = [];
const projectionMatrices = [];
for (let i = 0; i < 100; i++) {
    positions.push(Math.random() * 2 - 1, Math.random() * 2 - 1, Math.random() * 2 - 1);
    colors.push(Math.random(), Math.random(), Math.random());
    modelViewMatrices.push(camera.matrixWorldInverse.elements);
    projectionMatrices.push(camera.projectionMatrix.elements);
}
const positionAttribute = new THREE.Float32BufferAttribute(positions, 3);
geometry.setAttribute('position', positionAttribute);
const colorAttribute = new THREE.Float32BufferAttribute(colors, 3);
geometry.setAttribute('color', colorAttribute);
const modelViewMatrixAttribute = new THREE.InstancedBufferAttribute(new Float32Array(modelViewMatrices.flat()), 4);
geometry.setAttribute('modelViewMatrix', modelViewMatrixAttribute);
const projectionMatrixAttribute = new THREE.InstancedBufferAttribute(new Float32Array(projectionMatrices.flat()), 4);
geometry.setAttribute('projectionMatrix', projectionMatrixAttribute);

// create the material for the points,using the modelViewMatrix and projectionMatrix attributes in the shader
const material = new THREE.ShaderMaterial({
    uniforms: {},
    attributes: {
        modelViewMatrix: { value: null },
        projectionMatrix: { value: null }
    },
    vertexShader: `
        attribute vec3 pointPosition;
        attribute vec3 color;
        attribute mat4 modelViewMatrix;
        attribute mat4 projectionMatrix;
        varying vec3 vColor;
        void main() {
            vColor = color;
            gl_Position = projectionMatrix * modelViewMatrix * vec4(pointPosition, 1.0);
        }
    `,
    fragmentShader: `
        varying vec3 vColor;
        void main() {
            gl_FragColor = vec4(vColor, 1.0);
        }
    `
});

// create the mesh to hold the points and add it to the scene
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);

// set the number of instances (points) to render
geometry.setDrawRange(positions.length / 3);

// animate the scene
const animate = function () {
    requestAnimationFrame(animate);

    // update the modelViewMatrix and projectionMatrix uniforms
    material.uniforms.modelViewMatrix.value = camera.matrixWorldInverse;
    material.uniforms.projectionMatrix.value = camera.projectionMatrix;

    renderer.render(scene, camera);
};
animate();
</code>```

Body:
I'm working on a project using threejs to make a 3D environment to navigate in space.I integrated my environment as GLTF object and instanced a sphere on its surface of it.Now I would use the texture to assign colors to each instance. I think using a shader would be the most performant method!
Does someone have a clue on how to make it?

here is an image of the concept i would recreate
enter image description here

here is the basic point were I'm stuck

// create the model that the points will be placed on
const model = new THREE.Mesh(
    new THREE.BoxGeometry(1, 1, 1),
    new THREE.MeshBasicMaterial({
        color: 0x00ff00
    })
);
scene.add(model);

// create the instanced geometry to hold the points

const geometry = new THREE.InstancedBufferGeometry();

// set the attributes for the points (such as position, color, etc.)
const positions = [];
const colors = [];
const modelViewMatrices = [];
const projectionMatrices = [];
for (let i = 0; i < 100; i++) {
    positions.push(Math.random() * 2 - 1, Math.random() * 2 - 1, Math.random() * 2 - 1);
    colors.push(Math.random(), Math.random(), Math.random());
    modelViewMatrices.push(camera.matrixWorldInverse.elements);
    projectionMatrices.push(camera.projectionMatrix.elements);
}
const positionAttribute = new THREE.Float32BufferAttribute(positions, 3);
geometry.setAttribute('position', positionAttribute);
const colorAttribute = new THREE.Float32BufferAttribute(colors, 3);
geometry.setAttribute('color', colorAttribute);
const modelViewMatrixAttribute = new THREE.InstancedBufferAttribute(new Float32Array(modelViewMatrices.flat()), 4);
geometry.setAttribute('modelViewMatrix', modelViewMatrixAttribute);
const projectionMatrixAttribute = new THREE.InstancedBufferAttribute(new Float32Array(projectionMatrices.flat()), 4);
geometry.setAttribute('projectionMatrix', projectionMatrixAttribute);

// create the material for the points,using the modelViewMatrix and projectionMatrix attributes in the shader
const material = new THREE.ShaderMaterial({
    uniforms: {},
    attributes: {
        modelViewMatrix: { value: null },
        projectionMatrix: { value: null }
    },
    vertexShader: `
        attribute vec3 pointPosition;
        attribute vec3 color;
        attribute mat4 modelViewMatrix;
        attribute mat4 projectionMatrix;
        varying vec3 vColor;
        void main() {
            vColor = color;
            gl_Position = projectionMatrix * modelViewMatrix * vec4(pointPosition, 1.0);
        }
    `,
    fragmentShader: `
        varying vec3 vColor;
        void main() {
            gl_FragColor = vec4(vColor, 1.0);
        }
    `
});

// create the mesh to hold the points and add it to the scene
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);

// set the number of instances (points) to render
geometry.setDrawRange(positions.length / 3);

// animate the scene
const animate = function () {
    requestAnimationFrame(animate);

    // update the modelViewMatrix and projectionMatrix uniforms
    material.uniforms.modelViewMatrix.value = camera.matrixWorldInverse;
    material.uniforms.projectionMatrix.value = camera.projectionMatrix;

    renderer.render(scene, camera);
};
animate();


问:
Catching an exception during a transaction and saving the error to DB, but modified entities in try block also getting saved
Below is the code I have implemented:

```<code>@Transactional
MethodA{
  try{
     fetch from DB, update entities and save them;
     some exception occurs;
  } catch(Exception e){
     update Exception to DB;
  }
}
</code>```

The updates I do to the entities in the try block are also saved to DB. How to circumvent this?

Body:
Below is the code I have implemented:

@Transactional
MethodA{
  try{
     fetch from DB, update entities and save them;
     some exception occurs;
  } catch(Exception e){
     update Exception to DB;
  }
}

The updates I do to the entities in the try block are also saved to DB. How to circumvent this?


问:
Visual Studio 2022 "Value cannot be null. Parameter name: obj"
I am getting an error when opening C# .NET 4.x project as a website in Visual Studio 2022 Version 17.4.3.

"Value cannot be null. Parameter name: obj"

I was able to open it as a website without the error before the latest update for Visual Studio.

When I click OK, it takes me back to the list of websites from IIS. Even though I get the error, the code still loads, and I can edit it if I close the error.

There are a few other stack overflow questions with similar topics, but none for this version of visual studio that relate to opening a project as a website.


问:
How to add a line break in WooCommerce product titles on static pages
Here is a little follow-up to this thread.

So in order to add a line break in Woocommerce Product Titles, I have added this code to the functions.php:

```<code>//ADD LINE BREAK  add_filter( 'the_title', 'custom_the_title', 10, 2 ); function custom_the_title( $title, $post_id ) {
    $post_type = get_post_field( 'post_type', $post_id, true ); if( $post_type == 'product' || $post_type == 'product_variation' )
        $title = str_replace( '|', '<br/>', $title ); // we replace '|' by '<br>' return $title; }
</code>```

...which works amazing on Product Category pages.
However for some reason it does not when one of the product lists is imported as a widget on a static page (the Front Page of my shop).
What could be the problem?

Body:
Here is a little follow-up to this thread.

So in order to add a line break in Woocommerce Product Titles, I have added this code to the functions.php:

//ADD LINE BREAK  add_filter( 'the_title', 'custom_the_title', 10, 2 ); function custom_the_title( $title, $post_id ) {
    $post_type = get_post_field( 'post_type', $post_id, true ); if( $post_type == 'product' || $post_type == 'product_variation' )
        $title = str_replace( '|', '
', $title ); // we replace '|' by '
' return $title; }

...which works amazing on Product Category pages.
However for some reason it does not when one of the product lists is imported as a widget on a static page (the Front Page of my shop).
What could be the problem?