问:
Is it possible to rollback DELETE, DROP and TRUNCATE?
We can rollback a delete query but not so for truncate and drop. When I execute queries then successfully done with rollback in delete, drop & truncate.

We can rollback the data in conditions of Delete, Truncate & Drop.
But must be used Begin Transaction before executing query Delete, Drop & Truncate.

Here is example:

```<code>Create Database Ankit

Create Table Tbl_Ankit(Name varchar(11))

insert into tbl_ankit(name) values('ankit');
insert into tbl_ankit(name) values('ankur');
insert into tbl_ankit(name) values('arti');

Select * From Tbl_Ankit

/*======================For Delete==================*/
Begin Transaction
Delete From Tbl_Ankit where Name='ankit'

Rollback
Select * From Tbl_Ankit

/*======================For Truncate==================*/
Begin Transaction
Truncate Table Tbl_Ankit

Rollback
Select * From Tbl_Ankit

/*======================For Drop==================*/
Begin Transaction
Drop Table Tbl_Ankit

Rollback
Select * From Tbl_Ankit
</code>```

答:
DELETE(DML)-------------------
Used to delete the tuples(row) of the table and have facility to DELETE ONE OR
MULTIPLE ROW USING WHERE CLAUSE
delete EX ->
 delete from emp ;
it will delete all the row of table
 delete from emp where id = 2;
it will delete one row
----------------------Drop(DDL)-------------------
This command will delete the whole structure of table with data so that's why it
is very important or crucial command and the access is to this command is only
to database administrator (DBA)
dropEX -> DROP EMP1;
it will vanish whole table with structure
-------------------TRUNCATE(DDL)----------------
Used to delete all rows (tuple) of the table.
truncate EX -> TRUNCATE EMP1;
----------------------QUESTIONS-------------------
QUES 1: IF WE CAN DELETE ALL ROWS FROM BOTH 'DELETE' COMMAND AND
'TRUNCATE' COMMAND THEN WHAT IS THE DIFFERENCE
DELETE AND TRUNCATE DIFFERENCE

DELETE command is DML command and TRUNCATE is DDL

TRUNCTE command will delete all rows because we can not use where clause
with truncate but WHERE clause can be applied to DELETE command and can
delete one or more rows through where condition
QUES 2: WHY TRUNCATE IS DDL ALTHOUGH IT IS WORKING ON DATA AND
DELETE IS DML IT IS ALSO WORKING ON DATA?
ANSWER:
 When TRUNCATE Command deletes all the row then we can never ROLLBACK
our deleted data because in truncate COMMIT is called implicitly
 But in the case of delete the log(backend file) is created from where you can get
your data ROLLBACK if deleted by mistake
 REMEMBER: In DELETE case ROLLBACK can be done only before the COMMIT

Body:
We can rollback a delete query but not so for truncate and drop. When I execute queries then successfully done with rollback in delete, drop & truncate.

We can rollback the data in conditions of Delete, Truncate & Drop.
But must be used Begin Transaction before executing query Delete, Drop & Truncate.

Here is example:

Create Database Ankit

Create Table Tbl_Ankit(Name varchar(11))

insert into tbl_ankit(name) values('ankit');
insert into tbl_ankit(name) values('ankur');
insert into tbl_ankit(name) values('arti');

Select * From Tbl_Ankit

/*======================For Delete==================*/
Begin Transaction
Delete From Tbl_Ankit where Name='ankit'

Rollback
Select * From Tbl_Ankit

/*======================For Truncate==================*/
Begin Transaction
Truncate Table Tbl_Ankit

Rollback
Select * From Tbl_Ankit

/*======================For Drop==================*/
Begin Transaction
Drop Table Tbl_Ankit

Rollback
Select * From Tbl_Ankit


来源: stackexchange

问:
Islamic Date (Hijiri)
Does anybody know of a way to display the current date using the Islamic (Hajiri) date? Preferrably in PHP and/or Javascript.

Specifically in this format? "10 Safar, 1442"

I have been looking and looking and looking. I can find others using it, and when I search for "display Hajiri date", I get a bunch of sites about Muslim dating... not what I'm looking for, obviously.

I don't need anything special, just the date according to the location of the visitor to a site.

答:
Here is one way to display the Hijri Date in the format requested given a Gregorian Date.

function myHijriDateFormat(date) {
let startDate= new Date(date),
    c= 'en-u-ca-islamic-umalqura-nu-latn',  // use 'islamic-umalqura' calendar for the islamic date
    n='numeric',
    iDay  =new Intl.DateTimeFormat(c,{day  :n}).format(startDate),
    iMonth=new Intl.DateTimeFormat(c,{month:'long'}).format(startDate),
    iYear =new Intl.DateTimeFormat(c,{year :n}).format(startDate).split(" ")[0];

    return iDay+" "+iMonth+", "+iYear;
}
    console.log(myHijriDateFormat(new Date(Date.now()))); // today's date
    console.log(myHijriDateFormat("2022-04-02"));         // first Ramadan 2022```

ContentLicense: CC BY-SA 4.0

Title: Islamic Date (Hijiri)


问:
How do i turn this string into 2 arrays in python?
I have this string and want to turn it into two arrays, one has the film title and the other one has the year. Their positions in the array need to correspond with each other. Is there a way to do this?</p>
```<code>films = ("""Endless Love (1981), Top Gun (1986), The Color of Money (1986), Rain Man (1988),
Born on the Fourth of July (1989), Interview with the Vampire: The Vampire Chronicles (1994),
Mission: Impossible (1996), Jerry Maguire (1996), The Matrix (1999), Mission: Impossible II (2000),
Vanilla Sky (2001), Cocktail (1988), A Few Good Men (1992), The Firm (1993), Eyes Wide Shut (1999),
Magnolia (1999), Minority Report (2002), Austin Powers in Goldmember (2002), Days of Thunder (1990),
The Powers of Matthew Star (1982), Cold Mountain (2003), The Talented Mr. Ripley (1999),
 War of the Worlds (2005), The Oprah Winfrey Show (1986), Far and Away (1992), Taps (1981),
 The Last Samurai (2003), Valkyrie (2008), Jack Reacher (2012), Edge of Tomorrow (2014),
 Enemy of the State (1998), Mission: Impossible III (2006), Crimson Tide (1995), Reign Over Me (2007),
 Batman Forever (1995), Batman Begins (2005), The Simpsons (1989), The Simpsons: Brother from the Same Planet (1993),
 The Simpsons: When You Dish Upon a Star (1998), End of Days (1999), House of D (2004), The Indian Runner (1991),
  Harry & Son (1984), Mission: Impossible - Ghost Protocol (2011), Aladdin (1992), Pacific Rim (2013),
  Oblivion (2013), Knight and Day (2010),
""")
</code>```

答:
First split the input string on comma to generate a list, then use comprehensions to get the title and year as separate lists.

films_list = re.split(r',\s*', films)
titles = [re.split(r'\s*(?=\(\d+\))', x)[0] for x in films_list]
years = [re.split(r'\s*(?=\(\d+\))', x)[1] for x in films_list]
```

Body:
I have this string and want to turn it into two arrays, one has the film title and the other one has the year. Their positions in the array need to correspond with each other. Is there a way to do this?

films = ("""Endless Love (1981), Top Gun (1986), The Color of Money (1986), Rain Man (1988),
Born on the Fourth of July (1989), Interview with the Vampire: The Vampire Chronicles (1994),
Mission: Impossible (1996), Jerry Maguire (1996), The Matrix (1999), Mission: Impossible II (2000),
Vanilla Sky (2001), Cocktail (1988), A Few Good Men (1992), The Firm (1993), Eyes Wide Shut (1999),
Magnolia (1999), Minority Report (2002), Austin Powers in Goldmember (2002), Days of Thunder (1990),
The Powers of Matthew Star (1982), Cold Mountain (2003), The Talented Mr. Ripley (1999),
 War of the Worlds (2005), The Oprah Winfrey Show (1986), Far and Away (1992), Taps (1981),
 The Last Samurai (2003), Valkyrie (2008), Jack Reacher (2012), Edge of Tomorrow (2014),
 Enemy of the State (1998), Mission: Impossible III (2006), Crimson Tide (1995), Reign Over Me (2007),
 Batman Forever (1995), Batman Begins (2005), The Simpsons (1989), The Simpsons: Brother from the Same Planet (1993),
 The Simpsons: When You Dish Upon a Star (1998), End of Days (1999), House of D (2004), The Indian Runner (1991),
  Harry & Son (1984), Mission: Impossible - Ghost Protocol (2011), Aladdin (1992), Pacific Rim (2013),
  Oblivion (2013), Knight and Day (2010),
""")


问:
Should I use %$% instead of %>%?
Recently I have found the %$% pipe operator, but I am missing the point regarding its difference with %>% and if it could completely replace it.

Motivation to use %$%

The operator %$% could replace %>% in many cases:

```<code>mtcars %>% summary()
mtcars %$% summary(.)
mtcars %>% head(10)
mtcars %$% head(.,10)
</code>```

Apparently, %$% is more usable than %>%:

```<code>mtcars %>% plot(.$hp, .$mpg) # Does not work
mtcars %$% plot(hp, mpg)     # Works
</code>```

Implicitly fills the built-in data argument:

```<code>mtcars %>% lm(mpg ~ hp, data = .)
mtcars %$% lm(mpg ~ hp)
</code>```

Since % and $ are next to each other in the keyboard, inserting %$% is more convenient than inserting %>%.

Documentation

We find the following information in their respective help pages.

(?magrittr::`%>%`):

```<code>Description:

     Pipe an object forward into a function or call expression.

Usage:

     lhs %>% rhs
</code>```

(?magrittr::`%$%`):

```<code>Description:

     Expose the names in ‘lhs’ to the ‘rhs’ expression. This is useful
     when functions do not have a built-in data argument.

Usage:

     lhs %$% rhs
</code>```

I was not able to understand the difference between the two pipe operators. Which is the difference between piping an object and exposing a name? But, in the rhs of %$%, we are able to get the piped object with the ., right?

Should I start using %$% instead of %>%? Which problems could I face doing so?

答:
In addition to the provided comments:

%$% also called the Exposition pipe vs. %>%:

This is  a short summary of this article https://towardsdatascience.com/3-lesser-known-pipe-operators-in-tidyverse-111d3411803a

"The key difference in using %$% or %>% lies in the type of arguments of used functions."

One advantage, and as far as I can understand it, for me the only one to use %$% over %>% is the fact that
we can avoid repetitive input of the dataframe name in functions that have no data as an argument.

For example the lm() has a data argument. In this case we can use both %>% and %$% interchangeable.

But in functions like the cor() which has no data argument:

```<code>mtcars %>% cor(disp, mpg) # Will give an Error
</code>```
```<code>cor(mtcars$disp, mtcars$mpg)
</code>```

is equivalent to

```<code>mtcars %$% cor(disp, mpg)
</code>```

And note to use %$% pipe operator you have to load library(magrittr)

Update: on OPs comment:
The pipe independent which one allows us to transform machine or computer language to a more readable human language.

ggplot2 is special. ggplot2 is not internally consistent.
ggplot1 had a tidier API then ggplot2

Pipes would work with ggplot1:
library(ggplot1) mtcars %>%  ggplot(list( x= mpg, y = wt)) %>%  ggpoint() %>%  ggsave("mtcars.pdf", width= 8 height = 6)

In 2016 Wick Hadley said:
"ggplot2 newver would have existed if I'd discovered the pipe 10 years earlier!"
https://www.youtube.com/watch?v=K-ss_ag2k9E&list=LL&index=9

Title: Should I use %$% instead of %>%?

Body:
Recently I have found the %$% pipe operator, but I am missing the point regarding its difference with %>% and if it could completely replace it.

Motivation to use %$%

The operator %$% could replace %>% in many cases:

mtcars %>% summary()
mtcars %$% summary(.)
mtcars %>% head(10)
mtcars %$% head(.,10)

Apparently, %$% is more usable than %>%:

mtcars %>% plot(.$hp, .$mpg) # Does not work
mtcars %$% plot(hp, mpg)     # Works

Implicitly fills the built-in data argument:

mtcars %>% lm(mpg ~ hp, data = .)
mtcars %$% lm(mpg ~ hp)

Since % and $ are next to each other in the keyboard, inserting %$% is more convenient than inserting %>%.

Documentation

We find the following information in their respective help pages.

(?magrittr::`%>%`):

Description:

     Pipe an object forward into a function or call expression.

Usage:

     lhs %>% rhs

(?magrittr::`%$%`):

Description:

     Expose the names in ‘lhs’ to the ‘rhs’ expression. This is useful
     when functions do not have a built-in data argument.

Usage:

     lhs %$% rhs

I was not able to understand the difference between the two pipe operators. Which is the difference between piping an object and exposing a name? But, in the rhs of %$%, we are able to get the piped object with the ., right?

Should I start using %$% instead of %>%? Which problems could I face doing so?

Body:
In addition to the provided comments:

%$% also called the Exposition pipe vs. %>%:

This is  a short summary of this article https://towardsdatascience.com/3-lesser-known-pipe-operators-in-tidyverse-111d3411803a

"The key difference in using %$% or %>% lies in the type of arguments of used functions."

One advantage, and as far as I can understand it, for me the only one to use %$% over %>% is the fact that
we can avoid repetitive input of the dataframe name in functions that have no data as an argument.

For example the lm() has a data argument. In this case we can use both %>% and %$% interchangeable.

But in functions like the cor() which has no data argument:

mtcars %>% cor(disp, mpg) # Will give an Error

cor(mtcars$disp, mtcars$mpg)

is equivalent to

mtcars %$% cor(disp, mpg)

And note to use %$% pipe operator you have to load library(magrittr)

Update: on OPs comment:
The pipe independent which one allows us to transform machine or computer language to a more readable human language.

ggplot2 is special. ggplot2 is not internally consistent.
ggplot1 had a tidier API then ggplot2

Pipes would work with ggplot1:
library(ggplot1) mtcars %>%  ggplot(list( x= mpg, y = wt)) %>%  ggpoint() %>%  ggsave("mtcars.pdf", width= 8 height = 6)

In 2016 Wick Hadley said:
"ggplot2 newver would have existed if I'd discovered the pipe 10 years earlier!"
https://www.youtube.com/watch?v=K-ss_ag2k9E&list=LL&index=9


问:
Hiding error messages if writing to a file fails in a Windows .BAT script
i just subscribe here.

I would want to hide the "Acces is denied." error message in case writing to a read-only file fails. Could someone tell me why the following code doesn't work as expected ? I'm using Windows 10.

```<code>:: This file is assumed to be read-only.
echo( >"MyReadOnlyFile.txt" 2>nul
( echo( ) >"MyReadOnlyFile.txt" 2>nul
</code>```

In both case the "Access is denied." message is displayed, although the following "How-to: Redirection" page at SS64 says the contrary: https://ss64.com/nt/syntax-redirection.html

```<code>Redirect to NUL (hide errors)
command >filename 2> nul  Redirect output to file but suppress error
(command)>filename 2> nul  Redirect output to file but suppress CMD.exe errors
</code>```

Thanks in advance for your help.

Lionel.

答:
Thanks for your quick answers, i really appreciate.

Microsoft has been telling us for over a decade that PowerShell is the future of scripting.

I know indeed. I'm currently optimizing my own application in Batch+third party tools (a retrogame launcher, the main Batch script is about 41000 lines) by improving various stuffs here and there, so i guess Powershell will wait for a next project (smile). But anyway thanks for your advice, you're right.

Alternatively you could use the same method to reset the read only attribute, write to the file, then apply the read only attribute again:

This dir /A:-DR /B is nice and fast way to test if a file is read-only, indeed. There may be benefits to proceed in this way instead of 1. grabbing the file attribute with a more conventional for %%F in ("MyReadOnlyFile.txt") do set "file.attr=%%~aF" then 2. testing the second character by enabling delayed expansion. I will check where i can use it in my code to optimize some parts slightly, thank you for your suggestion Compo.

The error isn't written to STDERR, but to STDOUT (don't ask me, why), so echo( >"MyReadOnlyFile.txt" 1>nul suppresses the error message (sadly along with any possible useful output)

Thanks for your answer Stephan. Well, we know that Batch is quite insane often, but a such behavior would be more than insanity (smile). Redirecting stdout 1>nul doesn't hide the error message (as expected). However, surrounding the command and file redirection with brackets works as expected:

```<code>(echo( >"MyReadOnlyFile.txt") 2>nul
</code>```

It might be a possible typing error on SS64 about the position of surrounding brackets, it should be (command >"filename") 2>nul. The error message is redidrected to stderr as expected, confirmed by the following if you open the "stderr.txt" file.

```<code>(echo( >"MyReadOnlyFile.txt") 2>"stderr.txt"
</code>```

Again thank you to have replied, i did read a ton of threads on stackoverflow during the whole development of my application but i never subscribed. So that's a special feeling to have opened an account finally.

EDIT
I also add these two in case it can help someone.

```<code>rem Merge stderr to stdout.
set "_mute=>nul 2>&1" & set "_mute1=1>nul" & set "_mute2=2>nul"

rem Force ERRORLEVEL to 0.
set "_errlev0=(call )"

rem If you're lazy to type it each time (i am !).
set "_ede=enabledelayedexpansion"

rem Existing file name.
set "file.path=MyTestFile.txt"

rem Paths to the SQLite executable and SQLite database (example).
set "sqlite_file.path=C:\SQLite\SQLite.exe"
set "db_file.path=C:\Database\MyBase.db"

setlocal %_ede%
rem --- Test1 ---
%_errlev0%
echo ERRORLEVEL=!ERRORLEVEL!
(echo| set /p dummy_name="Hello & world">>"!file.path!") %_mute% && (
  echo Test1 succeeded
) || (
  echo Test1 failed
)
echo %ERRORLEVEL=!ERRORLEVEL!

rem --- Test2 ---
:: Whatever SQLite query of your choice.
set "sql_query=SELECT arcade_t.description FROM arcade_t WHERE arcade_t.description LIKE '%%Capcom%%'"
set "sql_bad_query=_!sql_query!"

%_errlev0%
echo ERRORLEVEL=!ERRORLEVEL!
(>>"!file.path!" "!sqlite_file.path!" "!db_file.path!" "!sql_query!") %_mute% && (
  echo Test2 succeeded
) || (
  echo Test2 failed
)
echo ERRORLEVEL=!ERRORLEVEL!

endlocal
</code>```

Surrounding the WHOLE command echo| set /p dummy_name="..." with brackets (as mentionned above, cf typing error in the SS64 page) and muting both stdout+stderr (or stderr only with %_mute2%) will hide the error message if writing the file failed.

Mentionning a variable name in the command set /p dummy_name="..." sets ERRORLEVEL as expected once the command echo| set /p="..." ends: 0 if writing the file succeeded, 1 if it failed. On the contrary, using a nameless command echo| set /p ="..." sets ERRORLEVEL to 1 even if writing the file succeeded, so should be avoided.

Again, surrounding the WHOLE SQLite command with brackets will hide the "Acces is denied." message but the SQLite "Error: near "_SELECT": syntax error" error message as well in case the SQLite query is syntaxically incorrect. This has has been tested and confirmed by replacing the proper query with the bad one sql_bad_query.

Body:
i just subscribe here.

I would want to hide the "Acces is denied." error message in case writing to a read-only file fails. Could someone tell me why the following code doesn't work as expected ? I'm using Windows 10.

:: This file is assumed to be read-only.
echo( >"MyReadOnlyFile.txt" 2>nul
( echo( ) >"MyReadOnlyFile.txt" 2>nul

In both case the "Access is denied." message is displayed, although the following "How-to: Redirection" page at SS64 says the contrary: https://ss64.com/nt/syntax-redirection.html

Redirect to NUL (hide errors)
command >filename 2> nul  Redirect output to file but suppress error
(command)>filename 2> nul  Redirect output to file but suppress CMD.exe errors

Thanks in advance for your help.

Lionel.

Body:
Thanks for your quick answers, i really appreciate.

Microsoft has been telling us for over a decade that PowerShell is the future of scripting.

I know indeed. I'm currently optimizing my own application in Batch+third party tools (a retrogame launcher, the main Batch script is about 41000 lines) by improving various stuffs here and there, so i guess Powershell will wait for a next project (smile). But anyway thanks for your advice, you're right.

Alternatively you could use the same method to reset the read only attribute, write to the file, then apply the read only attribute again:

This dir /A:-DR /B is nice and fast way to test if a file is read-only, indeed. There may be benefits to proceed in this way instead of 1. grabbing the file attribute with a more conventional for %%F in ("MyReadOnlyFile.txt") do set "file.attr=%%~aF" then 2. testing the second character by enabling delayed expansion. I will check where i can use it in my code to optimize some parts slightly, thank you for your suggestion Compo.

The error isn't written to STDERR, but to STDOUT (don't ask me, why), so echo( >"MyReadOnlyFile.txt" 1>nul suppresses the error message (sadly along with any possible useful output)

Thanks for your answer Stephan. Well, we know that Batch is quite insane often, but a such behavior would be more than insanity (smile). Redirecting stdout 1>nul doesn't hide the error message (as expected). However, surrounding the command and file redirection with brackets works as expected:

(echo( >"MyReadOnlyFile.txt") 2>nul

It might be a possible typing error on SS64 about the position of surrounding brackets, it should be (command >"filename") 2>nul. The error message is redidrected to stderr as expected, confirmed by the following if you open the "stderr.txt" file.

(echo( >"MyReadOnlyFile.txt") 2>"stderr.txt"

Again thank you to have replied, i did read a ton of threads on stackoverflow during the whole development of my application but i never subscribed. So that's a special feeling to have opened an account finally.

EDIT
I also add these two in case it can help someone.

rem Merge stderr to stdout.
set "_mute=>nul 2>&1" & set "_mute1=1>nul" & set "_mute2=2>nul"

rem Force ERRORLEVEL to 0.
set "_errlev0=(call )"

rem If you're lazy to type it each time (i am !).
set "_ede=enabledelayedexpansion"

rem Existing file name.
set "file.path=MyTestFile.txt"

rem Paths to the SQLite executable and SQLite database (example).
set "sqlite_file.path=C:\SQLite\SQLite.exe"
set "db_file.path=C:\Database\MyBase.db"

setlocal %_ede%
rem --- Test1 ---
%_errlev0%
echo ERRORLEVEL=!ERRORLEVEL!
(echo| set /p dummy_name="Hello & world">>"!file.path!") %_mute% && (
  echo Test1 succeeded
) || (
  echo Test1 failed
)
echo %ERRORLEVEL=!ERRORLEVEL!

rem --- Test2 ---
:: Whatever SQLite query of your choice.
set "sql_query=SELECT arcade_t.description FROM arcade_t WHERE arcade_t.description LIKE '%%Capcom%%'"
set "sql_bad_query=_!sql_query!"

%_errlev0%
echo ERRORLEVEL=!ERRORLEVEL!
(>>"!file.path!" "!sqlite_file.path!" "!db_file.path!" "!sql_query!") %_mute% && (
  echo Test2 succeeded
) || (
  echo Test2 failed
)
echo ERRORLEVEL=!ERRORLEVEL!

endlocal

Surrounding the WHOLE command echo| set /p dummy_name="..." with brackets (as mentionned above, cf typing error in the SS64 page) and muting both stdout+stderr (or stderr only with %_mute2%) will hide the error message if writing the file failed.

Mentionning a variable name in the command set /p dummy_name="..." sets ERRORLEVEL as expected once the command echo| set /p="..." ends: 0 if writing the file succeeded, 1 if it failed. On the contrary, using a nameless command echo| set /p ="..." sets ERRORLEVEL to 1 even if writing the file succeeded, so should be avoided.

Again, surrounding the WHOLE SQLite command with brackets will hide the "Acces is denied." message but the SQLite "Error: near "_SELECT": syntax error" error message as well in case the SQLite query is syntaxically incorrect. This has has been tested and confirmed by replacing the proper query with the bad one sql_bad_query.


问:
How to connect ethers.js library with Rinkeby programmatically?
According to official docs of ethers.js, this should be the way how to connect to a specific network like Rinkeby-testnet with custom data:

```<code> const provider = ethers.getDefaultProvider(network, {
    etherscan: ETHERSCAN_API_KEY,
    infura: INFURA_API_KEY,
</code>```

Also, this would be the way to get a signer in order to sign transactions:

```<code> const signer = provider.getSigner()
</code>```

However, there is now method "getSigner" available on the default provider.

TypeError: provider.getSigner is not a function

How to achieve that using ethers.js?

答:
This works for me:

const provider = new ethers.providers.JsonRpcProvider(url)
const signer = provider.getSigner()
```

Got to know about this from the Alchemy docs

ethers.js doc

Body:
According to official docs of ethers.js, this should be the way how to connect to a specific network like Rinkeby-testnet with custom data:

 const provider = ethers.getDefaultProvider(network, {
    etherscan: ETHERSCAN_API_KEY,
    infura: INFURA_API_KEY,

Also, this would be the way to get a signer in order to sign transactions:

 const signer = provider.getSigner()

However, there is now method "getSigner" available on the default provider.

TypeError: provider.getSigner is not a function

How to achieve that using ethers.js?

Body:
This works for me:

const provider = new ethers.providers.JsonRpcProvider(url)
const signer = provider.getSigner()

Got to know about this from the Alchemy docs

ethers.js doc


问:
Set Cookie in React app works in localhost but not in production
I am trying to set a cookie on the client side in my react web app.

I am using CRA deployed to Firebase.

Tried both js-cookie and react-cookie - in both cases I see that the set cookie code is running correctly.

When developing in localhost everything works perfectly - yet in production no cookie is ever being created.

Am I missing something?

答:
According to react-cookie docs  setCookie(name, value, [options]) and
removeCookie(name, [options]) accepts domain key in options object. Are you using your production url as a value of domain key ?


问:
What's the difference between amplify env checkout and import?
The documentation describes two commands:

```<code>amplify env checkout <env-name> [--restore]
amplify env import --name <env-name> --config <provider-configs> [--awsInfo <aws-configs>]
</code>```

But doesn't explain the difference between them in detail. checkout seems pretty straightforward with examples that make it analogous to git checkout, but import is a bit of a mystery. What are the various use cases?

答:
amplify env checkout ... is to switch between existing in your local backend environment stacks.

amplify env import ... is to imports an already existing Amplify project environment stack to your local backend.

The more details how to use the commands can be found here.

Although the checkout command is very similar to git. The import command is a little bit confusing when you first try to use it. In the link above there is an example how to import the environment. The important thing is to get the right AWSCLOUDFORMATIONCONFIG from file amplify/team-provider-info.json

Personally for me is easier to keep every local backend stack in different directory.

Body:
The documentation describes two commands:

amplify env checkout <env-name> [--restore]
amplify env import --name <env-name> --config <provider-configs> [--awsInfo <aws-configs>]

But doesn't explain the difference between them in detail. checkout seems pretty straightforward with examples that make it analogous to git checkout, but import is a bit of a mystery. What are the various use cases?


问:
golangci-lint run command shows errors in makefile
I have created a make file to run some bash commands for Go.

This is check.sh file

This is my make file

Error is : make: *** [Makefile:23: check] Error 1

How can I solve this issue?

答:
Have you created mod file in the root folder ?

```<code>go mod init <root folder /Application Name>
</code>```

if yes, check for the bin folder if the specified package is installed, if not install the package ,

```<code>go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest
</code>```

Then add it in make file

```<code>lint:
       golangci-lint run
</code>```

Body:
Have you created mod file in the root folder ?

go mod init <root folder /Application Name>

if yes, check for the bin folder if the specified package is installed, if not install the package ,

go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest

Then add it in make file

lint:
       golangci-lint run


问:
connect to non-discoverable bluetooth device
I am developing an app for android. Just a general questions as to , if is it possible to connect to a device which is non discoverable publicly?

Thanks in advance.

答:
If you have previously paired with the device then it is possible to connect to it again even if it is not in discoverable mode. See this post:
programmatically-connect-to-paired-bluetooth-device</p>

```<code>    // use paired devices or create a BluetoothDevice using a mac address
    //Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
    BluetoothAdapter myAdapter = BluetoothAdapter.getDefaultAdapter();
    BluetoothDevice remoteDevice = myAdapter.getRemoteDevice("00:00:00:00:00:00");
    BluetoothSockt btSocket = remoteDevice.createRfcommSocketToServiceRecord(UUID);
    btSocket.connect();
    //get input and output stream etc...
</code>```

ContentLicense: CC BY-SA 2.5

Body:
If you have previously paired with the device then it is possible to connect to it again even if it is not in discoverable mode. See this post:
programmatically-connect-to-paired-bluetooth-device

    // use paired devices or create a BluetoothDevice using a mac address
    //Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
    BluetoothAdapter myAdapter = BluetoothAdapter.getDefaultAdapter();
    BluetoothDevice remoteDevice = myAdapter.getRemoteDevice("00:00:00:00:00:00");
    BluetoothSockt btSocket = remoteDevice.createRfcommSocketToServiceRecord(UUID);
    btSocket.connect();
    //get input and output stream etc...

ContentLicense: CC BY-SA 3.0


问:
how to transform keyword "def" in Isabelle2005 into the corresponding form in Isabelle2020
I am performing a script updating. I encount such a question that :

```<code>constdefs is_initiator::"sigma \<Rightarrow>  agent\<Rightarrow> agent \<Rightarrow>nat \<Rightarrow>nat \<Rightarrow>bool"
  "is_initiator s A B Na Nb ==
  (SP s)=[(+, Crypt (pubK B) {|Nonce Na, Agent A|}),
  (-,Crypt (pubK A) {|Nonce Na, Nonce Nb, Agent B|}),
  (+, Crypt (pubK B) (Nonce Nb))]"

constdefs is_responder::"sigma \<Rightarrow>  agent\<Rightarrow> agent \<Rightarrow>nat \<Rightarrow>nat \<Rightarrow>bool"
  "is_responder s A B Na Nb ==
  (SP s)=[(-, Crypt (pubK B) {|Nonce Na, Agent A|}),
  (+,Crypt (pubK A) {|Nonce Na, Nonce Nb, Agent B|}),
  (-, Crypt (pubK B) (Nonce Nb))]"

defs NSL_1:
"\<Sigma> == {s. Is_penetrator_strand s |
          (EX A B Na Nb.  is_initiator s  A B Na Nb) |
          (EX A B Na Nb.  is_responder s A B Na Nb)
       }"
</code>```

And In Isabelle 2020, I code these phases into

```<code>definition is_initiator::"sigma \<Rightarrow>  agent\<Rightarrow> agent \<Rightarrow>nat \<Rightarrow>nat \<Rightarrow>bool" where
  "is_initiator s A B Na Nb ==
  (SP s)=[(+, Crypt (pubK B) \<lbrace>Nonce Na, Agent A\<rbrace>),
  (-,Crypt (pubK A) \<lbrace>Nonce Na, Nonce Nb, Agent B\<rbrace>),
  (+, Crypt (pubK B) (Nonce Nb))]"

definition is_responder::"sigma \<Rightarrow>  agent\<Rightarrow> agent \<Rightarrow>nat \<Rightarrow>nat \<Rightarrow>bool" where
  "is_responder s A B Na Nb ==
  (SP s)=[(-, Crypt (pubK B)  \<lbrace> Nonce Na, Agent A\<rbrace>),
  (+,Crypt (pubK A)  \<lbrace>Nonce Na, Nonce Nb, Agent B\<rbrace>),
  (-, Crypt (pubK B) (Nonce Nb))]"

definition NSL_1:
"NSL_1 == \<Sigma> = {s. Is_penetrator_strand s |
          (EX A B Na Nb.  is_initiator s  A B Na Nb) |
          (EX A B Na Nb.  is_responder s A B Na Nb)
       }"
</code>```

When i try to unfold the definition NSL_1 in the lemma, find that can not pass in Isabelle2020. How can i transform these codes rightly? Thanks.

The main aim of this is that i wanna unfold the definition  NSL_1.

```<code> 1. ¬ Is_penetrator_strand (fst m') ⟹
    Key k ⊏  node_term m' ∧
    m' ∈ nodes b ∧
    k ∉ KP ∧
    (∀a ba. (a, ba) ≺⇩b m' ⟶ (a, ba) ∈ nodes b ⟶ Key k ⊏  node_term (a, ba) ⟶ k ∈ KP) ⟹
    b ∈ bundles ⟹
    fst m' ∈ Σ ⟹
    (∃A B Na Nb. is_initiator (fst m') A B Na Nb) ∨
    (∃A B Na Nb. is_responder (fst m') A B Na Nb)
</code>```

It can be seen that we assume that strand can not be Is_penetrator_strand, so it must be is_initiator and is_responder. Second question that how to apply the definition into lemma prove.

答:
I am not familiar with def, but it seems that the constant being defined is Sigma, and the name of the fact that Sigma = ... is NSL_1. So you'd need

```<code>definition NSL_1:
"\<Sigma> == {s. Is_penetrator_strand s |
          (EX A B Na Nb.  is_initiator s  A B Na Nb) |
          (EX A B Na Nb.  is_responder s A B Na Nb)
       }"
</code>```

Then you can do unfolding NSL_1 or apply (unfold NSL_1) or apply (auto simp add: NSL_1), whatever you need.

Body:
I am performing a script updating. I encount such a question that :

constdefs is_initiator::"sigma \<Rightarrow>  agent\<Rightarrow> agent \<Rightarrow>nat \<Rightarrow>nat \<Rightarrow>bool"
  "is_initiator s A B Na Nb ==
  (SP s)=[(+, Crypt (pubK B) {|Nonce Na, Agent A|}),
  (-,Crypt (pubK A) {|Nonce Na, Nonce Nb, Agent B|}),
  (+, Crypt (pubK B) (Nonce Nb))]"

constdefs is_responder::"sigma \<Rightarrow>  agent\<Rightarrow> agent \<Rightarrow>nat \<Rightarrow>nat \<Rightarrow>bool"
  "is_responder s A B Na Nb ==
  (SP s)=[(-, Crypt (pubK B) {|Nonce Na, Agent A|}),
  (+,Crypt (pubK A) {|Nonce Na, Nonce Nb, Agent B|}),
  (-, Crypt (pubK B) (Nonce Nb))]"

defs NSL_1:
"\<Sigma> == {s. Is_penetrator_strand s |
          (EX A B Na Nb.  is_initiator s  A B Na Nb) |
          (EX A B Na Nb.  is_responder s A B Na Nb)
       }"

And In Isabelle 2020, I code these phases into

definition is_initiator::"sigma \<Rightarrow>  agent\<Rightarrow> agent \<Rightarrow>nat \<Rightarrow>nat \<Rightarrow>bool" where
  "is_initiator s A B Na Nb ==
  (SP s)=[(+, Crypt (pubK B) \<lbrace>Nonce Na, Agent A\<rbrace>),
  (-,Crypt (pubK A) \<lbrace>Nonce Na, Nonce Nb, Agent B\<rbrace>),
  (+, Crypt (pubK B) (Nonce Nb))]"

definition is_responder::"sigma \<Rightarrow>  agent\<Rightarrow> agent \<Rightarrow>nat \<Rightarrow>nat \<Rightarrow>bool" where
  "is_responder s A B Na Nb ==
  (SP s)=[(-, Crypt (pubK B)  \<lbrace> Nonce Na, Agent A\<rbrace>),
  (+,Crypt (pubK A)  \<lbrace>Nonce Na, Nonce Nb, Agent B\<rbrace>),
  (-, Crypt (pubK B) (Nonce Nb))]"

definition NSL_1:
"NSL_1 == \<Sigma> = {s. Is_penetrator_strand s |
          (EX A B Na Nb.  is_initiator s  A B Na Nb) |
          (EX A B Na Nb.  is_responder s A B Na Nb)
       }"

When i try to unfold the definition NSL_1 in the lemma, find that can not pass in Isabelle2020. How can i transform these codes rightly? Thanks.

The main aim of this is that i wanna unfold the definition  NSL_1.

 1. ¬ Is_penetrator_strand (fst m') ⟹
    Key k ⊏  node_term m' ∧
    m' ∈ nodes b ∧
    k ∉ KP ∧
    (∀a ba. (a, ba) ≺⇩b m' ⟶ (a, ba) ∈ nodes b ⟶ Key k ⊏  node_term (a, ba) ⟶ k ∈ KP) ⟹
    b ∈ bundles ⟹
    fst m' ∈ Σ ⟹
    (∃A B Na Nb. is_initiator (fst m') A B Na Nb) ∨
    (∃A B Na Nb. is_responder (fst m') A B Na Nb)

It can be seen that we assume that strand can not be Is_penetrator_strand, so it must be is_initiator and is_responder. Second question that how to apply the definition into lemma prove.

Body:
I am not familiar with def, but it seems that the constant being defined is Sigma, and the name of the fact that Sigma = ... is NSL_1. So you'd need

definition NSL_1:
"\<Sigma> == {s. Is_penetrator_strand s |
          (EX A B Na Nb.  is_initiator s  A B Na Nb) |
          (EX A B Na Nb.  is_responder s A B Na Nb)
       }"

Then you can do unfolding NSL_1 or apply (unfold NSL_1) or apply (auto simp add: NSL_1), whatever you need.


问:
How to fix ImportError: System.DllNotFoundException: libdl.so
When I tried to import aesim.simba (power electronics package) in Jupyter notebook (I have Ubuntu budgie 21.10 as operating system), I got the following error

```<code>import aesim.simba

---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-1-2ec74653cfe4> in <module>
----> 1 import aesim.simba

~/anaconda3/lib/python3.7/site-packages/aesim/simba/__init__.py in <module>
      1 #%% Load modules...
----> 2 import clr, sys, os
      3
      4 foldername = os.path.join(os.path.dirname(os.path.abspath(__file__)),'Resources')
      5 sys.path.append(foldername)

ImportError: System.DllNotFoundException: libdl.so
  at (wrapper managed-to-native) Python.Runtime.NativeMethods.dlerror()
  at Python.Runtime.NativeMethods.GetProcAddress (System.IntPtr dllHandle, System.String name) [0x00014] in <8dd8fc13f92f45c99ad71297a6b63b31>:0
  at Python.Runtime.Runtime.Initialize (System.Boolean initSigs) [0x00263] in <8dd8fc13f92f45c99ad71297a6b63b31>:0
  at Python.Runtime.PythonEngine.Initialize (System.Collections.Generic.IEnumerable`1[T] args, System.Boolean setSysArgv, System.Boolean initSigs) [0x00014] in <8dd8fc13f92f45c99ad71297a6b63b31>:0
  at Python.Runtime.PythonEngine.Initialize (System.Boolean setSysArgv, System.Boolean initSigs) [0x00005] in <8dd8fc13f92f45c99ad71297a6b63b31>:0
  at Python.Runtime.PythonEngine.InitExt () [0x00000] in <8dd8fc13f92f45c99ad71297a6b63b31>:0
</code>```

I'm new in Linux world. Could any one tell me how to fix this issue and how to import aesim.simba correctly?

答:
After a lot of search to solve this issue, the solution is to install  libdl.so in Ubuntu terminal  by executing  this command :
sudo ln -s /lib/x86_64-linux-gnu/libdl.so.2 /lib/x86_64-linux-gnu/libdl.so

now I have no problem at all when importing aesim.simba

This answer is from: https://github.com/sn4k3/UVtools/discussions/342

Body:
When I tried to import aesim.simba (power electronics package) in Jupyter notebook (I have Ubuntu budgie 21.10 as operating system), I got the following error

import aesim.simba

---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-1-2ec74653cfe4> in <module>
----> 1 import aesim.simba

~/anaconda3/lib/python3.7/site-packages/aesim/simba/__init__.py in <module>
      1 #%% Load modules...
----> 2 import clr, sys, os
      3
      4 foldername = os.path.join(os.path.dirname(os.path.abspath(__file__)),'Resources')
      5 sys.path.append(foldername)

ImportError: System.DllNotFoundException: libdl.so
  at (wrapper managed-to-native) Python.Runtime.NativeMethods.dlerror()
  at Python.Runtime.NativeMethods.GetProcAddress (System.IntPtr dllHandle, System.String name) [0x00014] in <8dd8fc13f92f45c99ad71297a6b63b31>:0
  at Python.Runtime.Runtime.Initialize (System.Boolean initSigs) [0x00263] in <8dd8fc13f92f45c99ad71297a6b63b31>:0
  at Python.Runtime.PythonEngine.Initialize (System.Collections.Generic.IEnumerable`1[T] args, System.Boolean setSysArgv, System.Boolean initSigs) [0x00014] in <8dd8fc13f92f45c99ad71297a6b63b31>:0
  at Python.Runtime.PythonEngine.Initialize (System.Boolean setSysArgv, System.Boolean initSigs) [0x00005] in <8dd8fc13f92f45c99ad71297a6b63b31>:0
  at Python.Runtime.PythonEngine.InitExt () [0x00000] in <8dd8fc13f92f45c99ad71297a6b63b31>:0

I'm new in Linux world. Could any one tell me how to fix this issue and how to import aesim.simba correctly?


问:
Django: add new column by function ( datetimefield to datefield )

Change datetimefield to datefield and put in in new column

python ways are useless because i want to be able to use order_by and distinct

i don't want to use sorted() and etc

my django model is something like this

class Product(models.Model):
    price = models.PositiveIntegerField(null=False, default=0)
    discounted_price = models.PositiveIntegerField(null=False, default=0)
    date = models.DateTimeField(auto_now_add=True)
```
<p>And i want to be able to call <strong>date()</strong> function<br />
and put it in another column and <strong>order_by</strong> it</p>
<pre class="lang-py prettyprint-override"><code>Product.objects.annotate(day=date.date()).order_by('-day').distinct('day')
</code>```

答:
You can do somthing like this

```<code>Product.objects.annotate(date__date=date.date()).order_by('-date').distinct('date')
</code>```

check doc. for more information

Body:
Change datetimefield to datefield and put in in new column

python ways are useless because i want to be able to use order_by and distinct

i don't want to use sorted() and etc

my django model is something like this

class Product(models.Model):
    price = models.PositiveIntegerField(null=False, default=0)
    discounted_price = models.PositiveIntegerField(null=False, default=0)
    date = models.DateTimeField(auto_now_add=True)

And i want to be able to call date() function

and put it in another column and order_by it

Product.objects.annotate(day=date.date()).order_by('-day').distinct('day')

Body:
You can do somthing like this

Product.objects.annotate(date__date=date.date()).order_by('-date').distinct('date')

check doc. for more information


问:
Create a new row with IF - Python/Pandas
I try to 'split/copy' a row if an IF-Condition (e.g. a cell contains a value) is true...

For example I've got this table:

```<code>d = {'Invited_guest': ["Max", "Luca", "John", "Biran", "Ian"], 'Age': [19, 21, 32, 45, 34], 'Origin' : ['US', 'UK', 'GER', 'ITA', 'FRA'],'FamilyMember_1': ["Paul", "Anna", "Peter", "Lewis", "Jeremy"], 'FamilyMember_2': ['Rene', 'Ruben', 'Calvin', 'George', 'Silke'], 'FamilyMember_3': ['', 'Olivia', '', '', 'Selina']}
df = pd.DataFrame(data=d)
df
</code>```

Index
Invited_guest
Age
Origin
FamilyMember_1
FamilyMember_2
FamilyMember_3

0
Max
19
US
Paul
Rene

1
Luca
21
UK
Anna
Ruben
Olivia

2
John
32
GER
Peter
Calvin

3
Brian
45
ITA
Lewis
George

4
Ian
34
FRA
Jeremy
Silke
Selina

So what I want to do is if there is more than one familymember the row gets splited and copied with just one familymember....Like this:

Index
Invited_guest
Age
Origin
FamilyMember

0
Max
19
US
Paul

1
Max
19
US
Rene

2
Luca
21
UK
Anna

3
Luca
21
UK
Ruben

4
Luca
21
UK
Anna

5
Luca
21
UK
Olivia

6
John
32
GER
Peter

7
John
32
GER
Calvin

8
Brian
45
ITA
Lewis

9
Brian
45
ITA
George

10
Ian
34
FRA
Jeremy

11
Ian
34
FRA
Silke

12
Ian
34
FRA
Selina

I hope my question is understandable...

Maybe I should say that I'm quite new to pandas and python and I'm very thankful for any idea, tip and remark :D it's just a practise for myselfe, don't know if this is a 'real world problem' :DD

答:
First, we get all the columns starting by FamilyMember_.

Then, we can use pandas.melt to get the expected result.

To get a clean output, we can drop the melt created output variable, then we drop the NaN values as some Invited_guest don't have a FamilyMember_3, we sort the values by Invited_guest and reset the index to get a clean ordered final DataFrame :

>>> keys = [c for c in df if c.startswith('FamilyMember_')]
>>> pd.melt(df, id_vars=['Invited_guest', 'Age', 'Origin'], value_vars=keys, value_name='key').drop('variable', axis=1).dropna().sort_values('Invited_guest').reset_index(drop=True)
    Invited_guest   Age     Origin  key
0   Brian           45      ITA     Lewis
1   Brian           45      ITA     George
2   Ian             34      FRA     Jeremy
3   Ian             34      FRA     Silke
4   Ian             34      FRA     Selina
5   John            32      GER     Peter
6   John            32      GER     Calvin
7   Luca            21      UK      Anna
8   Luca            21      UK      Ruben
9   Luca            21      UK      Olivia
10  Max             19      US      Paul
11  Max             19      US      Rene
```

Body:
I try to 'split/copy' a row if an IF-Condition (e.g. a cell contains a value) is true...

For example I've got this table:

d = {'Invited_guest': ["Max", "Luca", "John", "Biran", "Ian"], 'Age': [19, 21, 32, 45, 34], 'Origin' : ['US', 'UK', 'GER', 'ITA', 'FRA'],'FamilyMember_1': ["Paul", "Anna", "Peter", "Lewis", "Jeremy"], 'FamilyMember_2': ['Rene', 'Ruben', 'Calvin', 'George', 'Silke'], 'FamilyMember_3': ['', 'Olivia', '', '', 'Selina']}
df = pd.DataFrame(data=d)
df

Index
Invited_guest
Age
Origin
FamilyMember_1
FamilyMember_2
FamilyMember_3

0
Max
19
US
Paul
Rene

1
Luca
21
UK
Anna
Ruben
Olivia

2
John
32
GER
Peter
Calvin

3
Brian
45
ITA
Lewis
George

4
Ian
34
FRA
Jeremy
Silke
Selina

So what I want to do is if there is more than one familymember the row gets splited and copied with just one familymember....Like this:

Index
Invited_guest
Age
Origin
FamilyMember

0
Max
19
US
Paul

1
Max
19
US
Rene

2
Luca
21
UK
Anna

3
Luca
21
UK
Ruben

4
Luca
21
UK
Anna

5
Luca
21
UK
Olivia

6
John
32
GER
Peter

7
John
32
GER
Calvin

8
Brian
45
ITA
Lewis

9
Brian
45
ITA
George

10
Ian
34
FRA
Jeremy

11
Ian
34
FRA
Silke

12
Ian
34
FRA
Selina

I hope my question is understandable...

Maybe I should say that I'm quite new to pandas and python and I'm very thankful for any idea, tip and remark :D it's just a practise for myselfe, don't know if this is a 'real world problem' :DD


问:
getting different output in unordered manner
I am new to javascript so please do answer in detail,
I am calling settimeOut first and than calling an anonymous functions
but the out is arranged in opposite manner,
So What i want to know why is it so,is it because of online compiler or any concept
This is the image

```<code>setTimeout(function() {
    console.log('Execute later after 1 second')
}, 1000);

let show = function() {
    console.log('Anonymous function');
};

show();
</code>```

答:
That is due to what setTimeout does. setTimeout receives a callback function and a timeout in milliseconds, the execution of the callback function will be delayed by the given amount of the timeout. Meaning that show() will be executed first and console.log("Execute later after 1 second"); after one second.
Long story short setTimeout delays the execution of a given function.
So everything works as it should.

Body:
I am new to javascript so please do answer in detail,
I am calling settimeOut first and than calling an anonymous functions
but the out is arranged in opposite manner,
So What i want to know why is it so,is it because of online compiler or any concept
This is the image

setTimeout(function() {
    console.log('Execute later after 1 second')
}, 1000);

let show = function() {
    console.log('Anonymous function');
};

show();


问:
I applied a range to a goroutine channel, but I am getting an error. what's the problem?
I am studying goroutines and channels. I wrote a practice code to figure out the concurrency problem of goroutine and solve it. Deposit() is called 10 times, passing a bool to the done channel. After that, this is the code that resolves the concurrency while receiving done.

I am getting an error when I run the following code:

package main

import (
    "bank"
    "fmt"
    "log"
    "time"
)

func main() {
    start := time.Now()

    done := make(chan bool)

    // Alice
    for i := 0; i < 10; i++ {
        go func() {
            bank.Deposit(1)
            done <- true
        }()
    }

    // Wait for both transactions.
    for flag := range done {
        if !flag {
            panic("error")
        }
    }

    fmt.Printf("Balance = %d\n", bank.Balance())
    defer log.Printf("[time] Elipsed Time: %s", time.Since(start))
}
```
<pre class="lang-golang prettyprint-override"><code>package bank

var deposits = make(chan int) // send amount to deposit
var balances = make(chan int) // receive balance

func Deposit(amount int) { deposits <- amount }
func Balance() int       { return <-balances }

func teller() {
    var balance int // balance is confined to teller goroutine
    for {
        select {
        case amount := <-deposits:
            balance += amount
        case balances <- balance:
        }
    }
}

func init() {
    go teller() // start the monitor goroutine
}
</code>```

But I get an error.

```<code>fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan receive]:
main.main()
        /Users/kyounghwan.choi/go/main.go:48 +0xd6

goroutine 49 [select]:
bank.teller()
        /usr/local/go/src/bank/bank.go:14 +0x85
created by bank.init.0
        /usr/local/go/src/bank/bank.go:23 +0x25
exit status 2
</code>```

am i missing something?
what's the problem?

答:
The deadlock occurs because the runtime detected that the remaining routines were stuck and could never proceed further.

That has happen because the implementation does not provide the required logic to exit the loop iteration over the done channel.

To exit that iteration the implementation must close the channel or break out.

This is commonly solved using a WaitGroup.

A WaitGroup waits for a collection of goroutines to finish. The main goroutine calls Add to set the number of goroutines to wait for. Then each of the goroutines runs and calls Done when finished. At the same time, Wait can be used to block until all goroutines have finished.

A WaitGroup must not be copied after first use.

```<code>func main() {
    start := time.Now()
    done := make(chan bool)

    var wg sync.WaitGroup
    for i := 0; i < 10; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            bank.Deposit(1)
            done <- true
        }()
    }
    go func() {
        wg.Wait()
        close(done)
    }()
    // Wait for the channel to close.
    for flag := range done {
        if !flag {
            panic("error")
        }
    }

    fmt.Printf("Balance = %d\n", bank.Balance())
    defer log.Printf("[time] Elipsed Time: %s", time.Since(start))
}
</code>```

https://go.dev/play/p/pyuguc6LaEX

Though, closing the channel, in this convoluted example, is really just a burden without additional values.

This main function could be written,

```<code>func main() {
    start := time.Now()

    var wg sync.WaitGroup
    for i := 0; i < 10; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            bank.Deposit(1)
        }()
    }
    wg.Wait()

    fmt.Printf("Balance = %d\n", bank.Balance())
    defer log.Printf("[time] Elipsed Time: %s", time.Since(start))
}
</code>```

https://go.dev/play/p/U4Zh62Rt_Be

Though, it appears to me that removing the "concurrency" just works as good https://go.dev/play/p/qXs2oqi_1Zw

Using channels it is also possible to read at most as many times it was written.

```<code>func main() {
    start := time.Now()

    done := make(chan bool)

    // Alice
    for i := 0; i < 10; i++ {
        go func() {
            bank.Deposit(1)
            done <- true
        }()
    }

    // Read that much writes.
    for i := 0; i < 10; i++ {
        if !<-done {
            panic("error")
        }
    }

    fmt.Printf("Balance = %d\n", bank.Balance())
    defer log.Printf("[time] Elipsed Time: %s", time.Since(start))
}
</code>```

Body:
I am studying goroutines and channels. I wrote a practice code to figure out the concurrency problem of goroutine and solve it. Deposit() is called 10 times, passing a bool to the done channel. After that, this is the code that resolves the concurrency while receiving done.

I am getting an error when I run the following code:

package main

import (
    "bank"
    "fmt"
    "log"
    "time"
)

func main() {
    start := time.Now()

    done := make(chan bool)

    // Alice
    for i := 0; i < 10; i++ {
        go func() {
            bank.Deposit(1)
            done <- true
        }()
    }

    // Wait for both transactions.
    for flag := range done {
        if !flag {
            panic("error")
        }
    }

    fmt.Printf("Balance = %d\n", bank.Balance())
    defer log.Printf("[time] Elipsed Time: %s", time.Since(start))
}

package bank

var deposits = make(chan int) // send amount to deposit
var balances = make(chan int) // receive balance

func Deposit(amount int) { deposits <- amount }
func Balance() int       { return <-balances }

func teller() {
    var balance int // balance is confined to teller goroutine
    for {
        select {
        case amount := <-deposits:
            balance += amount
        case balances <- balance:
        }
    }
}

func init() {
    go teller() // start the monitor goroutine
}

But I get an error.

fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan receive]:
main.main()
        /Users/kyounghwan.choi/go/main.go:48 +0xd6

goroutine 49 [select]:
bank.teller()
        /usr/local/go/src/bank/bank.go:14 +0x85
created by bank.init.0
        /usr/local/go/src/bank/bank.go:23 +0x25
exit status 2

am i missing something?
what's the problem?

Body:
The deadlock occurs because the runtime detected that the remaining routines were stuck and could never proceed further.

That has happen because the implementation does not provide the required logic to exit the loop iteration over the done channel.

To exit that iteration the implementation must close the channel or break out.

This is commonly solved using a WaitGroup.

A WaitGroup waits for a collection of goroutines to finish. The main goroutine calls Add to set the number of goroutines to wait for. Then each of the goroutines runs and calls Done when finished. At the same time, Wait can be used to block until all goroutines have finished.

A WaitGroup must not be copied after first use.

func main() {
    start := time.Now()
    done := make(chan bool)

    var wg sync.WaitGroup
    for i := 0; i < 10; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            bank.Deposit(1)
            done <- true
        }()
    }
    go func() {
        wg.Wait()
        close(done)
    }()
    // Wait for the channel to close.
    for flag := range done {
        if !flag {
            panic("error")
        }
    }

    fmt.Printf("Balance = %d\n", bank.Balance())
    defer log.Printf("[time] Elipsed Time: %s", time.Since(start))
}

https://go.dev/play/p/pyuguc6LaEX

Though, closing the channel, in this convoluted example, is really just a burden without additional values.

This main function could be written,

func main() {
    start := time.Now()

    var wg sync.WaitGroup
    for i := 0; i < 10; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            bank.Deposit(1)
        }()
    }
    wg.Wait()

    fmt.Printf("Balance = %d\n", bank.Balance())
    defer log.Printf("[time] Elipsed Time: %s", time.Since(start))
}

https://go.dev/play/p/U4Zh62Rt_Be

Though, it appears to me that removing the "concurrency" just works as good https://go.dev/play/p/qXs2oqi_1Zw

Using channels it is also possible to read at most as many times it was written.

func main() {
    start := time.Now()

    done := make(chan bool)

    // Alice
    for i := 0; i < 10; i++ {
        go func() {
            bank.Deposit(1)
            done <- true
        }()
    }

    // Read that much writes.
    for i := 0; i < 10; i++ {
        if !<-done {
            panic("error")
        }
    }

    fmt.Printf("Balance = %d\n", bank.Balance())
    defer log.Printf("[time] Elipsed Time: %s", time.Since(start))
}


问:
Moving an element using javascript
I've built a small Javascript application which can move an SVG element, i've now tried to rebuild it using image elements for the controls rather than SVG shapes.

Javascript + jQuery

```<code><script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        var panning = false;
        var direction;

        function startPan(dir){
            panning = true;
            direction = dir;
        }

        function stopPan(){
            panning = false;
        }

        function pan(){
            var item = $("#moveme");
            var x = item.position().left;
            var y = item.position().top;
            var amount = 1;
            if(direction == "left"){
                x -= amount;
            } else if (direction == "right"){
                x += amount ;
            } else if (direction == "up"){
                y -= amount;
            } else if (direction == "down"){
                y += amount;
            }

            item.css("left", x);
            item.css("top", y);
        }

        function panLoop(){
            if(panning == true){
                pan();
            }
        }
        setInterval(panLoop,100);
    });
</script>

<style>
    .button:hover{
        opacity: 0.5;
    }

    .button{
        position: absolute;
    }

    .compass{
        position: absolute;
    }

    div.pan{
        position: absolute;
        width: 90px;
        height: 90px;
    }

    #moveme{
        position: absolute;
        top: 200px;
        left: 200px;
    }
</style>

<div class="pan">
    <img class="button"
         style="top: 0px; left: 30px;"
         src="images/tu.png"
         onmouseover="startPan('up')"
         onmouseout="stopPan()" />
    <img class="button"
         style="top: 30px; right: 0px;"
         src="images/tr.png"
         onmouseover="startPan('right')"
         onmouseout="stopPan()" />

    <img class="button"
         style="bottom: 0px; left: 30px;"
         src="images/td.png"
         onmouseover="startPan('down')"
         onmouseout="stopPan()" />

    <img class="button"
         style="top: 30px; left: 0px;"
         src="images/tl.png"
         onmouseover="startPan('left')"
         onmouseout="stopPan()" />

    <img class="compass"
         style="top: 21px; left: 21px;"
         src="images/c.png"/>

</div>

<div id="moveme">
    HELLo
</div>
</code>```

However it's not calling the mouseover event, and I can't figure out why....

Here is the version using SVG:

Working version using Javascript + SVG

Working version:
Working without SVG

答:
See here http://jsbin.com/ecihij/edit#source

When you write your functions you do not need to put them inside the jQuery document Ready section

Jarred is right you should also be using jQuery event handers see updated example here
http://jsbin.com/ecihij/2/edit.

And code below

HTML

```<code><!DOCTYPE html>
<html>
<head>

<style>
    .button:hover{
        opacity: 0.5;
    }

    .button{
        position: absolute;
    }

    .compass{
        position: absolute;
    }

    div.pan{
        position: absolute;
        width: 90px;
        height: 90px;
    }

    #moveme{
        position: absolute;
        top: 200px;
        left: 200px;
    }
</style>

<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
  article, aside, figure, footer, header, hgroup,
  menu, nav, section { display: block; }
</style>
</head>
<body>
<div class="pan">

    <p class="button bup" style="top: 0px; left: 30px;" > up</p>

    <p  class="button bright" syle="top: 30px; right: 0px;" >right </p>

    <p  class="button bdown" style="bottom: 0px; left: 30px;">down </p>

    <p class="button bleft" style="top: 30px; left: 0px;" >left </p>

    <p  class="compass" style="top: 21px; left: 21px;">compass </p>

</div>

<div id="moveme">
    HELLo
</div>
</body>
</html>
</code>```

JAVASCRIPT

```<code>         var panning = false;
        var direction;

function startPan(dir){
            panning = true;
            direction = dir;
        }

        function stopPan(){
            panning = false;
        }

        function pan(){
            var item = $("#moveme");
            var x = item.position().left;
            var y = item.position().top;
            var amount = 1;
            if(direction == "left"){
                x -= amount;
            } else if (direction == "right"){
                x += amount ;
            } else if (direction == "up"){
                y -= amount;
            } else if (direction == "down"){
                y += amount;
            }

            item.css("left", x);
            item.css("top", y);
        }

        function panLoop(){
            if(panning === true){
                pan();
            }
        }

     setInterval(panLoop,100);

$(document).ready(function(){

  $('.bup').mouseover(function(){  startPan('up');  }).mouseout(stopPan);
  $('.bright').mouseover(function(){  startPan('right');  }).mouseout(stopPan);
  $('.bleft').mouseover(function(){  startPan('left');  }).mouseout(stopPan);
  $('.bdown').mouseover(function(){  startPan('down');  }).mouseout(stopPan);

    });
</code>```

Title: Moving an element using javascript

Body:
I've built a small Javascript application which can move an SVG element, i've now tried to rebuild it using image elements for the controls rather than SVG shapes.

Javascript + jQuery

    HELLo

However it's not calling the mouseover event, and I can't figure out why....

Here is the version using SVG:

Working version using Javascript + SVG

Working version:
Working without SVG

Body:
See here http://jsbin.com/ecihij/edit#source

When you write your functions you do not need to put them inside the jQuery document Ready section

Jarred is right you should also be using jQuery event handers see updated example here
http://jsbin.com/ecihij/2/edit.

And code below

HTML

<!DOCTYPE html>
<html>
<head>

<style>
    .button:hover{
        opacity: 0.5;
    }

    .button{
        position: absolute;
    }

    .compass{
        position: absolute;
    }

    div.pan{
        position: absolute;
        width: 90px;
        height: 90px;
    }

    #moveme{
        position: absolute;
        top: 200px;
        left: 200px;
    }
</style>

<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
  article, aside, figure, footer, header, hgroup,
  menu, nav, section { display: block; }
</style>
</head>
<body>
<div class="pan">

    <p class="button bup" style="top: 0px; left: 30px;" > up</p>

    <p  class="button bright" syle="top: 30px; right: 0px;" >right </p>

    <p  class="button bdown" style="bottom: 0px; left: 30px;">down </p>

    <p class="button bleft" style="top: 30px; left: 0px;" >left </p>

    <p  class="compass" style="top: 21px; left: 21px;">compass </p>

</div>

<div id="moveme">
    HELLo
</div>
</body>
</html>

JAVASCRIPT

         var panning = false;
        var direction;

function startPan(dir){
            panning = true;
            direction = dir;
        }

        function stopPan(){
            panning = false;
        }

        function pan(){
            var item = $("#moveme");
            var x = item.position().left;
            var y = item.position().top;
            var amount = 1;
            if(direction == "left"){
                x -= amount;
            } else if (direction == "right"){
                x += amount ;
            } else if (direction == "up"){
                y -= amount;
            } else if (direction == "down"){
                y += amount;
            }

            item.css("left", x);
            item.css("top", y);
        }

        function panLoop(){
            if(panning === true){
                pan();
            }
        }

     setInterval(panLoop,100);

$(document).ready(function(){

  $('.bup').mouseover(function(){  startPan('up');  }).mouseout(stopPan);
  $('.bright').mouseover(function(){  startPan('right');  }).mouseout(stopPan);
  $('.bleft').mouseover(function(){  startPan('left');  }).mouseout(stopPan);
  $('.bdown').mouseover(function(){  startPan('down');  }).mouseout(stopPan);

    });


问:
How do I automate importing repos in gitlab?
How do I automate cloning/pushing certain repos to a gitlab instance when it is instantiated?

I'm building an IaC project which uses Gitlab, Terraform and Docker to build testing lab pods.

Thanks!

答:
With Gitlab provider:

```<code>resource "gitlab_project" "terraform" {
  name = "my_shiny_new_project"
  import_url = "https://github.com/hashicorp/terraform.git"
}
</code>```

Above will create a new project named "terraform" containing cloned repo from given URL.

Body:
With Gitlab provider:

resource "gitlab_project" "terraform" {
  name = "my_shiny_new_project"
  import_url = "https://github.com/hashicorp/terraform.git"
}

Above will create a new project named "terraform" containing cloned repo from given URL.


问:
How do I use a factory generated object?
I am a student trying to learn factory methods in C# and I would love some help.
I now have a CommanderFactory that creates a "Commander()". Let's say I generate a "Commander()" with both values set to 1. (val1 = 1, val2 = 2).
How Would I now go about doing calculations on these values? As seen in the calculator class above. I have a parameter for "Commander", but how do I "select" the values inside, and do addition on them?</p>
```<code>namespace FactoryCalculator
{
    public static class Calculator
    {
        public static int Add(Commander)
        {
            return val1 + val2;
        }

    }

    public class Commander
    {
        private Commander()
        {
        }

        public int Val1 { get; set; }
        public int Val2 { get; set; }

        public static class CommanderFactory
        {
            public static Commander CreateNewCommander(int val1, int val2)
            {
                return new Commander()
                {
                    Val1 = val1,
                    Val2 = val2
                };
            }

        }
    }
}
</code>```

答:
This is the syntax for accessing a Property ([instance].[property]):</p>
```<code>public static int Add(Commander c)
{
    return c.Val1 + c.Val2;
}
</code>```

Body:
I am a student trying to learn factory methods in C# and I would love some help.
I now have a CommanderFactory that creates a "Commander()". Let's say I generate a "Commander()" with both values set to 1. (val1 = 1, val2 = 2).
How Would I now go about doing calculations on these values? As seen in the calculator class above. I have a parameter for "Commander", but how do I "select" the values inside, and do addition on them?

namespace FactoryCalculator
{
    public static class Calculator
    {
        public static int Add(Commander)
        {
            return val1 + val2;
        }

    }

    public class Commander
    {
        private Commander()
        {
        }

        public int Val1 { get; set; }
        public int Val2 { get; set; }

        public static class CommanderFactory
        {
            public static Commander CreateNewCommander(int val1, int val2)
            {
                return new Commander()
                {
                    Val1 = val1,
                    Val2 = val2
                };
            }

        }
    }
}

Body:
This is the syntax for accessing a Property ([instance].[property]):

public static int Add(Commander c)
{
    return c.Val1 + c.Val2;
}


问:
"require 'mongoid'" is very slow
Just opening irb and typing require 'mongoid' takes more than 5 seconds on my Macbook Air. Is it normal, and how can I speed this up ? It slows down a lot my Rails and Ruby apps launches.

I tried with versions 2.0.1 and 2.1.8, same result. Ruby version is ruby 1.9.2p136 (2010-12-25 revision 30365) [x86_64-darwin10.6.0]

Thanks!

答:
require 'mongoid'

Seems to be a call that takes long, indeed.

On my MacBook Pro (ruby 1.9.2p180 (2011-02-18 revision 30909) [x86_64-darwin10.7.0]) it's taking about 5-7 seconds (I've tested it on irb).

Note that one interesting message I got was:

**Notice: C extension not loaded. This is required for optimum MongoDB
  Ruby driver performance.   You can install the extension as follows:

  gem install bson_ext

If you continue to receive this message after installing, make sure
  that the   bson_ext gem is in your load path and that the bson_ext and
  mongo gems are of the same version.

Installing that gem does not make the gem load faster but it seems to improve speed overall.

Bottom line: try to make that require only once and at the start of your application.

Title: "require 'mongoid'" is very slow


问:
How to iterate and display each element from inner list - reactjs
How to iterate and display each element from 'grandChildren' list -> for eg: ["AQ11", "AS12"]. Thank you.

responseData:

```<code>[{Key:"A",Value:["AQ11", "AS12"]}, {Key:"C",Value:["CN22", "CL33", "CV44"]}].
</code>```

Have set KeyValuePair's key to 'children' and Value to 'grandChildren' state.

I am able to display children but not grandChildren as it returns list of values ["AQ11", "AS12"]. Tried below but could not succeed

```<code>render() {
        const child= Object.values(this.state.items);
        const grandChild= Object.values(this.state.items[i].grandChildren); // Not sure how to set -  how do I pass value of i.

        return (
            <div>

                    {child.map((element, index) => {
                    <div key={index + element.children}>
                    return (
                         <Autocomplete
                            value={element.children}        // this displays children like "A" OR "C"
                         />

                            {grandChild.map((element1, index) => (
                                <Autocomplete
                                value={element.grandChildren[element1]}  // NOT SURE HOW TO GET THIS TO WORK
                                />
                            ))}
                    </div>
                    ))}

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

How do I iterate and display value of grandchildren

答:
You can do it like this</p>
```<code>render(){
  const child = Object.values(this.state.items);

  return (
    <div>
      {child.map((element, index) => {
        const grandChild = Object.values(this.state.items[index].grandChildren);

        return (
          <div key={index}>
            <Autocomplete
              value={element.children} // this displays children like "A" OR "C"
            />

            {grandChild.map((element1, index) => (
              <Autocomplete
                value={element1}
              />
            ))}
          </div>
        );
      })}
    </div>
  );
};

</code>```

Body:
How to iterate and display each element from 'grandChildren' list -> for eg: ["AQ11", "AS12"]. Thank you.

responseData:

[{Key:"A",Value:["AQ11", "AS12"]}, {Key:"C",Value:["CN22", "CL33", "CV44"]}].

Have set KeyValuePair's key to 'children' and Value to 'grandChildren' state.

I am able to display children but not grandChildren as it returns list of values ["AQ11", "AS12"]. Tried below but could not succeed

render() {
        const child= Object.values(this.state.items);
        const grandChild= Object.values(this.state.items[i].grandChildren); // Not sure how to set -  how do I pass value of i.

        return (

                    {child.map((element, index) => {

                    return (
                         <Autocomplete
                            value={element.children}        // this displays children like "A" OR "C"
                         />

                            {grandChild.map((element1, index) => (
                                <Autocomplete
                                value={element.grandChildren[element1]}  // NOT SURE HOW TO GET THIS TO WORK
                                />
                            ))}

                    ))}

                    );

How do I iterate and display value of grandchildren

Body:
You can do it like this

render(){
  const child = Object.values(this.state.items);

  return (
    <div>
      {child.map((element, index) => {
        const grandChild = Object.values(this.state.items[index].grandChildren);

        return (
          <div key={index}>
            <Autocomplete
              value={element.children} // this displays children like "A" OR "C"
            />

            {grandChild.map((element1, index) => (
              <Autocomplete
                value={element1}
              />
            ))}
          </div>
        );
      })}
    </div>
  );
};


问:
Max sum contiguous subarray
Find the contiguous subarray within an array, A of length N which has the largest sum.

Input Format:

The first and the only argument contains an integer array, A.

Output Format:

Return an integer representing the maximum possible sum of the contiguous subarray.

Constraints:

1 <= N <= 1e6
-1000 <= A[i] <= 1000

For example:

Input 1:
    A = [1, 2, 3, 4, -10]

Output 1:
    10

Explanation 1:
    The subarray [1, 2, 3, 4] has the maximum possible sum of 10.

Input 2:
    A = [-2, 1, -3, 4, -1, 2, 1, -5, 4]

Output 2:
    6

Explanation 2:
    The subarray [4,-1,2,1] has the maximum possible sum of 6.

Can you please tell me why the following code does not work, and what is the error in the code :

```<code>public class Solution {

public int maxSubArray(final List<Integer> A) {

    ArrayList<Integer> al = new ArrayList<Integer>();
    int sum = 0;
    int max = A.get(0);
    int min = A.get(0);
    for(int i = 0;i < A.size();i++){

        sum += A.get(i);
        al.add(sum);
        if(sum > max) max = sum;

    }

    //to find the min till the index of max
    for(int i = 0; al.get(i) != max;i++) {
        if(al.get(i) < min) min = al.get(i);
    }

    if(min < 0)return max-min;
    else return max;
}

}
</code>```

答:
Assume a situation like this where

```<code>A = [-120, -202, -293, -60, -261, -67, 10]
</code>```

So at the start

```<code>max = -120
min = -120
</code>```

Now during the first loop your max wouldn't change it will stay at -120 since the sum always be less than -120.

Also your second loop wouldn't run since,

al.get(i) = -120 and max = -120  then al.get(i) != max will be false.

Title: Max sum contiguous subarray

Body:
Find the contiguous subarray within an array, A of length N which has the largest sum.

Input Format:

The first and the only argument contains an integer array, A.

Output Format:

Return an integer representing the maximum possible sum of the contiguous subarray.

Constraints:

1 <= N <= 1e6
-1000 <= A[i] <= 1000

For example:

Input 1:
    A = [1, 2, 3, 4, -10]

Output 1:
    10

Explanation 1:
    The subarray [1, 2, 3, 4] has the maximum possible sum of 10.

Input 2:
    A = [-2, 1, -3, 4, -1, 2, 1, -5, 4]

Output 2:
    6

Explanation 2:
    The subarray [4,-1,2,1] has the maximum possible sum of 6.

Can you please tell me why the following code does not work, and what is the error in the code :

public class Solution {

public int maxSubArray(final List<Integer> A) {

    ArrayList<Integer> al = new ArrayList<Integer>();
    int sum = 0;
    int max = A.get(0);
    int min = A.get(0);
    for(int i = 0;i  max) max = sum;

    }

    //to find the min till the index of max
    for(int i = 0; al.get(i) != max;i++) {
        if(al.get(i) < min) min = al.get(i);
    }

    if(min < 0)return max-min;
    else return max;
}

}

Body:
Assume a situation like this where

A = [-120, -202, -293, -60, -261, -67, 10]

So at the start

max = -120
min = -120

Now during the first loop your max wouldn't change it will stay at -120 since the sum always be less than -120.

Also your second loop wouldn't run since,

al.get(i) = -120 and max = -120  then al.get(i) != max will be false.


问:
How do i turn this string into 2 arrays in python?
I have this string and want to turn it into two arrays, one has the film title and the other one has the year. Their positions in the array need to correspond with each other. Is there a way to do this?</p>
```<code>films = ("""Endless Love (1981), Top Gun (1986), The Color of Money (1986), Rain Man (1988),
Born on the Fourth of July (1989), Interview with the Vampire: The Vampire Chronicles (1994),
Mission: Impossible (1996), Jerry Maguire (1996), The Matrix (1999), Mission: Impossible II (2000),
Vanilla Sky (2001), Cocktail (1988), A Few Good Men (1992), The Firm (1993), Eyes Wide Shut (1999),
Magnolia (1999), Minority Report (2002), Austin Powers in Goldmember (2002), Days of Thunder (1990),
The Powers of Matthew Star (1982), Cold Mountain (2003), The Talented Mr. Ripley (1999),
 War of the Worlds (2005), The Oprah Winfrey Show (1986), Far and Away (1992), Taps (1981),
 The Last Samurai (2003), Valkyrie (2008), Jack Reacher (2012), Edge of Tomorrow (2014),
 Enemy of the State (1998), Mission: Impossible III (2006), Crimson Tide (1995), Reign Over Me (2007),
 Batman Forever (1995), Batman Begins (2005), The Simpsons (1989), The Simpsons: Brother from the Same Planet (1993),
 The Simpsons: When You Dish Upon a Star (1998), End of Days (1999), House of D (2004), The Indian Runner (1991),
  Harry & Son (1984), Mission: Impossible - Ghost Protocol (2011), Aladdin (1992), Pacific Rim (2013),
  Oblivion (2013), Knight and Day (2010),
""")
</code>```

答:
Answer of Tim is well enough. I will try to write an alternative someone who would like to solve the problem without using regex.

```<code>a = films.split(",")
years = []
for i in a:
    years.append(i[i.find("(")+1:i.find(")")])
</code>```

Same approach can be applied for titles.

Body:
I have this string and want to turn it into two arrays, one has the film title and the other one has the year. Their positions in the array need to correspond with each other. Is there a way to do this?

films = ("""Endless Love (1981), Top Gun (1986), The Color of Money (1986), Rain Man (1988),
Born on the Fourth of July (1989), Interview with the Vampire: The Vampire Chronicles (1994),
Mission: Impossible (1996), Jerry Maguire (1996), The Matrix (1999), Mission: Impossible II (2000),
Vanilla Sky (2001), Cocktail (1988), A Few Good Men (1992), The Firm (1993), Eyes Wide Shut (1999),
Magnolia (1999), Minority Report (2002), Austin Powers in Goldmember (2002), Days of Thunder (1990),
The Powers of Matthew Star (1982), Cold Mountain (2003), The Talented Mr. Ripley (1999),
 War of the Worlds (2005), The Oprah Winfrey Show (1986), Far and Away (1992), Taps (1981),
 The Last Samurai (2003), Valkyrie (2008), Jack Reacher (2012), Edge of Tomorrow (2014),
 Enemy of the State (1998), Mission: Impossible III (2006), Crimson Tide (1995), Reign Over Me (2007),
 Batman Forever (1995), Batman Begins (2005), The Simpsons (1989), The Simpsons: Brother from the Same Planet (1993),
 The Simpsons: When You Dish Upon a Star (1998), End of Days (1999), House of D (2004), The Indian Runner (1991),
  Harry & Son (1984), Mission: Impossible - Ghost Protocol (2011), Aladdin (1992), Pacific Rim (2013),
  Oblivion (2013), Knight and Day (2010),
""")

Body:
Answer of Tim is well enough. I will try to write an alternative someone who would like to solve the problem without using regex.

a = films.split(",")
years = []
for i in a:
    years.append(i[i.find("(")+1:i.find(")")])

Same approach can be applied for titles.


答:
You can use a combination of melt, groupby, and agg(list) to convert each row of FamilyMember names to a list (and use pipe to remove empty ones), then assign the result back to the dataframe, and explode that column:

```<code>exploded = df.assign(names=df.filter(like='FamilyMember_').T.melt().pipe(lambda x: x[x['value'] != '']).groupby('variable')['value'].agg(list)).explode('names').drop(df.filter(like='FamilyMember_'), axis=1).reset_index(drop=True)
</code>```

Output:

```<code>>>> exploded
   Invited_guest  Age Origin   names
0            Max   19     US    Paul
1            Max   19     US    Rene
2           Luca   21     UK    Anna
3           Luca   21     UK   Ruben
4           Luca   21     UK  Olivia
5           John   32    GER   Peter
6           John   32    GER  Calvin
7          Brian   45    ITA   Lewis
8          Brian   45    ITA  George
9            Ian   34    FRA  Jeremy
10           Ian   34    FRA   Silke
11           Ian   34    FRA  Selina
</code>```

Explanation

First, we select the columns that start with FamilyMember_:

```<code>>>> family_members = df.filter(like='FamilyMember_')
>>> family_members
  FamilyMember_1 FamilyMember_2 FamilyMember_3
0           Paul           Rene
1           Anna          Ruben         Olivia
2          Peter         Calvin
3          Lewis         George
4         Jeremy          Silke         Selina
</code>```

Next, we rotate that 90 degrees (also known as transposing) for later use with melt:

```<code>>>> family_members.T
                   0       1       2       3       4
FamilyMember_1  Paul    Anna   Peter   Lewis  Jeremy
FamilyMember_2  Rene   Ruben  Calvin  George   Silke
FamilyMember_3        Olivia                  Selina
</code>```

Then, we'll melt it:

```<code>>>> family_members.T.melt()
    variable   value
0          0    Paul
1          0    Rene
2          0
3          1    Anna
4          1   Ruben
5          1  Olivia
6          2   Peter
7          2  Calvin
8          2
9          3   Lewis
10         3  George
11         3
12         4  Jeremy
13         4   Silke
14         4  Selina
</code>```

Now we need to remove the empty items. We could do that like this:

```<code>x = family_members.T.melt()
x = x[x['values'] != '']
</code>```

...but that's multiple lines, which won't do in a one-liner. So we can use pipe with a lambda function to achieve exactly this in a one-liner fashion:

```<code>>>> family_members.T.melt().pipe(lambda x: x[x['value'] != ''])
    variable   value
0          0    Paul
1          0    Rene
3          1    Anna
4          1   Ruben
5          1  Olivia
6          2   Peter
7          2  Calvin
9          3   Lewis
10         3  George
12         4  Jeremy
13         4   Silke
14         4  Selina
</code>```

Then we can group by the variable column as it groups together perfectly those names that need to go together:

```<code>>>> g = family_members.T.melt().pipe(lambda x: x[x['value'] != '']).groupby('variable')
>>> g
<pandas.core.groupby.generic.DataFrameGroupBy object at 0x12b131e50>

# That's not very useful, so we can convert it to a list to have a peek at what's inside:
>>> list(g)
[(0,
     variable value
  0         0  Paul
  1         0  Rene),
 (1,
     variable   value
  3         1    Anna
  4         1   Ruben
  5         1  Olivia),
 (2,
     variable   value
  6         2   Peter
  7         2  Calvin),
 (3,
      variable   value
  9          3   Lewis
  10         3  George),
 (4,
      variable   value
  12         4  Jeremy
  13         4   Silke
  14         4  Selina)]
</code>```

We need to convert each of those groups to a list of the names contained inside them. That's where agg(list) comes in:

```<code>>>> g['value'].agg(list)
variable
0               [Paul, Rene]
1      [Anna, Ruben, Olivia]
2            [Peter, Calvin]
3            [Lewis, George]
4    [Jeremy, Silke, Selina]
Name: value, dtype: object
</code>```

Perfect. Now we need to put that column back on the dataframe. We could just assign it like normal:

```<code>g['names'] = g['value'].agg(list)
</code>```

...but again, that would make a one-liner impossible. Fortunately, there's the assign function, which is built for this use-case:

```<code>>>> exploded
   Invited_guest  Age Origin   names
0            Max   19     US    Paul
1            Max   19     US    Rene
2           Luca   21     UK    Anna
3           Luca   21     UK   Ruben
4           Luca   21     UK  Olivia
5           John   32    GER   Peter
6           John   32    GER  Calvin
7          Brian   45    ITA   Lewis
8          Brian   45    ITA  George
9            Ian   34    FRA  Jeremy
10           Ian   34    FRA   Silke
11           Ian   34    FRA  Selina
</code>```0

(Note that assign is NOT in-place. It modifies a new copy of the dataframe, not the original).

Finally, we use the magic explode (only available in pandas 0.25 and newer):

```<code>>>> exploded
   Invited_guest  Age Origin   names
0            Max   19     US    Paul
1            Max   19     US    Rene
2           Luca   21     UK    Anna
3           Luca   21     UK   Ruben
4           Luca   21     UK  Olivia
5           John   32    GER   Peter
6           John   32    GER  Calvin
7          Brian   45    ITA   Lewis
8          Brian   45    ITA  George
9            Ian   34    FRA  Jeremy
10           Ian   34    FRA   Silke
11           Ian   34    FRA  Selina
</code>```1

And of course, remove the only FamilyMember_* columns:

```<code>>>> exploded
   Invited_guest  Age Origin   names
0            Max   19     US    Paul
1            Max   19     US    Rene
2           Luca   21     UK    Anna
3           Luca   21     UK   Ruben
4           Luca   21     UK  Olivia
5           John   32    GER   Peter
6           John   32    GER  Calvin
7          Brian   45    ITA   Lewis
8          Brian   45    ITA  George
9            Ian   34    FRA  Jeremy
10           Ian   34    FRA   Silke
11           Ian   34    FRA  Selina
</code>```2

Title: Create a new row with IF - Python/Pandas

Body:
You can use a combination of melt, groupby, and agg(list) to convert each row of FamilyMember names to a list (and use pipe to remove empty ones), then assign the result back to the dataframe, and explode that column:

exploded = df.assign(names=df.filter(like='FamilyMember_').T.melt().pipe(lambda x: x[x['value'] != '']).groupby('variable')['value'].agg(list)).explode('names').drop(df.filter(like='FamilyMember_'), axis=1).reset_index(drop=True)

Output:

>>> exploded
   Invited_guest  Age Origin   names
0            Max   19     US    Paul
1            Max   19     US    Rene
2           Luca   21     UK    Anna
3           Luca   21     UK   Ruben
4           Luca   21     UK  Olivia
5           John   32    GER   Peter
6           John   32    GER  Calvin
7          Brian   45    ITA   Lewis
8          Brian   45    ITA  George
9            Ian   34    FRA  Jeremy
10           Ian   34    FRA   Silke
11           Ian   34    FRA  Selina

Explanation

First, we select the columns that start with FamilyMember_:

>>> family_members = df.filter(like='FamilyMember_')
>>> family_members
  FamilyMember_1 FamilyMember_2 FamilyMember_3
0           Paul           Rene
1           Anna          Ruben         Olivia
2          Peter         Calvin
3          Lewis         George
4         Jeremy          Silke         Selina

Next, we rotate that 90 degrees (also known as transposing) for later use with melt:

>>> family_members.T
                   0       1       2       3       4
FamilyMember_1  Paul    Anna   Peter   Lewis  Jeremy
FamilyMember_2  Rene   Ruben  Calvin  George   Silke
FamilyMember_3        Olivia                  Selina

Then, we'll melt it:

>>> family_members.T.melt()
    variable   value
0          0    Paul
1          0    Rene
2          0
3          1    Anna
4          1   Ruben
5          1  Olivia
6          2   Peter
7          2  Calvin
8          2
9          3   Lewis
10         3  George
11         3
12         4  Jeremy
13         4   Silke
14         4  Selina

Now we need to remove the empty items. We could do that like this:

x = family_members.T.melt()
x = x[x['values'] != '']

...but that's multiple lines, which won't do in a one-liner. So we can use pipe with a lambda function to achieve exactly this in a one-liner fashion:

>>> family_members.T.melt().pipe(lambda x: x[x['value'] != ''])
    variable   value
0          0    Paul
1          0    Rene
3          1    Anna
4          1   Ruben
5          1  Olivia
6          2   Peter
7          2  Calvin
9          3   Lewis
10         3  George
12         4  Jeremy
13         4   Silke
14         4  Selina

Then we can group by the variable column as it groups together perfectly those names that need to go together:

>>> g = family_members.T.melt().pipe(lambda x: x[x['value'] != '']).groupby('variable')
>>> g
<pandas.core.groupby.generic.DataFrameGroupBy object at 0x12b131e50>

# That's not very useful, so we can convert it to a list to have a peek at what's inside:
>>> list(g)
[(0,
     variable value
  0         0  Paul
  1         0  Rene),
 (1,
     variable   value
  3         1    Anna
  4         1   Ruben
  5         1  Olivia),
 (2,
     variable   value
  6         2   Peter
  7         2  Calvin),
 (3,
      variable   value
  9          3   Lewis
  10         3  George),
 (4,
      variable   value
  12         4  Jeremy
  13         4   Silke
  14         4  Selina)]

We need to convert each of those groups to a list of the names contained inside them. That's where agg(list) comes in:

>>> g['value'].agg(list)
variable
0               [Paul, Rene]
1      [Anna, Ruben, Olivia]
2            [Peter, Calvin]
3            [Lewis, George]
4    [Jeremy, Silke, Selina]
Name: value, dtype: object

Perfect. Now we need to put that column back on the dataframe. We could just assign it like normal:

g['names'] = g['value'].agg(list)

...but again, that would make a one-liner impossible. Fortunately, there's the assign function, which is built for this use-case:

>>> df.assign(names=g['value'].agg(list))
  Invited_guest  Age Origin FamilyMember_1 FamilyMember_2 FamilyMember_3                    names
0           Max   19     US           Paul           Rene                            [Paul, Rene]
1          Luca   21     UK           Anna          Ruben         Olivia    [Anna, Ruben, Olivia]
2          John   32    GER          Peter         Calvin                         [Peter, Calvin]
3         Biran   45    ITA          Lewis         George                         [Lewis, George]
4           Ian   34    FRA         Jeremy          Silke         Selina  [Jeremy, Silke, Selina]

(Note that assign is NOT in-place. It modifies a new copy of the dataframe, not the original).

Finally, we use the magic explode (only available in pandas 0.25 and newer):

>>> df.assign(names=g['value'].agg(list)).explode('names')
  Invited_guest  Age Origin FamilyMember_1 FamilyMember_2 FamilyMember_3   names
0           Max   19     US           Paul           Rene                   Paul
0           Max   19     US           Paul           Rene                   Rene
1          Luca   21     UK           Anna          Ruben         Olivia    Anna
1          Luca   21     UK           Anna          Ruben         Olivia   Ruben
1          Luca   21     UK           Anna          Ruben         Olivia  Olivia
2          John   32    GER          Peter         Calvin                  Peter
2          John   32    GER          Peter         Calvin                 Calvin
3         Biran   45    ITA          Lewis         George                  Lewis
3         Biran   45    ITA          Lewis         George                 George
4           Ian   34    FRA         Jeremy          Silke         Selina  Jeremy
4           Ian   34    FRA         Jeremy          Silke         Selina   Silke
4           Ian   34    FRA         Jeremy          Silke         Selina  Selina

And of course, remove the only FamilyMember_* columns:

>>> family_member_columns = df.filter(like='FamilyMember_').columns
>>> family_member_columns
Index(['FamilyMember_1', 'FamilyMember_2', 'FamilyMember_3'], dtype='object')

>>> df.assign(names=g['value'].agg(list)).explode('names').drop(family_member_columns, axis=1)


问:
How do I binary serialize a object using Compact Framework?
I have a object

```<code>struct _NETINFO { }
</code>```

and I want to convert it to a Byte[] using Compact Framework, I tried the following without sucess:

```<code>_NETINFO info = new _NETINFO();
byte[] buffer = (byte[])info;
</code>```

And it doesn't work! The only other sugestion I found is to use the BinaryFormatter which isn't available in CF!

Any other sugestions?

答:
How complex is the struct?  For simple things where you don't have pointers to other stuff, it's pretty easy:

```<code>    var info = new _NETINFO();
    var buffer = new byte[Marshal.SizeOf(info)];
    var handle = GCHandle.Alloc(info, GCHandleType.Pinned);
    try
    {
        Marshal.Copy(handle.AddrOfPinnedObject(), buffer, 0, buffer.Length);
    }
    finally
    {
        handle.Free();
    }
</code>```

There's also a version using unsafe code that's shorter, but that requires turning on "allow unsafe code" and for some reason that makes some people panic.

Wish managed code allowed doing this without the copy (or the reverse - casting a byte array to a struct), but sadly it does not.

Body:
I have a object

struct _NETINFO { }

and I want to convert it to a Byte[] using Compact Framework, I tried the following without sucess:

_NETINFO info = new _NETINFO();
byte[] buffer = (byte[])info;

And it doesn't work! The only other sugestion I found is to use the BinaryFormatter which isn't available in CF!

Any other sugestions?

Body:
How complex is the struct?  For simple things where you don't have pointers to other stuff, it's pretty easy:

    var info = new _NETINFO();
    var buffer = new byte[Marshal.SizeOf(info)];
    var handle = GCHandle.Alloc(info, GCHandleType.Pinned);
    try
    {
        Marshal.Copy(handle.AddrOfPinnedObject(), buffer, 0, buffer.Length);
    }
    finally
    {
        handle.Free();
    }

There's also a version using unsafe code that's shorter, but that requires turning on "allow unsafe code" and for some reason that makes some people panic.

Wish managed code allowed doing this without the copy (or the reverse - casting a byte array to a struct), but sadly it does not.


问:
how to add an X=msgbox command using sendkeys vbs
when I try adding the " quotes in

```<code>X=msgbox"Writing",48,"Title"
</code>```

but the quotes wont recognise.

I've tried using {} but that doesn't help either?

答:
you have to put in chr(34) thats quotes so you should be using the code vvv</p>
```<code>thewshkey.sendkeys "x=msgbox" & Chr(34) & "writing" & Chr(34) & ",48," & Chr(34) & "Title" & Chr(34)
</code>```

Body:
when I try adding the " quotes in

X=msgbox"Writing",48,"Title"

but the quotes wont recognise.

I've tried using {} but that doesn't help either?

Body:
you have to put in chr(34) thats quotes so you should be using the code vvv

thewshkey.sendkeys "x=msgbox" & Chr(34) & "writing" & Chr(34) & ",48," & Chr(34) & "Title" & Chr(34)


问:
Drop rows of df with fewer entries
I'm working currently with pandas in python.

I've got a dataset of customers (user_id on column1) and of the item they bought (column2).

Example dataset:

ID_user
ID_item

0
1

0
2

0
3

1
2

2
1

3
3

...
...

Now I want only to focus on customers, which have bought more than 10 items. How can I create a new dataframe with pandas and drop all other customers with less than 10 items bought?

Thank you very much!

答:
You can try groupby with transform then filter it

```<code>n = 10
cond = df.groupby('ID_user')['ID_item'].transform('sum')
out = df[cond>=n].copy()
</code>```

Title: Drop rows of df with fewer entries

Body:
You can try groupby with transform then filter it

n = 10
cond = df.groupby('ID_user')['ID_item'].transform('sum')
out = df[cond>=n].copy()


问:
How can I use a Timer of 2 seconds inside a fragment?
This is my Fragment.kt

class SplashFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        return inflater.inflate(R.layout.fragment_splash, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
            // My Timer
            Timer().schedule(object : TimerTask() {
                override fun run() {
                    findNavController().navigate(SplashFragmentDirections.actionSplashFragmentToHomeFragment()))
                }
            }, 2000)

    }
}
```
<p><code>This is my Logcat error</code></p>
```2022-02-06 20:37:34.755 27478-27510/com.finite.livelocationtest E/AndroidRuntime: FATAL EXCEPTION: Timer-0
    Process: com.finite.livelocationtest, PID: 27478
    java.lang.NullPointerException: Can't toast on a thread that has not called Looper.prepare()
        at com.android.internal.util.Preconditions.checkNotNull(Preconditions.java:157)
        at android.widget.Toast.getLooper(Toast.java:179)
        at android.widget.Toast.<init>(Toast.java:164)
        at android.widget.Toast.makeText(Toast.java:492)
        at android.widget.Toast.makeText(Toast.java:480)
        at com.finite.livelocationtest.ui.fragment.SplashFragment$onViewCreated$1.run(SplashFragment.kt:31)
        at java.util.TimerThread.mainLoop(Timer.java:562)
        at java.util.TimerThread.run(Timer.java:512)
```

What do I want to achieve?

I want to go from this fragment to the next fragment after a time of 2 seconds time, please let me know any possible way to achieve this.

答: The exception that you have included tells me you are trying to display a Toast on a non-UI thread. I'm not seeing any toast call in your example, bud please note that you CANNOT show a Toast on non-UI thread. You need to call Toast.makeText() (and most other functions dealing with the UI) from within the main thread.

Body:
This is my Fragment.kt

class SplashFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        return inflater.inflate(R.layout.fragment_splash, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
            // My Timer
            Timer().schedule(object : TimerTask() {
                override fun run() {
                    findNavController().navigate(SplashFragmentDirections.actionSplashFragmentToHomeFragment()))
                }
            }, 2000)

    }
}

This is my Logcat error

2022-02-06 20:37:34.755 27478-27510/com.finite.livelocationtest E/AndroidRuntime: FATAL EXCEPTION: Timer-0
    Process: com.finite.livelocationtest, PID: 27478
    java.lang.NullPointerException: Can't toast on a thread that has not called Looper.prepare()
        at com.android.internal.util.Preconditions.checkNotNull(Preconditions.java:157)
        at android.widget.Toast.getLooper(Toast.java:179)
        at android.widget.Toast.<init>(Toast.java:164)
        at android.widget.Toast.makeText(Toast.java:492)
        at android.widget.Toast.makeText(Toast.java:480)
        at com.finite.livelocationtest.ui.fragment.SplashFragment$onViewCreated$1.run(SplashFragment.kt:31)
        at java.util.TimerThread.mainLoop(Timer.java:562)
        at java.util.TimerThread.run(Timer.java:512)

What do I want to achieve?

I want to go from this fragment to the next fragment after a time of 2 seconds time, please let me know any possible way to achieve this.