问:
Python3: Why is my else statement activating regardless of multiple if statements being true
```<code>tweet = ''
tweet = input('Enter a tweet (160 characters or less):\n')

if len(tweet) <= 160:
    if 'LOL' in tweet:
        print('Laugh out loud')
    if 'BFN' in tweet:
        print('Bye for now')
    if 'BRB' in tweet:
        print('Be right back')
    if 'IRL' in tweet:
        print('In real life')
    if 'FTW' in tweet:
        print('For the win')
    if 'LMFAO' in tweet:
        print('Laugh my F**king a** off')
    if 'LMAO' in tweet:
        print('Laugh my a** off')
    else:
        print('You didn\'t use any abbreviations')
elif len(tweet) == 0:
    print('Wow, such empty')
elif len(tweet) > 160:
    print('Your tweet is over 160 characters')
</code>```

So, for example if I run this program and input:
LOL BRB

The output is:
Laugh out loud
Be right back
You didn't use any abbreviations

Whereas the output I want for that input is:
Laugh out loud
Be right back

As far as I can tell the indentation is correct. Also we haven't gone over the 'break' or 'enumerate' functions, so we are not expected to use these to attain the desired result.

Thank you for the help!!

This is the code in working order after everyone's help:

```<code>tweet = ''
tweet = input('Enter a tweet (160 characters or less):\n')

tweet_abbrev = False

if len(tweet) <= 160:
    if 'LOL' in tweet:
        tweet_abbrev = True
        print('Laugh out loud')
    if 'BFN' in tweet:
        tweet_abbrev = True
        print('Bye for now')
    if 'BRB' in tweet:
        tweet_abbrev = True
        print('Be right back')
    if 'IRL' in tweet:
        tweet_abbrev = True
        print('In real life')
    if 'FTW' in tweet:
        tweet_abbrev = True
        print('For the win')
    if 'LMFAO' in tweet:
        tweet_abbrev = True
        print('Laugh my F**king a** off')
    if 'LMAO' in tweet:
        tweet_abbrev = True
        print('Laugh my a** off')
    if not tweet_abbrev:
        print('You didn\'t use any abbreviations')
if len(tweet) == 0:
    print('Wow, such empty')
elif len(tweet) > 160:
    print('Your tweet is over 160 characters')
</code>```

Thank you everyone for the quick responses!!!

答:
I know it may be not so efficient, but you may initialize a flag

```<code>tweet = ''
tweet = input('Enter a tweet (160 characters or less):\n')
flag = 0
if len(tweet) <= 160:
    if 'LOL' in tweet:
        print('Laugh out loud')
        flag = 1;
    if 'BFN' in tweet:
        print('Bye for now')
        flag = 1;
    if 'BRB' in tweet:
        print('Be right back')
        flag = 1;
    if 'IRL' in tweet:
        print('In real life')
        flag = 1;
    if 'FTW' in tweet:
        print('For the win')
        flag = 1;
    if 'LMFAO' in tweet:
        print('Laugh my F**king a** off')
        flag = 1;
    if 'LMAO' in tweet:
        print('Laugh my a** off')
        flag = 1;
    elif flag==0:
        print('You didn\'t use any abbreviations')
elif len(tweet) == 0:
    print('Wow, such empty')
elif len(tweet) > 160:
    print('Your tweet is over 160 characters')
</code>```

Body:
tweet = ''
tweet = input('Enter a tweet (160 characters or less):\n')

if len(tweet) <= 160:
    if 'LOL' in tweet:
        print('Laugh out loud')
    if 'BFN' in tweet:
        print('Bye for now')
    if 'BRB' in tweet:
        print('Be right back')
    if 'IRL' in tweet:
        print('In real life')
    if 'FTW' in tweet:
        print('For the win')
    if 'LMFAO' in tweet:
        print('Laugh my F**king a** off')
    if 'LMAO' in tweet:
        print('Laugh my a** off')
    else:
        print('You didn\'t use any abbreviations')
elif len(tweet) == 0:
    print('Wow, such empty')
elif len(tweet) > 160:
    print('Your tweet is over 160 characters')

So, for example if I run this program and input:
LOL BRB

The output is:
Laugh out loud
Be right back
You didn't use any abbreviations

Whereas the output I want for that input is:
Laugh out loud
Be right back

As far as I can tell the indentation is correct. Also we haven't gone over the 'break' or 'enumerate' functions, so we are not expected to use these to attain the desired result.

Thank you for the help!!

This is the code in working order after everyone's help:

tweet = ''
tweet = input('Enter a tweet (160 characters or less):\n')

tweet_abbrev = False

if len(tweet) <= 160:
    if 'LOL' in tweet:
        tweet_abbrev = True
        print('Laugh out loud')
    if 'BFN' in tweet:
        tweet_abbrev = True
        print('Bye for now')
    if 'BRB' in tweet:
        tweet_abbrev = True
        print('Be right back')
    if 'IRL' in tweet:
        tweet_abbrev = True
        print('In real life')
    if 'FTW' in tweet:
        tweet_abbrev = True
        print('For the win')
    if 'LMFAO' in tweet:
        tweet_abbrev = True
        print('Laugh my F**king a** off')
    if 'LMAO' in tweet:
        tweet_abbrev = True
        print('Laugh my a** off')
    if not tweet_abbrev:
        print('You didn\'t use any abbreviations')
if len(tweet) == 0:
    print('Wow, such empty')
elif len(tweet) > 160:
    print('Your tweet is over 160 characters')

Thank you everyone for the quick responses!!!

Body:
I know it may be not so efficient, but you may initialize a flag

tweet = ''
tweet = input('Enter a tweet (160 characters or less):\n')
flag = 0
if len(tweet) <= 160:
    if 'LOL' in tweet:
        print('Laugh out loud')
        flag = 1;
    if 'BFN' in tweet:
        print('Bye for now')
        flag = 1;
    if 'BRB' in tweet:
        print('Be right back')
        flag = 1;
    if 'IRL' in tweet:
        print('In real life')
        flag = 1;
    if 'FTW' in tweet:
        print('For the win')
        flag = 1;
    if 'LMFAO' in tweet:
        print('Laugh my F**king a** off')
        flag = 1;
    if 'LMAO' in tweet:
        print('Laugh my a** off')
        flag = 1;
    elif flag==0:
        print('You didn\'t use any abbreviations')
elif len(tweet) == 0:
    print('Wow, such empty')
elif len(tweet) > 160:
    print('Your tweet is over 160 characters')


来源: stackexchange

问:
SSH: what is the difference between user:~ and user:#
I have come across someone who when using ssh after logging in uses the command 'cd /' as soon as they log in. I'm trying to find out what the difference is and cannot really find an answer anywhere. I have added a picture to hopefully clear up the exact thing I am looking for:
example

Sorry if this is a stupid question but it has been on my mind for a while now and I would like to know the difference.

Thank you

答:
```<code>~  current user home directory
~user1 home directory of user1
/ root directory
</code>```

ContentLicense: CC BY-SA 4.0


问:
Python - 2 Equations In 1 Loop
I'm a beginner with Python and trying to learn how to put 2 equations into 1 loop.

```<code>months = paymentTerm * 12
startingMonth = 1
while startingMonth <= months :
    print(startingMonth)
    startingMonth = startingMonth + 1

principal = principalAmount
startingPrincipal = principalAmount - monthlyInterest
while startingPrincipal <= principal :
    print(startingPrincipal)
    startingPrincipal = startingPrincipal - monthlyInterest
</code>```

Any ideas on how? Essentially I want the outputs to print side by side while using the \t\t function because the values for my principal are printing after the months, but I want them to be side by side. Thank you!!

答:
Zero, Welcome!

First, this code won't run -- Please considering posting code that runs (although if it doesn't that's fine but your question should reflect that issue).  Second, this problem can not be solve the way you think it can (as it appears to me).

This is probably the closest approximation of what you are looking for.  By declaring the booleans up from, you can determine if you should start that loop, and at each iteration, it can be determined which process to apply.

```<code>months = paymentTerm * 12
startingMonth = 1

t: bool = startingMonth <= months
p: bool = startingPrincipal <= principal

while t or p:

    if t:
        print(startingMonth)
        startingMonth += 1

    if p:
        print(startingPrincipal)
        startingPrincipal -= monthlyInterest

    t = startingMonth <= months
    p = startingPrincipal <= principal
</code>```

you can also use the fancy walrus operator too!

```<code>months = paymentTerm * 12
startingMonth = 1

while (t := startingMonth <= months) or (p := startingPrincipal <= principal):

    if t:
        print(startingMonth)
        startingMonth += 1

    if p:
        print(startingPrincipal)
        startingPrincipal -= monthlyInterest
</code>```

Title: Python - 2 Equations In 1 Loop

Body:
I'm a beginner with Python and trying to learn how to put 2 equations into 1 loop.

months = paymentTerm * 12
startingMonth = 1
while startingMonth <= months :
    print(startingMonth)
    startingMonth = startingMonth + 1

principal = principalAmount
startingPrincipal = principalAmount - monthlyInterest
while startingPrincipal <= principal :
    print(startingPrincipal)
    startingPrincipal = startingPrincipal - monthlyInterest

Any ideas on how? Essentially I want the outputs to print side by side while using the \t\t function because the values for my principal are printing after the months, but I want them to be side by side. Thank you!!

Body:
Zero, Welcome!

First, this code won't run -- Please considering posting code that runs (although if it doesn't that's fine but your question should reflect that issue).  Second, this problem can not be solve the way you think it can (as it appears to me).

This is probably the closest approximation of what you are looking for.  By declaring the booleans up from, you can determine if you should start that loop, and at each iteration, it can be determined which process to apply.

months = paymentTerm * 12
startingMonth = 1

t: bool = startingMonth <= months
p: bool = startingPrincipal <= principal

while t or p:

    if t:
        print(startingMonth)
        startingMonth += 1

    if p:
        print(startingPrincipal)
        startingPrincipal -= monthlyInterest

    t = startingMonth <= months
    p = startingPrincipal <= principal

you can also use the fancy walrus operator too!

months = paymentTerm * 12
startingMonth = 1

while (t := startingMonth <= months) or (p := startingPrincipal <= principal):

    if t:
        print(startingMonth)
        startingMonth += 1

    if p:
        print(startingPrincipal)
        startingPrincipal -= monthlyInterest


问:
How to get FDQuery result?
Hi guys I have a few forms in my application and I have a test button where I want to fire a query taken from another unit. Here is my code:

```<code>procedure TForm1.Button7Click(Sender: TObject);
var test : string;
begin
// test :=  Unit1.DataModule1.FDQuery2.Open.ToString;
 // Unit1.DataModule1.FDQuery2.ExecSQL;
 // test.ToString;
 // ShowMessage(Unit1.DataModule1.FDQuery2.Open);
 // Unit1.DataModule1.FDQuery2.Active := true;
  Unit1.DataModule1.FDQuery2.SQL.Text := 'SELECT CURRENT_DATE';
  Unit1.DataModule1.FDQuery2.Open();
  // Writeln(test);
end;
</code>```

basically I want to be able to for example take the result array or whatever datatype returns and assign them for example to a TEdit and then change it and so on. I wanted to show the result as a string but could not convert it properly. How would you the store the response? Also please correct my calls if there is something wrong - because my TFDQuery2 has the same argument like SQL.TEXT. Is it possible to just fire that query and get the result in a way that I can show it or use it?

答:
After TFDQuery.Open() has executed the SELECT query, you can use the TFDQuery.Fields property to access the returned field values, eg:

procedure TForm1.Button7Click(Sender: TObject);
var
  test : string;
begin
  Unit1.DataModule1.FDQuery2.SQL.Text := 'SELECT CURRENT_DATE';
  Unit1.DataModule1.FDQuery2.Open();
  test := Unit1.DataModule1.FDQuery2.Fields[0].AsString;
  Edit1.Text := test;
  Unit1.DataModule1.FDQuery2.Close();
end;
```

Title: How to get FDQuery result?

Body:
Hi guys I have a few forms in my application and I have a test button where I want to fire a query taken from another unit. Here is my code:

procedure TForm1.Button7Click(Sender: TObject);
var test : string;
begin
// test :=  Unit1.DataModule1.FDQuery2.Open.ToString;
 // Unit1.DataModule1.FDQuery2.ExecSQL;
 // test.ToString;
 // ShowMessage(Unit1.DataModule1.FDQuery2.Open);
 // Unit1.DataModule1.FDQuery2.Active := true;
  Unit1.DataModule1.FDQuery2.SQL.Text := 'SELECT CURRENT_DATE';
  Unit1.DataModule1.FDQuery2.Open();
  // Writeln(test);
end;

basically I want to be able to for example take the result array or whatever datatype returns and assign them for example to a TEdit and then change it and so on. I wanted to show the result as a string but could not convert it properly. How would you the store the response? Also please correct my calls if there is something wrong - because my TFDQuery2 has the same argument like SQL.TEXT. Is it possible to just fire that query and get the result in a way that I can show it or use it?


问:
MS access Query with in and parameter
I need to create a query in MS access where the parameter is a list (given by me).

This works In ("2209487";"2102669";"2727930";"3727550"), but if I try to put a parameter inside the "IN" like this: In ([NUM]) It doesn't return a result!

I write 2209487";"2102669";"2727930";"3727550 when the parameter window appears.

PS: my laptop is in European Portuguese so I use the ";"

答:
You can't use a "list" or "multiple" values for this. But you CAN do this in the where clause of hte form (or report).

First, remove any paramters for the form/report. You want to be able to open/launch the form/report WITHOUT any prompts from the query. In fact, what follows will even work if you based the form/report directly on the table.

So, you can do this:

```<code>dim strInvoices    as string

strInvoices = InputBox("Enter invoice numbers ',' between each")

dim strWhere as string

strWhere = "InvoiceNumber in (" & strInvoices & ")"

docmd.OpenReport "frmInvoices",,,strWhere
</code>```

So, you can provide a list as per above and use the "in"

the IN clause is this

```<code>  InvoiceNumber in (234,433,555)
</code>```

So, you can pass the conditions as a "where" clause to a open form or report.

Title: MS access Query with in and parameter

Body:
You can't use a "list" or "multiple" values for this. But you CAN do this in the where clause of hte form (or report).

First, remove any paramters for the form/report. You want to be able to open/launch the form/report WITHOUT any prompts from the query. In fact, what follows will even work if you based the form/report directly on the table.

So, you can do this:

dim strInvoices    as string

strInvoices = InputBox("Enter invoice numbers ',' between each")

dim strWhere as string

strWhere = "InvoiceNumber in (" & strInvoices & ")"

docmd.OpenReport "frmInvoices",,,strWhere

So, you can provide a list as per above and use the "in"

the IN clause is this

  InvoiceNumber in (234,433,555)

So, you can pass the conditions as a "where" clause to a open form or report.


问:
Libreoffice Writer lets the computer crash when editing the file properties
In LibreOffice Writer (6.4.3.2 x64, Windows 10.0) I try to edit the file properties, particularly the custom properties. Trying anything (adding an attribute, deleting one, editing one) lets the computer crash with a blue screen. That happens when I click the save button in the File Properties dialog.

Details:
error reason is igdkmd64.sys, stop code is PAGE_FAULT_IN_NONE_PAGED_AREA

I tried it with and without Java RE, both crashed.

Does anybody know what is wrong?

Edit 2020-05-08:

In Tools --> Options --> LibreOffice --> View --> GraphicsOutput the checkbox "Use OpenGL for all rendering" was checked. No more crashes if I uncheck it

答:
I had this same..
Use OpenGL for all rendering works.


问:
SQL function appears to be stuck in loop
I am currently working on a function that should be returning 3 business days prior to the date sent as an argument to the function.

I am somewhat new to functions in SQL and I believe my logic is sound but I am stuck.

I have 2 tables I made. One contains all the weekend dates and one contains all the holiday dates. The function is meant to take in a single date and then using 2 while loops calculate 3 business days prior to the date submitted and then return that new date into my select statement.

Here is the function in quesion:

```<code>FUNCTION [dbo].[lessThreeBD](@WORKING_DT DATE)
RETURNS DATE
AS
BEGIN
DECLARE @ThreeBD DATE
DECLARE @COUNTER INT
SET @COUNTER = 0

WHILE @COUNTER < 4
SET @ThreeBD = @WORKING_DT
BEGIN
    WHILE CASE WHEN (SELECT TOP 1 HOL.DATE from DATABASE.dbo.Holidays HOL where HOL.DATE = CAST(@WORKING_DT AS DATE)) IS NULL THEN 'NOT HOLIDAY' ELSE 'HOLIDAY' END = 'HOLIDAY'
    OR CASE WHEN (SELECT TOP 1 WKND.DATE from DATABASE.dbo.Weekends WKND where WKND.DATE = CAST(@WORKING_DT AS DATE)) IS NULL THEN 'WEEKDAY' ELSE 'WEEKEND' END = 'WEEKEND'
    BEGIN
        SET @WORKING_DT = DATEADD(DAY, -1, @WORKING_DT)
    END
    SET @WORKING_DT = DATEADD(DAY, -1, @WORKING_DT)
    SET @COUNTER  = @COUNTER + 1
SET @ThreeBD = @WORKING_DT
END
RETURN @ThreeBD
END
</code>```

However when I test this with a single date it appears to be locked up:

Test line:

```<code>SELECT DATABASE.dbo.lessThreeBD('2020-05-24') AS TESTING
</code>```

This line should return the 20th.

Any idea what I might be doing wrong here?

Keep in mind that both the holiday and weekend tables work perfectly fine. I have already tested the case statements and I get the expected results with each case statement.

答:
After fixing the null issue and the issue with SET not being inside of BEGIN I had to make a couple more changes to make this work accuratly.

The final function is as follows for anyone who would like it for their own use:

```<code>FUNCTION [dbo].[lessThreeBD](@WORKING_DT DATE)
RETURNS DATE
AS
BEGIN
    DECLARE @COUNTER INT
    SET @COUNTER = 0

    WHILE @COUNTER < 3
    BEGIN
        SET @WORKING_DT = DATEADD(DAY, -1, @WORKING_DT)
        SET @COUNTER  = @COUNTER + 1
        WHILE (SELECT SQL_VARIANT_PROPERTY((SELECT TOP 1 HOL.DATE as CT from crmCAST.dbo.Holidays HOL where HOL.DATE = CAST(@WORKING_DT AS DATE)), 'BaseType')) IS NOT NULL
        OR (((DATEPART(DW, @WORKING_DT) - 1 ) + @@DATEFIRST ) % 7) IN (0,6)
        BEGIN
            SET @WORKING_DT = DATEADD(DAY, -1, @WORKING_DT)
        END
    END
RETURN @WORKING_DT
END
</code>```

I was able to remove my weekend table with the use of (((DATEPART(DW, @WORKING_DT) - 1 ) + @@DATEFIRST ) % 7) IN (0,6) that will tell me if the date is a weekend so the only thing you will need is a table that has a list of holidays your business observes so you can have an accurate 3 business day return.

Body:
I am currently working on a function that should be returning 3 business days prior to the date sent as an argument to the function.

I am somewhat new to functions in SQL and I believe my logic is sound but I am stuck.

I have 2 tables I made. One contains all the weekend dates and one contains all the holiday dates. The function is meant to take in a single date and then using 2 while loops calculate 3 business days prior to the date submitted and then return that new date into my select statement.

Here is the function in quesion:

FUNCTION [dbo].[lessThreeBD](@WORKING_DT DATE)
RETURNS DATE
AS
BEGIN
DECLARE @ThreeBD DATE
DECLARE @COUNTER INT
SET @COUNTER = 0

WHILE @COUNTER < 4
SET @ThreeBD = @WORKING_DT
BEGIN
    WHILE CASE WHEN (SELECT TOP 1 HOL.DATE from DATABASE.dbo.Holidays HOL where HOL.DATE = CAST(@WORKING_DT AS DATE)) IS NULL THEN 'NOT HOLIDAY' ELSE 'HOLIDAY' END = 'HOLIDAY'
    OR CASE WHEN (SELECT TOP 1 WKND.DATE from DATABASE.dbo.Weekends WKND where WKND.DATE = CAST(@WORKING_DT AS DATE)) IS NULL THEN 'WEEKDAY' ELSE 'WEEKEND' END = 'WEEKEND'
    BEGIN
        SET @WORKING_DT = DATEADD(DAY, -1, @WORKING_DT)
    END
    SET @WORKING_DT = DATEADD(DAY, -1, @WORKING_DT)
    SET @COUNTER  = @COUNTER + 1
SET @ThreeBD = @WORKING_DT
END
RETURN @ThreeBD
END

However when I test this with a single date it appears to be locked up:

Test line:

SELECT DATABASE.dbo.lessThreeBD('2020-05-24') AS TESTING

This line should return the 20th.

Any idea what I might be doing wrong here?

Keep in mind that both the holiday and weekend tables work perfectly fine. I have already tested the case statements and I get the expected results with each case statement.

Body:
After fixing the null issue and the issue with SET not being inside of BEGIN I had to make a couple more changes to make this work accuratly.

The final function is as follows for anyone who would like it for their own use:

FUNCTION [dbo].[lessThreeBD](@WORKING_DT DATE)
RETURNS DATE
AS
BEGIN
    DECLARE @COUNTER INT
    SET @COUNTER = 0

    WHILE @COUNTER < 3
    BEGIN
        SET @WORKING_DT = DATEADD(DAY, -1, @WORKING_DT)
        SET @COUNTER  = @COUNTER + 1
        WHILE (SELECT SQL_VARIANT_PROPERTY((SELECT TOP 1 HOL.DATE as CT from crmCAST.dbo.Holidays HOL where HOL.DATE = CAST(@WORKING_DT AS DATE)), 'BaseType')) IS NOT NULL
        OR (((DATEPART(DW, @WORKING_DT) - 1 ) + @@DATEFIRST ) % 7) IN (0,6)
        BEGIN
            SET @WORKING_DT = DATEADD(DAY, -1, @WORKING_DT)
        END
    END
RETURN @WORKING_DT
END

I was able to remove my weekend table with the use of (((DATEPART(DW, @WORKING_DT) - 1 ) + @@DATEFIRST ) % 7) IN (0,6) that will tell me if the date is a weekend so the only thing you will need is a table that has a list of holidays your business observes so you can have an accurate 3 business day return.


问:
How to establish connection to SSAS Tabular Model using Python
I am trying to establish connection to Azure SSAS using Python .Below is my python script snippet ,when I execute the Python script it error out with listed error attached below:
I checked my C drive for ADOMD client and unable to find it.
I am using SSAS 2017.
Can you please help to resolve the error in the screenshot ?

I am referring the Code snippet from this link :
https://github.com/yehoshuadimarsky/python-ssas

I also referred the link to understand about 'Microsoft.AnalysisServices.AdomdClient' error

https://social.technet.microsoft.com/Forums/en-US/47d0b992-3c10-4851-b2a5-9f72d2c0976e/could-not-load-file-or-assembly-microsoftanalysisservicesadomdclient-error?forum=sqlanalysisservices

答:
The Pyadomd package might help you with your problem:

Pyadomd


问:
Plot the longest transcript in GenomicRanges with ggbio
I am trying to plot an specific region using ggbio. I am using the below code that produced my desire output, except that it contains several transcript. Is it possible to only plot the longest transcript? I've not been able to access the genomic ranges object within Homo.sapiens that I assume contains this information.

```<code>library(ggbio)
library(Homo.sapiens)

range <- GRanges("chr10"  , IRanges(start = 78000000 , end = 79000000))
p.txdb <- autoplot(Homo.sapiens, which = range)
p.txdb
</code>```

答:
Here is a solution that involves filtering TxDb.Hsapiens.UCSC.hg19.knownGene on the longest transcript by gene_id (which does remove genes without gene_id):

suppressPackageStartupMessages({
    invisible(lapply(c("ggbio", "biovizBase", "data.table",
        "TxDb.Hsapiens.UCSC.hg19.knownGene",
        "org.Hs.eg.db"),
        require, character.only = TRUE))})
txdb <- TxDb.Hsapiens.UCSC.hg19.knownGene

# retrieve transcript lengths
txlen <- transcriptLengths(txdb, with.utr5_len=TRUE, with.utr3_len=TRUE)
setDT(txlen)
txlen$len <- rowSums(as.matrix(txlen[, .(tx_len, utr5_len, utr3_len)]))
setkey(txlen, gene_id, len, tx_id)

# filter longesttranscript by gene_id
ltx <- txlen[!is.na(gene_id)][, tail(.SD,1), by=gene_id]$tx_id

# filter txdb object
txb <- as.list(txdb)
txb$transcripts <- txb$transcripts[txb$transcripts$tx_id %in% ltx, ]
txb$splicings <- txb$splicings[txb$splicings$tx_id %in% ltx,]
txb$genes <- txb$genes[txb$genes$tx_id %in% ltx,]
txb <- do.call(makeTxDb, txb)

# plot according to vignette, chapter 2.2.5
range <- GRanges("chr10", IRanges(start = 78000000 , end = 79000000))
gr.txdb <- crunch(txb, which = range)
#> Parsing transcripts...
#> Parsing exons...
#> Parsing cds...
#> Parsing utrs...
#> ------exons...
#> ------cdss...
#> ------introns...
#> ------utr...
#> aggregating...
#> Done
colnames(values(gr.txdb))[4] <- "model"
grl <- split(gr.txdb, gr.txdb$gene_id)
symbols <- select(org.Hs.eg.db, keys=names(grl), columns="SYMBOL", keytype="ENTREZID")
#> 'select()' returned 1:1 mapping between keys and columns
names(grl) <- symbols[match(symbols$ENTREZID, names(grl), nomatch=0),"SYMBOL"]
autoplot(grl, aes(type = "model"), gap.geom="chevron")
#> Constructing graphics...
```

Created on 2020-05-29 by the reprex package (v0.3.0)

Edit:
To get gene symbols instead of gene (or transcript) ids, just replace the names of grl with the associated gene symbols, e.g. via org.Hs.eg.db, or any other resource that matches them up.

Body:
I am trying to plot an specific region using ggbio. I am using the below code that produced my desire output, except that it contains several transcript. Is it possible to only plot the longest transcript? I've not been able to access the genomic ranges object within Homo.sapiens that I assume contains this information.

library(ggbio)
library(Homo.sapiens)

range <- GRanges("chr10"  , IRanges(start = 78000000 , end = 79000000))
p.txdb <- autoplot(Homo.sapiens, which = range)
p.txdb

Body:
Here is a solution that involves filtering TxDb.Hsapiens.UCSC.hg19.knownGene on the longest transcript by gene_id (which does remove genes without gene_id):

suppressPackageStartupMessages({
    invisible(lapply(c("ggbio", "biovizBase", "data.table",
        "TxDb.Hsapiens.UCSC.hg19.knownGene",
        "org.Hs.eg.db"),
        require, character.only = TRUE))})
txdb <- TxDb.Hsapiens.UCSC.hg19.knownGene

# retrieve transcript lengths
txlen <- transcriptLengths(txdb, with.utr5_len=TRUE, with.utr3_len=TRUE)
setDT(txlen)
txlen$len <- rowSums(as.matrix(txlen[, .(tx_len, utr5_len, utr3_len)]))
setkey(txlen, gene_id, len, tx_id)

# filter longesttranscript by gene_id
ltx <- txlen[!is.na(gene_id)][, tail(.SD,1), by=gene_id]$tx_id

# filter txdb object
txb <- as.list(txdb)
txb$transcripts <- txb$transcripts[txb$transcripts$tx_id %in% ltx, ]
txb$splicings <- txb$splicings[txb$splicings$tx_id %in% ltx,]
txb$genes <- txb$genes[txb$genes$tx_id %in% ltx,]
txb <- do.call(makeTxDb, txb)

# plot according to vignette, chapter 2.2.5
range <- GRanges("chr10", IRanges(start = 78000000 , end = 79000000))
gr.txdb <- crunch(txb, which = range)
#> Parsing transcripts...
#> Parsing exons...
#> Parsing cds...
#> Parsing utrs...
#> ------exons...
#> ------cdss...
#> ------introns...
#> ------utr...
#> aggregating...
#> Done
colnames(values(gr.txdb))[4] <- "model"
grl <- split(gr.txdb, gr.txdb$gene_id)
symbols <- select(org.Hs.eg.db, keys=names(grl), columns="SYMBOL", keytype="ENTREZID")
#> 'select()' returned 1:1 mapping between keys and columns
names(grl) <- symbols[match(symbols$ENTREZID, names(grl), nomatch=0),"SYMBOL"]
autoplot(grl, aes(type = "model"), gap.geom="chevron")
#> Constructing graphics...

Created on 2020-05-29 by the reprex package (v0.3.0)

Edit:
To get gene symbols instead of gene (or transcript) ids, just replace the names of grl with the associated gene symbols, e.g. via org.Hs.eg.db, or any other resource that matches them up.


问:
Dask: Setup a Cluster where multiple machines can connect to
From the docs, there is a class called Cluster, but other than for the LocalCluster, I can not find any docs about how to setup a Cluster which accepts workers from different machines (as this is described for LocalClusterhere.

Are there some recommendations out there?

Related question: 1 (only reference on the docs as above)

答:
The answer is SSHCluster
It is based on asyncsshand can have multiple workers per machine in the cluster. Make sure to have pre requirements installed.


问:
Memory Leak in C#
Is it ever possible in a managed system to leak memory when you make sure that all handles, things that implement IDispose are disposed?

Would there be cases where some variables are left out?

答:
Once all the references to an object are gone, the garbage collector will free that object on it's next pass. I wouldn't say it's impossible to leak memory but it's fairly difficult, in order to leak you'd have to have a reference to an object sitting around without realizing it.

For example if you instantiate objects into a list and then forget to remove them from the list when you're done AND forget to dispose them.

OwnerDisplayName: Joan Venge

ContentLicense: CC BY-SA 2.5

Title: Memory Leak in C#

LastEditorDisplayName: strager

OwnerDisplayName: Kevin Laity


问:
ModelFormSet to edit all entries for a model class
I have a simple model class:

```<code>class Category(BaseModel):
    categoryText = db.StringProperty()
    parentCat = db.IntegerProperty()
</code>```

I want to create a model formset to display all entries of category:

form class:

```<code>class CategoryForm(forms.ModelForm):
    categoryText = forms.CharField()
    class Meta:
        model = Category
</code>```

View.py

```<code>def showAllCategories:
    CategoryFormSet = modelformset_factory(Category)

    if request.POST:
       formset = CategoryFormSet(request.POST)
       if formset.is_valid():
           formset.save()

    else:
       formset = CategoryFormSet(Category.objects.all())
     return render_to_response('showcat.html',{'formset':formset})
</code>```

not sure what I'm doing wrong: I get this error:
    'StringProperty' object has no attribute 'editable'

This should be really simple but it's been a challenge.

答:
Try this:

view.py

```<code>def showAllCategories(request):
    CategoryFormSet = modelformset_factory(CategoryForm)
    if request.method=='POST':
        formset = CategoryFormset(request.POST)
        if formset.is_valid():
            ...
            formset.save()
            ...
    else:
        formset = CategoryFormset(queryset=Category.objects.all())
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a simple model class:

class Category(BaseModel):
    categoryText = db.StringProperty()
    parentCat = db.IntegerProperty()

I want to create a model formset to display all entries of category:

form class:

class CategoryForm(forms.ModelForm):
    categoryText = forms.CharField()
    class Meta:
        model = Category

View.py

def showAllCategories:
    CategoryFormSet = modelformset_factory(Category)

    if request.POST:
       formset = CategoryFormSet(request.POST)
       if formset.is_valid():
           formset.save()

    else:
       formset = CategoryFormSet(Category.objects.all())
     return render_to_response('showcat.html',{'formset':formset})

not sure what I'm doing wrong: I get this error:
    'StringProperty' object has no attribute 'editable'

This should be really simple but it's been a challenge.

Body:
Try this:

view.py

def showAllCategories(request):
    CategoryFormSet = modelformset_factory(CategoryForm)
    if request.method=='POST':
        formset = CategoryFormset(request.POST)
        if formset.is_valid():
            ...
            formset.save()
            ...
    else:
        formset = CategoryFormset(queryset=Category.objects.all())


问:
How to update version on Heroku?
I used the deploy on Heroku button of https://github.com/errbit/errbit .

Worked great for a long time (version 0.7.0-dev) , now I'm getting a deprecation warning from GitHub:

[GitHub API] Deprecation notice for authentication via URL query parameters

The instructions at https://github.com/errbit/errbit#upgrading doesn't seem to work with Heroku.

答:
Seems like the way to upgrade would be to git clone errbit at the tagged release version you want to run, and then use the heroku command line tool to add a git remote for your heroku app. From that point you would manage the upgrade by pushing to the heroku remote.

Here's a rough guide, but you'll want to be somewhat familiar with git and the heroku command line tools.

```<code>git clone git@github.com:errbit/errbit.git
cd errbit
heroku git:remote -a your-app-name
git push heroku origin/v0.9.0:master
</code>```

See also https://devcenter.heroku.com/articles/git#for-an-existing-heroku-app

Title: How to update version on Heroku?

Body:
Seems like the way to upgrade would be to git clone errbit at the tagged release version you want to run, and then use the heroku command line tool to add a git remote for your heroku app. From that point you would manage the upgrade by pushing to the heroku remote.

Here's a rough guide, but you'll want to be somewhat familiar with git and the heroku command line tools.

git clone git@github.com:errbit/errbit.git
cd errbit
heroku git:remote -a your-app-name
git push heroku origin/v0.9.0:master

See also https://devcenter.heroku.com/articles/git#for-an-existing-heroku-app


问:
Right place to garbage collect File type in dispose pattern
now there is a debate between my coworkers regarding where the C# File type needs to be handled. (https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-dispose)

Looking at the code below, currently File.Delete is within if(disposing) section, where it is considered for managed objects.  Some people believe it needs to be outside of the loop and need to be place for unmanaged objects.

```<code>~someService() => Dispose(false);

public void Dispose()
{
    Dispose(true);
    GC.SuppressFinalize(this);
    GC.Collect();
}

bool disposed = false;
protected virtual void Dispose(bool disposing)
{
    if (disposed)
    {
        return;
    }

    if (disposing)
    {
        // Dispose managed state (managed objects).
        tempFilePaths?.ToList().ForEach(f =>
        {
            if (File.Exists(f))
            {
                File.Delete(f);
            }
        });

        this._engine?.Dispose();
    }

    // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
    // TODO: set large fields to null.
    this._fields = null;

    disposed = true;
}
</code>```

答:
Just read carefully about the IDisposable pattern to understand what these "sections" mean and when they will be executed.

TL;DR

You don't use any existing references to managed objects outside of the if (disposing) block. In your example, tempFilePaths seems to be a field/property of the IEnumerable<string> type which is a managed object (an existing reference). So, the only correct place to access/use it is inside of the if (disposing) block.

Reason

The code outside of if (disposing) runs both on calling the public Dispose() method and when called by the finalizer.

The finalizer will be called on a special finalizer thread. It is not guaranteed that - at the time of the finalizer call - the tempFilePaths will be available at all. It could have been collected by the GC already, despite the object reference is held by your class instance. This is how the finalzers work.

If you want more background and more arguments while discussing with your team, please carefully read these blog posts by Eric Lippert (former C# compiler team member) about the finalizers:

When everything you know is wrong, part one

When everything you know is wrong, part two

Body:
now there is a debate between my coworkers regarding where the C# File type needs to be handled. (https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-dispose)

Looking at the code below, currently File.Delete is within if(disposing) section, where it is considered for managed objects.  Some people believe it needs to be outside of the loop and need to be place for unmanaged objects.

~someService() => Dispose(false);

public void Dispose()
{
    Dispose(true);
    GC.SuppressFinalize(this);
    GC.Collect();
}

bool disposed = false;
protected virtual void Dispose(bool disposing)
{
    if (disposed)
    {
        return;
    }

    if (disposing)
    {
        // Dispose managed state (managed objects).
        tempFilePaths?.ToList().ForEach(f =>
        {
            if (File.Exists(f))
            {
                File.Delete(f);
            }
        });

        this._engine?.Dispose();
    }

    // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
    // TODO: set large fields to null.
    this._fields = null;

    disposed = true;
}


问:
Script to remove Python comments/docstrings
Is there a Python script or tool available which can remove comments and docstrings from Python source?

It should take care of cases like:

```<code>"""
aas
"""
def f():
    m = {
        u'x':
            u'y'
        } # faake docstring ;)
    if 1:
        'string' >> m
    if 2:
        'string' , m
    if 3:
        'string' > m
</code>```

So at last I have come up with a simple script, which uses the tokenize module and removes comment tokens. It seems to work pretty well, except that I am not able to remove docstrings in all cases. See if you can improve it to remove docstrings.

```<code>import cStringIO
import tokenize

def remove_comments(src):
    """
    This reads tokens using tokenize.generate_tokens and recombines them
    using tokenize.untokenize, and skipping comment/docstring tokens in between
    """
    f = cStringIO.StringIO(src)
    class SkipException(Exception): pass
    processed_tokens = []
    last_token = None
    # go thru all the tokens and try to skip comments and docstrings
    for tok in tokenize.generate_tokens(f.readline):
        t_type, t_string, t_srow_scol, t_erow_ecol, t_line = tok

        try:
            if t_type == tokenize.COMMENT:
                raise SkipException()

            elif t_type == tokenize.STRING:

                if last_token is None or last_token[0] in [tokenize.INDENT]:
                    # FIXEME: this may remove valid strings too?
                    #raise SkipException()
                    pass

        except SkipException:
            pass
        else:
            processed_tokens.append(tok)

        last_token = tok

    return tokenize.untokenize(processed_tokens)
</code>```

Also I would like to test it on a very large collection of scripts with good unit test coverage. Can you suggest such a open source project?

答:
Here is a modification of Dan's solution to make it run for Python3 + also remove empty lines + make it ready-to-use:</p>
```<code>import io, tokenize, re
def remove_comments_and_docstrings(source):
    io_obj = io.StringIO(source)
    out = ""
    prev_toktype = tokenize.INDENT
    last_lineno = -1
    last_col = 0
    for tok in tokenize.generate_tokens(io_obj.readline):
        token_type = tok[0]
        token_string = tok[1]
        start_line, start_col = tok[2]
        end_line, end_col = tok[3]
        ltext = tok[4]
        if start_line > last_lineno:
            last_col = 0
        if start_col > last_col:
            out += (" " * (start_col - last_col))
        if token_type == tokenize.COMMENT:
            pass
        elif token_type == tokenize.STRING:
            if prev_toktype != tokenize.INDENT:
                if prev_toktype != tokenize.NEWLINE:
                    if start_col > 0:
                        out += token_string
        else:
            out += token_string
        prev_toktype = token_type
        last_col = end_col
        last_lineno = end_line
    out = '\n'.join(l for l in out.splitlines() if l.strip())
    return out
with open('test.py', 'r') as f:
    print(remove_comments_and_docstrings(f.read()))
</code>```

Body:
Is there a Python script or tool available which can remove comments and docstrings from Python source?

It should take care of cases like:

"""
aas
"""
def f():
    m = {
        u'x':
            u'y'
        } # faake docstring ;)
    if 1:
        'string' >> m
    if 2:
        'string' , m
    if 3:
        'string' > m

So at last I have come up with a simple script, which uses the tokenize module and removes comment tokens. It seems to work pretty well, except that I am not able to remove docstrings in all cases. See if you can improve it to remove docstrings.

import cStringIO
import tokenize

def remove_comments(src):
    """
    This reads tokens using tokenize.generate_tokens and recombines them
    using tokenize.untokenize, and skipping comment/docstring tokens in between
    """
    f = cStringIO.StringIO(src)
    class SkipException(Exception): pass
    processed_tokens = []
    last_token = None
    # go thru all the tokens and try to skip comments and docstrings
    for tok in tokenize.generate_tokens(f.readline):
        t_type, t_string, t_srow_scol, t_erow_ecol, t_line = tok

        try:
            if t_type == tokenize.COMMENT:
                raise SkipException()

            elif t_type == tokenize.STRING:

                if last_token is None or last_token[0] in [tokenize.INDENT]:
                    # FIXEME: this may remove valid strings too?
                    #raise SkipException()
                    pass

        except SkipException:
            pass
        else:
            processed_tokens.append(tok)

        last_token = tok

    return tokenize.untokenize(processed_tokens)

Also I would like to test it on a very large collection of scripts with good unit test coverage. Can you suggest such a open source project?

Body:
Here is a modification of Dan's solution to make it run for Python3 + also remove empty lines + make it ready-to-use:

import io, tokenize, re
def remove_comments_and_docstrings(source):
    io_obj = io.StringIO(source)
    out = ""
    prev_toktype = tokenize.INDENT
    last_lineno = -1
    last_col = 0
    for tok in tokenize.generate_tokens(io_obj.readline):
        token_type = tok[0]
        token_string = tok[1]
        start_line, start_col = tok[2]
        end_line, end_col = tok[3]
        ltext = tok[4]
        if start_line > last_lineno:
            last_col = 0
        if start_col > last_col:
            out += (" " * (start_col - last_col))
        if token_type == tokenize.COMMENT:
            pass
        elif token_type == tokenize.STRING:
            if prev_toktype != tokenize.INDENT:
                if prev_toktype != tokenize.NEWLINE:
                    if start_col > 0:
                        out += token_string
        else:
            out += token_string
        prev_toktype = token_type
        last_col = end_col
        last_lineno = end_line
    out = '\n'.join(l for l in out.splitlines() if l.strip())
    return out
with open('test.py', 'r') as f:
    print(remove_comments_and_docstrings(f.read()))


问:
How do nested transactions work with triggers and different isolation levels in SQL Server?
I need to answer two questions. Here's an overview:

I have 3 tables:

```<code>CREATE TABLE A(x INT)
CREATE TABLE B(x INT)
CREATE TABLE C(x INT)
</code>```

and 2 triggers:

```<code>ALTER TRIGGER ATr ON A
FOR INSERT AS
BEGIN
    SET TRANSACTION ISOLATION LEVEL SERIALIZABLE

    INSERT INTO B
        SELECT *
        FROM inserted;
    COMMIT
END

ALTER TRIGGER BTr ON B
FOR INSERT AS
BEGIN
    INSERT INTO C
        SELECT * FROM inserted;
END
</code>```

and the INSERT triggering the ATr trigger INSERT INTO A VALUES(3) is done on REPEATABLE READ isolation level, and the default isolation level for this database is READ COMMITTED.

And I need to answer two questions:

On which isolation level will the ATr trigger execute?

On which isolation level will the BTr trigger execute (if at all)?

I have problem understanding how these nested transactions are going to work. Will any transaction inside a LEVEL SERIALIZABLE transaction ever execute? Are they even nested in this case? What happens if a lower isolation level is inside a higher isolation level or the other way around?

答:
The behavior is documented here SET TRANSACTION ISOLATION LEVEL

And you can examine this behavior by running

```<code>select CASE transaction_isolation_level
WHEN 0 THEN 'Unspecified'
WHEN 1 THEN 'ReadUncomitted'
WHEN 2 THEN 'ReadCommitted'
WHEN 3 THEN 'Repeatable'
WHEN 4 THEN 'Serializable'
WHEN 5 THEN 'Snapshot' END AS transaction_isolation_level
from sys.dm_exec_requests
where session_id = @@spid
</code>```

wherever you are curious about the currently-active isolation level.

Body:
I need to answer two questions. Here's an overview:

I have 3 tables:

CREATE TABLE A(x INT)
CREATE TABLE B(x INT)
CREATE TABLE C(x INT)

and 2 triggers:

ALTER TRIGGER ATr ON A
FOR INSERT AS
BEGIN
    SET TRANSACTION ISOLATION LEVEL SERIALIZABLE

    INSERT INTO B
        SELECT *
        FROM inserted;
    COMMIT
END

ALTER TRIGGER BTr ON B
FOR INSERT AS
BEGIN
    INSERT INTO C
        SELECT * FROM inserted;
END

and the INSERT triggering the ATr trigger INSERT INTO A VALUES(3) is done on REPEATABLE READ isolation level, and the default isolation level for this database is READ COMMITTED.

And I need to answer two questions:

On which isolation level will the ATr trigger execute?

On which isolation level will the BTr trigger execute (if at all)?

I have problem understanding how these nested transactions are going to work. Will any transaction inside a LEVEL SERIALIZABLE transaction ever execute? Are they even nested in this case? What happens if a lower isolation level is inside a higher isolation level or the other way around?

Body:
The behavior is documented here SET TRANSACTION ISOLATION LEVEL

And you can examine this behavior by running

select CASE transaction_isolation_level
WHEN 0 THEN 'Unspecified'
WHEN 1 THEN 'ReadUncomitted'
WHEN 2 THEN 'ReadCommitted'
WHEN 3 THEN 'Repeatable'
WHEN 4 THEN 'Serializable'
WHEN 5 THEN 'Snapshot' END AS transaction_isolation_level
from sys.dm_exec_requests
where session_id = @@spid

wherever you are curious about the currently-active isolation level.


问:
Directshow recording/preview problem
I have a project where I need to record a video using DirectShow from a webcam, but I need to be able to stop recording while the preview continues to run.

I am using WPFMediaKit

http://wpfmediakit.codeplex.com/

The problem is that when I record a video the pause function also pauses the preview pane in the application

I am new to DirectShow, any suggestions how is can address this issue or a solution

Thank you very much.

P.S I use C# & WPF

答: I don't know about the WPFMediaKit, but basically when you want to start/stop recording while keeping the preview, you will need two graphs, and something to connect between those graphs. Take a look at the pdf document at the GMFBridge page.</p>

Title: Directshow recording/preview problem


问:
TextField label border position
I am making a form with several text fields. I need to have a label above each field displayed.I don't want to have to click in the field to show the text above each field. They need to be fixed.

Using label text, the label only shows when the user clicks in the field, I need that to be fixed.

I tried:

static TextField user_name() {
            return TextField(
                maxLines: 2,
                decoration: InputDecoration(
                  labelText: 'Full Name',
                  border: OutlineInputBorder(),
                ));
}
```

But only shows 'Full Name' when the user clicks on the field.

答:
You could use a TextFormField like so:

```<code>TextFormField(
  decoration: InputDecoration(
    floatingLabelBehavior:FloatingLabelBehavior.always,
  ),
);

</code>```

Title: TextField label border position

Body:
I am making a form with several text fields. I need to have a label above each field displayed.I don't want to have to click in the field to show the text above each field. They need to be fixed.

Using label text, the label only shows when the user clicks in the field, I need that to be fixed.

I tried:

static TextField user_name() {
            return TextField(
                maxLines: 2,
                decoration: InputDecoration(
                  labelText: 'Full Name',
                  border: OutlineInputBorder(),
                ));
}

But only shows 'Full Name' when the user clicks on the field.

Body:
You could use a TextFormField like so:

TextFormField(
  decoration: InputDecoration(
    floatingLabelBehavior:FloatingLabelBehavior.always,
  ),
);


问:
Understanding Array.isArray Polyfill
I was going through the polyfill of Array.isArray method on MDN, and this is what I found:

```<code>if (!Array.isArray) {
  Array.isArray = function(arg) {
    return Object.prototype.toString.call(arg) === '[object Array]';
  };
}
</code>```

While this works, I wonder why MDN hasn't listed the following as the polyfill for isArray?

```<code>if (!Array.isArray) {
  Array.isArray = function(arg) {
    return arg.constructor === Array;
  };
}
</code>```

Above code is a bit short and simpler. I wonder if there is any advantage of using MDN's implementation as compared to above one?

答:
One problem would be that a non-array object with a constructor property of Array would pass when it shouldn't:

// Bad polyfill, do not use
Array.isArray = function(arg) {
  return arg.constructor === Array;
};

const badObj = {};
badObj.constructor = Array;
console.log(Array.isArray(badObj));```

The above would be a very strange situation, but a polyfill must be as spec-compliant as possible, even if it requires more convoluted code.

Title: Understanding Array.isArray Polyfill

Body:
I was going through the polyfill of Array.isArray method on MDN, and this is what I found:

if (!Array.isArray) {
  Array.isArray = function(arg) {
    return Object.prototype.toString.call(arg) === '[object Array]';
  };
}

While this works, I wonder why MDN hasn't listed the following as the polyfill for isArray?

if (!Array.isArray) {
  Array.isArray = function(arg) {
    return arg.constructor === Array;
  };
}

Above code is a bit short and simpler. I wonder if there is any advantage of using MDN's implementation as compared to above one?

Body:
One problem would be that a non-array object with a constructor property of Array would pass when it shouldn't:

// Bad polyfill, do not use
Array.isArray = function(arg) {
  return arg.constructor === Array;
};

const badObj = {};
badObj.constructor = Array;
console.log(Array.isArray(badObj));

The above would be a very strange situation, but a polyfill must be as spec-compliant as possible, even if it requires more convoluted code.


问:
Python3: Why is my else statement activating regardless of multiple if statements being true
```<code>tweet = ''
tweet = input('Enter a tweet (160 characters or less):\n')

if len(tweet) <= 160:
    if 'LOL' in tweet:
        print('Laugh out loud')
    if 'BFN' in tweet:
        print('Bye for now')
    if 'BRB' in tweet:
        print('Be right back')
    if 'IRL' in tweet:
        print('In real life')
    if 'FTW' in tweet:
        print('For the win')
    if 'LMFAO' in tweet:
        print('Laugh my F**king a** off')
    if 'LMAO' in tweet:
        print('Laugh my a** off')
    else:
        print('You didn\'t use any abbreviations')
elif len(tweet) == 0:
    print('Wow, such empty')
elif len(tweet) > 160:
    print('Your tweet is over 160 characters')
</code>```

So, for example if I run this program and input:
LOL BRB

The output is:
Laugh out loud
Be right back
You didn't use any abbreviations

Whereas the output I want for that input is:
Laugh out loud
Be right back

As far as I can tell the indentation is correct. Also we haven't gone over the 'break' or 'enumerate' functions, so we are not expected to use these to attain the desired result.

Thank you for the help!!

This is the code in working order after everyone's help:

```<code>tweet = ''
tweet = input('Enter a tweet (160 characters or less):\n')

tweet_abbrev = False

if len(tweet) <= 160:
    if 'LOL' in tweet:
        tweet_abbrev = True
        print('Laugh out loud')
    if 'BFN' in tweet:
        tweet_abbrev = True
        print('Bye for now')
    if 'BRB' in tweet:
        tweet_abbrev = True
        print('Be right back')
    if 'IRL' in tweet:
        tweet_abbrev = True
        print('In real life')
    if 'FTW' in tweet:
        tweet_abbrev = True
        print('For the win')
    if 'LMFAO' in tweet:
        tweet_abbrev = True
        print('Laugh my F**king a** off')
    if 'LMAO' in tweet:
        tweet_abbrev = True
        print('Laugh my a** off')
    if not tweet_abbrev:
        print('You didn\'t use any abbreviations')
if len(tweet) == 0:
    print('Wow, such empty')
elif len(tweet) > 160:
    print('Your tweet is over 160 characters')
</code>```

Thank you everyone for the quick responses!!!

答:
What you probably want is the following:

```<code>tweet = ''
tweet = input('Enter a tweet (160 characters or less):\n')

if len(tweet) <= 160:
    abbr_found = False
    for (abbr, feedback) in [
        ('LOL', 'Laugh out loud'),
        ('BFN', 'Bye for now'),
        ('BRB', 'Be right back'),
        ('IRL', 'In real life'),
        ('FTW', 'For the win'),
        ('LMFAO', 'Laugh my F**king a** off'),
        ('LMAO', 'Laugh my a** off'),
    ]:
        if abbr in tweet:
            print(feedback)
            abbr_found = True
    if not abbr_found:
        print('You didn\'t use any abbreviations')
elif len(tweet) == 0:
    print('Wow, such empty')
elif len(tweet) > 160:
    print('Your tweet is over 160 characters')
</code>```

For every abbreviation you check, you can get a feedback "translating" to human-speak. If no abbreviation was used, you get a feedback indicating this.

I'm making an assumption on the logic you want here, and the easiest way to implement it is using this loop. Otherwise, in addition to the multitude of if statements, you would have has to assign to addr_found in each of the conditional blocks.

Body:
tweet = ''
tweet = input('Enter a tweet (160 characters or less):\n')

if len(tweet) <= 160:
    if 'LOL' in tweet:
        print('Laugh out loud')
    if 'BFN' in tweet:
        print('Bye for now')
    if 'BRB' in tweet:
        print('Be right back')
    if 'IRL' in tweet:
        print('In real life')
    if 'FTW' in tweet:
        print('For the win')
    if 'LMFAO' in tweet:
        print('Laugh my F**king a** off')
    if 'LMAO' in tweet:
        print('Laugh my a** off')
    else:
        print('You didn\'t use any abbreviations')
elif len(tweet) == 0:
    print('Wow, such empty')
elif len(tweet) > 160:
    print('Your tweet is over 160 characters')

So, for example if I run this program and input:
LOL BRB

The output is:
Laugh out loud
Be right back
You didn't use any abbreviations

Whereas the output I want for that input is:
Laugh out loud
Be right back

As far as I can tell the indentation is correct. Also we haven't gone over the 'break' or 'enumerate' functions, so we are not expected to use these to attain the desired result.

Thank you for the help!!

This is the code in working order after everyone's help:

tweet = ''
tweet = input('Enter a tweet (160 characters or less):\n')

tweet_abbrev = False

if len(tweet) <= 160:
    if 'LOL' in tweet:
        tweet_abbrev = True
        print('Laugh out loud')
    if 'BFN' in tweet:
        tweet_abbrev = True
        print('Bye for now')
    if 'BRB' in tweet:
        tweet_abbrev = True
        print('Be right back')
    if 'IRL' in tweet:
        tweet_abbrev = True
        print('In real life')
    if 'FTW' in tweet:
        tweet_abbrev = True
        print('For the win')
    if 'LMFAO' in tweet:
        tweet_abbrev = True
        print('Laugh my F**king a** off')
    if 'LMAO' in tweet:
        tweet_abbrev = True
        print('Laugh my a** off')
    if not tweet_abbrev:
        print('You didn\'t use any abbreviations')
if len(tweet) == 0:
    print('Wow, such empty')
elif len(tweet) > 160:
    print('Your tweet is over 160 characters')

Thank you everyone for the quick responses!!!

Body:
What you probably want is the following:

tweet = ''
tweet = input('Enter a tweet (160 characters or less):\n')

if len(tweet) <= 160:
    abbr_found = False
    for (abbr, feedback) in [
        ('LOL', 'Laugh out loud'),
        ('BFN', 'Bye for now'),
        ('BRB', 'Be right back'),
        ('IRL', 'In real life'),
        ('FTW', 'For the win'),
        ('LMFAO', 'Laugh my F**king a** off'),
        ('LMAO', 'Laugh my a** off'),
    ]:
        if abbr in tweet:
            print(feedback)
            abbr_found = True
    if not abbr_found:
        print('You didn\'t use any abbreviations')
elif len(tweet) == 0:
    print('Wow, such empty')
elif len(tweet) > 160:
    print('Your tweet is over 160 characters')

For every abbreviation you check, you can get a feedback "translating" to human-speak. If no abbreviation was used, you get a feedback indicating this.

I'm making an assumption on the logic you want here, and the easiest way to implement it is using this loop. Otherwise, in addition to the multitude of if statements, you would have has to assign to addr_found in each of the conditional blocks.


问:
Set value of primeng dropdown in model driven form
I am trying to populate a form which has a few PrimeNg dropdowns.
For simplicity let me use example similar to what is on their web site.

<form [formGroup]="myFormGroup">

</form>
```

<pre class="lang-js prettyprint-override"><code>this.cities = [
  {name: 'New York', code: 'NY'},
  {name: 'Rome', code: 'RM'},
  {name: 'London', code: 'LDN'},
  {name: 'Istanbul', code: 'IST'},
  {name: 'Paris', code: 'PRS'}
];
</code>```

So suppose user from table with his trips selects a row for edit.
It corresponds to some complex object, which contains a City property.
We need to programmatically select say Rome in that dropdown on the form.

I tried to do:

```<code>this.myFormGroup.get("selectedCity").setValue('Rome');
</code>```

tried:

```<code>this.myFormGroup.get("selectedCity").patchValue('Rome');
</code>```

tried adding to html:

```<code>optionLabel="name"
</code>```

Nothing gets selected.

Any advice how to do it properly?

I assume I should not add

```<code>[(ngModel)]="selectedCity"
</code>```

and do:

```<code>this.selectedCity='Rome';
</code>```

Using Angular6 and PrimeNG 6.1.2.

答:
First of all it should be clear that; whatever the options array contains they are the values set to the FormControl.

In this case form control values are city objects because cities array contains objects.

In order to set form control value programmatically, the value must be one of the elements from options array.

So, if you want to set Istanbul as selected you must set exact same object from cities array (particularly, cities[3])

It can be done in this way;

this.myFormGroup.get("selectedCity").setValue(this.cities.find(city => city.name === "Istanbul"));
```

As a side note optionLabel="name" only indicates which field from city objects to use as display value, that's all.

Here is a demo: https://stackblitz.com/edit/angular-6-template-6yu6jz

Body:
I am trying to populate a form which has a few PrimeNg dropdowns.
For simplicity let me use example similar to what is on their web site.

<form [formGroup]="myFormGroup">

</form>

this.cities = [
  {name: 'New York', code: 'NY'},
  {name: 'Rome', code: 'RM'},
  {name: 'London', code: 'LDN'},
  {name: 'Istanbul', code: 'IST'},
  {name: 'Paris', code: 'PRS'}
];

So suppose user from table with his trips selects a row for edit.
It corresponds to some complex object, which contains a City property.
We need to programmatically select say Rome in that dropdown on the form.

I tried to do:

this.myFormGroup.get("selectedCity").setValue('Rome');

tried:

this.myFormGroup.get("selectedCity").patchValue('Rome');

tried adding to html:

optionLabel="name"

Nothing gets selected.

Any advice how to do it properly?

I assume I should not add

[(ngModel)]="selectedCity"

and do:

this.selectedCity='Rome';

Using Angular6 and PrimeNG 6.1.2.

Body:
First of all it should be clear that; whatever the options array contains they are the values set to the FormControl.

In this case form control values are city objects because cities array contains objects.

In order to set form control value programmatically, the value must be one of the elements from options array.

So, if you want to set Istanbul as selected you must set exact same object from cities array (particularly, cities[3])

It can be done in this way;

this.myFormGroup.get("selectedCity").setValue(this.cities.find(city => city.name === "Istanbul"));

As a side note optionLabel="name" only indicates which field from city objects to use as display value, that's all.

Here is a demo: https://stackblitz.com/edit/angular-6-template-6yu6jz


问:
Error when executing PowerShell script for SharePoint Online
So, i'm trying to run this SPO PowerShell script that microsoft provides in this link:
https://learn.microsoft.com/en-us/powershell/module/sharepoint-online/export-spouserinfo?view=sharepoint-ps on the "example 2". However, when i try to run the script on PowerShell ISE, i get the following error: "Parameter missing for 'Output Folder' argument. Specify a 'System.String' type parameter and try again." I tried to change the arguments, input my site collection, creating a .csv file on the folder, but nothing changes this error message, what am i doing wrong?

Here is the code i'm using:

```<code>    $sites = Get-SPOSite -IncludePersonalSite $true
$user = "xxxxxx@domain.com"
foreach ($site in $sites)
{
Export-SPOUserInfo -LoginName $user -site $site.Url -OutputFolder
"D:"
}
</code>```

Thanks in advance!

答:
Writing to the root of a drive is really not a best practice. Always use a folder of the root, unless there is a very valid reason to put a file there. Yet, that is not your use case as presented.

```<code>$sites = Get-SPOSite -IncludePersonalSite $true
$user = "xxxxxx@domain.com"
foreach ($site in $sites)
{
    Export-SPOUserInfo -LoginName $user -site $($site.Url) -OutputFolder 'D:\SPOSiteData'
}
</code>```

Your string must be all on one line if not properly terminated for multi-line. For example, using PowerShell Splatting

about_Splatting - PowerShell | Microsoft Docs

```<code>$ExportSPOUserInfoSplat = @{
    LoginName    = $user
    site         = $($site.Url)
    OutputFolder = 'D:\SPOSiteData'
}
Export-SPOUserInfo @ExportSPOUserInfoSplat
</code>```

Te line wrapping, which it seems you copied and pasted, is that way because of page space not a code requirement.

Body:
So, i'm trying to run this SPO PowerShell script that microsoft provides in this link:
https://learn.microsoft.com/en-us/powershell/module/sharepoint-online/export-spouserinfo?view=sharepoint-ps on the "example 2". However, when i try to run the script on PowerShell ISE, i get the following error: "Parameter missing for 'Output Folder' argument. Specify a 'System.String' type parameter and try again." I tried to change the arguments, input my site collection, creating a .csv file on the folder, but nothing changes this error message, what am i doing wrong?

Here is the code i'm using:

    $sites = Get-SPOSite -IncludePersonalSite $true
$user = "xxxxxx@domain.com"
foreach ($site in $sites)
{
Export-SPOUserInfo -LoginName $user -site $site.Url -OutputFolder
"D:"
}

Thanks in advance!

Body:
Writing to the root of a drive is really not a best practice. Always use a folder of the root, unless there is a very valid reason to put a file there. Yet, that is not your use case as presented.

$sites = Get-SPOSite -IncludePersonalSite $true
$user = "xxxxxx@domain.com"
foreach ($site in $sites)
{
    Export-SPOUserInfo -LoginName $user -site $($site.Url) -OutputFolder 'D:\SPOSiteData'
}

Your string must be all on one line if not properly terminated for multi-line. For example, using PowerShell Splatting

about_Splatting - PowerShell | Microsoft Docs

$ExportSPOUserInfoSplat = @{
    LoginName    = $user
    site         = $($site.Url)
    OutputFolder = 'D:\SPOSiteData'
}
Export-SPOUserInfo @ExportSPOUserInfoSplat

Te line wrapping, which it seems you copied and pasted, is that way because of page space not a code requirement.


问:
Why are packages not installing to both versions of Python on my Mac (in /User/name/Library and /usr/local/bin)?
I have been trying to install tensorflow and I keep getting this error that the module six is not found.

```<code>$ python3 -c "import tensorflow as tf;print(tf.reduce_sum(tf.random.normal([1000, 1000])))"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/Users/name/Library/Python/3.7/lib/python/site-packages/tensorflow/__init__.py", line 38, in <module>
    import six as _six
ModuleNotFoundError: No module named 'six'
</code>```

However when I try to install six, it says Requirement already satisfied.

```<code>$ sudo pip3 install six
Password:
WARNING: The directory '/Users/name/Library/Caches/pip' or its parent directory is not owned or is not writable by the current user. The cache has been disabled. Check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Requirement already satisfied: six in /usr/local/lib/python3.7/site-packages (1.15.0)
</code>```

What am I doing wrong?

UPDATE/EDIT:
Thank you all for your answers. I ended up using pyenv global 3.7.4 and that fixed all my problems. I'm not really sure why, but I'm sure that I'll understand better as I continue reading about and using Python.

答:
You can try to reinstall the package, that solved a couple of issues in my environment..</p>

```<code>pip3 uninstall six
pip3 install six
</code>```

Body:
I have been trying to install tensorflow and I keep getting this error that the module six is not found.

$ python3 -c "import tensorflow as tf;print(tf.reduce_sum(tf.random.normal([1000, 1000])))"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/Users/name/Library/Python/3.7/lib/python/site-packages/tensorflow/__init__.py", line 38, in <module>
    import six as _six
ModuleNotFoundError: No module named 'six'

However when I try to install six, it says Requirement already satisfied.

$ sudo pip3 install six
Password:
WARNING: The directory '/Users/name/Library/Caches/pip' or its parent directory is not owned or is not writable by the current user. The cache has been disabled. Check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Requirement already satisfied: six in /usr/local/lib/python3.7/site-packages (1.15.0)

What am I doing wrong?

UPDATE/EDIT:
Thank you all for your answers. I ended up using pyenv global 3.7.4 and that fixed all my problems. I'm not really sure why, but I'm sure that I'll understand better as I continue reading about and using Python.

Body:
You can try to reinstall the package, that solved a couple of issues in my environment..

pip3 uninstall six
pip3 install six


问:
Need to play a mp3 audio over the internet without latency in iOS (Swift)
We are trying to achieve low latency audio streaming(only encoded audio data present, no video data) using AVPlayer.  We have tested audio streaming protocols like HTTP & HLS and have observed a minimum of 3 seconds latency to play.
Does AVPlayer require an input buffer of a minimum of 3 seconds on the device before starting the playback?

Does latency reduction have any correlation with the quality of audio playback?

Can we reduce this latency? If yes, are there any suggestions or recommended practices?

答:
Latency can be minimized by using Audio Units, as Audio Units can request to be configured with very short audio buffers, typically 20 mS down to 5 mS, or even less on some Apple devices.  UDP with MTU size packets can be used to stream data over the network, where your network buffering and traffic interference may be the dominating factor in added latency.  You will likely have to add some amount of latency (circular ring buffer fill level) to account for worse case network timing jitter.  Then, for mp3 compressed audio, add on the minimum mp3 block size and how long your chosen mp3 decoder takes.

Other APIs and protocols can potentially add large amounts of overhead and buffering latency.


问:
How can I unpivot three types of values (including the column headers)
The data I have looks like this:

```<code>╔═════════╦═════════╦═════════╦══════════════╦══════════════╦══════════════╗
║ option1 ║ option2 ║ option3 ║ percent_opt1 ║ percent_opt2 ║ percent_opt3 ║
╠═════════╬═════════╬═════════╬══════════════╬══════════════╬══════════════╣
║ 10      ║ 4       ║ 1       ║ 0.67         ║ 0.27         ║ 0.07         ║
╚═════════╩═════════╩═════════╩══════════════╩══════════════╩══════════════╝
</code>```

So if i want to make the first three column headers row values, then the other ones also as more row values, how would I do that?

This is what I mean:

```<code>╔═════════╦════════╦═════════════╗
║ options ║ values ║ percentages ║
╠═════════╬════════╬═════════════╣
║ option1 ║ 10     ║ 0.67        ║
╠═════════╬════════╬═════════════╣
║ option2 ║ 4      ║ 0.27        ║
╠═════════╬════════╬═════════════╣
║ option3 ║ 1      ║ 0.07        ║
╚═════════╩════════╩═════════════╝
</code>```

Here is the code I'm using:

```<code>declare @tbl as table (
    option1 numeric(18,0),
    option2 numeric(18,0),
    option3 numeric(18,0),
    per_opt1 numeric(18,2),
    per_opt2 numeric(18,2),
    per_opt3 numeric(18,2)
)

insert into @tbl
values (10,4,1,0.67,0.27,0.07)

;

select * from
(
    select t.[option1],t.[option2],t.[option3]
    from @tbl as t
) as srctbl
    unpivot (
        val for options in (option1,option2,option3)
) as unpiv
</code>```

I don't know how to get those last three percentage column values to be row values, partially because I can't have a different datatype, and because I'm not sure how to.

Any suggestions?

答:
Use a lateral join - in SQL Server this is called apply:

```<code>select x.*
from @tbl t
cross apply (values
    ('option1', t.option1, t.per_opt1),
    ('option2', t.option2, t.per_opt2),
    ('option3', t.option3, t.per_opt3)
) as x(options, vals, percentages)
</code>```

Demo on DB Fiddle:

```
options | vals | percentages
:------ | ---: | ----------:
option1 |   10 |        0.67
option2 |    4 |        0.27
option3 |    1 |        0.07
```

Note that values is a SQL keyword - I renamed the column to vals in the resultset.

Body:
The data I have looks like this:

╔═════════╦═════════╦═════════╦══════════════╦══════════════╦══════════════╗
║ option1 ║ option2 ║ option3 ║ percent_opt1 ║ percent_opt2 ║ percent_opt3 ║
╠═════════╬═════════╬═════════╬══════════════╬══════════════╬══════════════╣
║ 10      ║ 4       ║ 1       ║ 0.67         ║ 0.27         ║ 0.07         ║
╚═════════╩═════════╩═════════╩══════════════╩══════════════╩══════════════╝

So if i want to make the first three column headers row values, then the other ones also as more row values, how would I do that?

This is what I mean:

╔═════════╦════════╦═════════════╗
║ options ║ values ║ percentages ║
╠═════════╬════════╬═════════════╣
║ option1 ║ 10     ║ 0.67        ║
╠═════════╬════════╬═════════════╣
║ option2 ║ 4      ║ 0.27        ║
╠═════════╬════════╬═════════════╣
║ option3 ║ 1      ║ 0.07        ║
╚═════════╩════════╩═════════════╝

Here is the code I'm using:

declare @tbl as table (
    option1 numeric(18,0),
    option2 numeric(18,0),
    option3 numeric(18,0),
    per_opt1 numeric(18,2),
    per_opt2 numeric(18,2),
    per_opt3 numeric(18,2)
)

insert into @tbl
values (10,4,1,0.67,0.27,0.07)

;

select * from
(
    select t.[option1],t.[option2],t.[option3]
    from @tbl as t
) as srctbl
    unpivot (
        val for options in (option1,option2,option3)
) as unpiv

I don't know how to get those last three percentage column values to be row values, partially because I can't have a different datatype, and because I'm not sure how to.

Any suggestions?

Body:
Use a lateral join - in SQL Server this is called apply:

select x.*
from @tbl t
cross apply (values
    ('option1', t.option1, t.per_opt1),
    ('option2', t.option2, t.per_opt2),
    ('option3', t.option3, t.per_opt3)
) as x(options, vals, percentages)

Demo on DB Fiddle:

options | vals | percentages
:------ | ---: | ----------:
option1 |   10 |        0.67
option2 |    4 |        0.27
option3 |    1 |        0.07

Note that values is a SQL keyword - I renamed the column to vals in the resultset.


答:
Use apply:

```<code>select v.*
from @tbl t cross apply
     (values ('option1', option1, percent_opt1),
             ('option2', option2, percent_opt2),
             ('option3', option3, percent_opt3)
     ) v(option, value, percent_opt);
</code>```

Note:  values is a SQL keyword so I changed the name of the middle column.

In my opinion, there is no reason whatsoever to learn unpivot.  It is bespoke functionality -- extensions in a small number of databases -- that does just one thing in an "okay" way.

On the other hand, apply supports lateral joins, which are standard (even if the syntax varies among databases).  They are very powerful, and unpivoting is a good way to start learning about them.

Title: How can I unpivot three types of values (including the column headers)

Body:
Use apply:

select v.*
from @tbl t cross apply
     (values ('option1', option1, percent_opt1),
             ('option2', option2, percent_opt2),
             ('option3', option3, percent_opt3)
     ) v(option, value, percent_opt);

Note:  values is a SQL keyword so I changed the name of the middle column.

In my opinion, there is no reason whatsoever to learn unpivot.  It is bespoke functionality -- extensions in a small number of databases -- that does just one thing in an "okay" way.

On the other hand, apply supports lateral joins, which are standard (even if the syntax varies among databases).  They are very powerful, and unpivoting is a good way to start learning about them.


问:
Convert a dictionary of strings to a dictionary of numpy arrays
I have a dictionary structured similar to below.

```<code>test_dict = {1: 'I run fast', 2: 'She runs', 3: 'How are you?'}
</code>```

What I'm trying to do is convert all the strings to 4x4 numpy arrays where each word is in it's own row and each letter occupies one cell of the array, populated with blanks for lines that wouldn't fill the entire row a whole row of blanks for sentences that are less than 4 words long. I also need to be able to tie it back to the ID, so the result needs to be in some format that can allow for referencing each array by it's ID later on.

I don't know of any pre built functions that can handle something like this, but I would be happy to be wrong. For now I've been trying to write a loop to handle it. Below is obviously incomplete because I'm stuck at the point of creating an array in the structure I would like.

```<code>for k in test_dict.keys():
    sentence = test_dict.getvalues(k)
    sentence_ascii = [ord(c) for c in sentence]
    sentence_array = np.array(sentence_ascii)
</code>```

答:
This'll ensure you have blank rows for sentences less than four words long.</p>

```<code>new_dict = {i+1:np.empty((4,4),dtype='str') for i in range(len(test_dict))}
for k,v in test_dict.items():
    new_dict[k][:len(v.split())] = np.array([list(s)+['']*(4-len(s)) for s in v.split()])
    new_dict[k] = new_dict[k].view(np.int32)
</code>```

Body:
I have a dictionary structured similar to below.

test_dict = {1: 'I run fast', 2: 'She runs', 3: 'How are you?'}

What I'm trying to do is convert all the strings to 4x4 numpy arrays where each word is in it's own row and each letter occupies one cell of the array, populated with blanks for lines that wouldn't fill the entire row a whole row of blanks for sentences that are less than 4 words long. I also need to be able to tie it back to the ID, so the result needs to be in some format that can allow for referencing each array by it's ID later on.

I don't know of any pre built functions that can handle something like this, but I would be happy to be wrong. For now I've been trying to write a loop to handle it. Below is obviously incomplete because I'm stuck at the point of creating an array in the structure I would like.

for k in test_dict.keys():
    sentence = test_dict.getvalues(k)
    sentence_ascii = [ord(c) for c in sentence]
    sentence_array = np.array(sentence_ascii)

Body:
This'll ensure you have blank rows for sentences less than four words long.

new_dict = {i+1:np.empty((4,4),dtype='str') for i in range(len(test_dict))}
for k,v in test_dict.items():
    new_dict[k][:len(v.split())] = np.array([list(s)+['']*(4-len(s)) for s in v.split()])
    new_dict[k] = new_dict[k].view(np.int32)


问:
get query string in popup window
```<code><a href="tags.php" onclick="return popitup('tags.php')">tags</a>
</code>```

I have this line of code that runs the javascript to open new mini popup window,and it mostly works.

Now how could i add current query string attributes so that my popup window has url something like this "tags.php?variable1&variable2"

In few similar places I used this along with some other code to get the query attributes,the problem is that in this case page refreshes and contacts the sql without running javascript or opening window,when i try to make my code PHP using echo the quotation makrs f* everything up.

```<code>".$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING']."
</code>```

Title: get query string in popup window

Body:
tags

I have this line of code that runs the javascript to open new mini popup window,and it mostly works.

Now how could i add current query string attributes so that my popup window has url something like this "tags.php?variable1&variable2"

In few similar places I used this along with some other code to get the query attributes,the problem is that in this case page refreshes and contacts the sql without running javascript or opening window,when i try to make my code PHP using echo the quotation makrs f* everything up.

".$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING']."

Body: return popitup('tags.php'+window.location.search)


问:
Solve matrix equation with scalar value
I have two square matrices, A and B and wish to find the scalar value, s, which minimizes the below equation:

||A-sB||

where || is the 2-norm. How can I efficiently code this in python with numpy or scipy?

答:
You can use scipy.optimize.minimize: first define your objective function, which I called f, then minimize requires an initial guess x0 and additional parameters of the function you want to minimize:

import numpy as np
from scipy.optimize import minimize

def f(x, A, B):
    return np.linalg.norm(A-x*B, ord=2)

n = 3

A = np.ones((n,n))
B = np.arange(n**2).reshape(n,n)

minimize(f, x0=1, args=(A, B))
      fun: 1.5845110835227028
 hess_inv: array([[0.00838895]])
      jac: array([-4.47034836e-08])
  message: 'Optimization terminated successfully.'
     nfev: 24
      nit: 5
     njev: 8
   status: 0
  success: True
        x: array([0.1844041])
```

Minimize will return a sort of optimization report, in particular you care about the x value, which you can access as a dictionary minimize(f, x0=1, args=(A, B))['x'].

Title: Solve matrix equation with scalar value

Body:
You can use scipy.optimize.minimize: first define your objective function, which I called f, then minimize requires an initial guess x0 and additional parameters of the function you want to minimize:

import numpy as np
from scipy.optimize import minimize

def f(x, A, B):
    return np.linalg.norm(A-x*B, ord=2)

n = 3

A = np.ones((n,n))
B = np.arange(n**2).reshape(n,n)

minimize(f, x0=1, args=(A, B))
      fun: 1.5845110835227028
 hess_inv: array([[0.00838895]])
      jac: array([-4.47034836e-08])
  message: 'Optimization terminated successfully.'
     nfev: 24
      nit: 5
     njev: 8
   status: 0
  success: True
        x: array([0.1844041])

Minimize will return a sort of optimization report, in particular you care about the x value, which you can access as a dictionary minimize(f, x0=1, args=(A, B))['x'].


问:
Why is there no tkinter distribution found?
I am having a problem during the installation of tkinter. I have version 2.7.11. I entered the pip install tkinter on dos but it shows the following message:

collecting tkinter

Could not find a version that satisfies the requirement tkinter (from versions:)
  No matching distribution found for tkinter

I have successfully installed flask with the same procedure, but for tkinter it is showing problem. How can I get rid of this problem?

答: I was able to fix this on Amazon Linux 2 with python2.7 by running this sudo yum install python-tools -y command.


问:
Can't access ansible_host property of my inventory items
I have this inventory file:

```<code>[masters]
master ansible_host=1.2.3.4.5 ansible_user=ubuntu

[workers]
worker1 ansible_host=1.2.3.4.5 ansible_user=ubuntu

[nodes]
master ansible_host=1.2.3.4.5 ansible_user=ubuntu
worker1 ansible_host=1.2.3.4.5 ansible_user=ubuntu

[fileserver]
fs-01 ansible_host=1.2.3.4.5 ansible_user=ubuntu
</code>```

I'm trying to install an SSH key from my local machine to all inventory machines.

```<code>- name: install the SSH key on all machines.
  hosts: 127.0.0.1
  connection: local
  tasks:
  - name: install SSH-key
    shell: sshpass -p {{ ssh_key_password }} ssh-copy-id -i /id_rsa.pub -o StrictHostKeyChecking ubuntu@{{ item }}
    with_items:
      - "{{ hostvars['all'].ansible_host }}"
</code>```

However, it ends with this error:

```<code>fatal: [127.0.0.1]: FAILED! => {"msg": "\"hostvars['all']\" is undefined"}
</code>```

I'm trying to get the ansible_host 1.2.3.4.5 of each unique inventory name in my inventory. However, I'm not having much luck. What am I doing wrong?

答:
You're going about it backward.  Ansible automatically loops through your play hosts, so use your hosts, not localhost, then delegate the task to localhost.

```<code>- name: install the SSH key on all machines.
  hosts: all
  gather_facts: no
  tasks:
  - name: install SSH-key
    shell: sshpass -p {{ ssh_key_password }} ssh-copy-id -i /id_rsa.pub -o StrictHostKeyChecking {{ ansible_user }}@{{ ansible_host }}
    delegate_to: localhost
</code>```

Body:
I have this inventory file:

[masters]
master ansible_host=1.2.3.4.5 ansible_user=ubuntu

[workers]
worker1 ansible_host=1.2.3.4.5 ansible_user=ubuntu

[nodes]
master ansible_host=1.2.3.4.5 ansible_user=ubuntu
worker1 ansible_host=1.2.3.4.5 ansible_user=ubuntu

[fileserver]
fs-01 ansible_host=1.2.3.4.5 ansible_user=ubuntu

I'm trying to install an SSH key from my local machine to all inventory machines.

- name: install the SSH key on all machines.
  hosts: 127.0.0.1
  connection: local
  tasks:
  - name: install SSH-key
    shell: sshpass -p {{ ssh_key_password }} ssh-copy-id -i /id_rsa.pub -o StrictHostKeyChecking ubuntu@{{ item }}
    with_items:
      - "{{ hostvars['all'].ansible_host }}"

However, it ends with this error:

fatal: [127.0.0.1]: FAILED! => {"msg": "\"hostvars['all']\" is undefined"}

I'm trying to get the ansible_host 1.2.3.4.5 of each unique inventory name in my inventory. However, I'm not having much luck. What am I doing wrong?

Body:
You're going about it backward.  Ansible automatically loops through your play hosts, so use your hosts, not localhost, then delegate the task to localhost.

- name: install the SSH key on all machines.
  hosts: all
  gather_facts: no
  tasks:
  - name: install SSH-key
    shell: sshpass -p {{ ssh_key_password }} ssh-copy-id -i /id_rsa.pub -o StrictHostKeyChecking {{ ansible_user }}@{{ ansible_host }}
    delegate_to: localhost


问:
I cannot get git to ignore my tmp folder of my Ruby on Rails project
So I tried everything
but to no avail
I keep getting the following error
"fatal: cannot use tmp/ as an exclude file"
I have even tried using /tmp and tmp/* but none of these  two work either .
Finally I deleted the tmp folder in frustration and i found that git now works perfectly

SO I have two questions.

The obvious one being . How do I get this to work?

Is it possible for me to run my   ruby on rails  applications    without the tmp folder?

答:
It may have to do with the way git works with cached files that the folder may still show up after including it in the .gitignore file.

Try git rm . -r --cached in the command line to clear out the cached files.


问:
Glassfish EJB server + OpenEJB client
Is it possible not to use Java EE Application client from Glassfish to access EJB on Server. I would like to try using OpenEJB for a standalone Java SE client. Is it possible? I cannot find anything in the Internet on the topic.

Thanks

答:
Short answer is no.  The OpenEJB client only works with EJBs running in an OpenEJB container. There is support for running the container in Tomcat, Geronimo as well as standalone or embedded in a plain Java SE app, but there is no support for running it in GlassFish.

Side note that OpenEJB does support reading and using the GlassFish deployment descriptors, so if you were tempted to try running your EJBs in an environment where OpenEJB is the container, it should be fairly easy.

Title: Glassfish EJB server + OpenEJB client


问:
Blazor format an InputType of Numeric
Would anyone know how to format a Numeric type to look like 100.10? Currently if the value is 100.10 it will display as 100.1

tried @bind-value:format with C2, 0:0.##, I'm new to Blazor so if anyone could point me in the right direction it would be appreciated.

```<code><BSBasicInput InputType="InputType.Number" @bind-Value="@Amount" step="0.01" />
</code>```

答:
If you bind to a decimal it seems it will keep the number of decimals you specify for the value, even training zeros.

```<code>@page "/"
<EditForm Model=@Account>
    <InputNumber @bind-Value=Account.Balance/>
    <button>Submit</button>
</EditForm>

@code
{
    BankAccount Account = new BankAccount();

    public class BankAccount
    {
        public decimal Balance { get; set; } = 23.300;
    }
}
</code>```

For floats and doubles I would have expected the following to work

```<code><InputNumber @bind-Value=Account.Balance @bind-Value:format="F2"/>
</code>```

But it seems only DateTime and DateTimeOffset are supported, which is a shame.

There is an example on Blazor University showing how to descend from InputBase to create your own input controls. It would be quite trivial to implement a control that honours the format.

https://blazor-university.com/forms/descending-from-inputbase/

Title: Blazor format an InputType of Numeric

Body:
Would anyone know how to format a Numeric type to look like 100.10? Currently if the value is 100.10 it will display as 100.1

tried @bind-value:format with C2, 0:0.##, I'm new to Blazor so if anyone could point me in the right direction it would be appreciated.

<BSBasicInput InputType="InputType.Number" @bind-Value="@Amount" step="0.01" />

Body:
If you bind to a decimal it seems it will keep the number of decimals you specify for the value, even training zeros.

@page "/"
<EditForm Model=@Account>
    <InputNumber @bind-Value=Account.Balance/>
    <button>Submit</button>
</EditForm>

@code
{
    BankAccount Account = new BankAccount();

    public class BankAccount
    {
        public decimal Balance { get; set; } = 23.300;
    }
}

For floats and doubles I would have expected the following to work

<InputNumber @bind-Value=Account.Balance @bind-Value:format="F2"/>

But it seems only DateTime and DateTimeOffset are supported, which is a shame.

There is an example on Blazor University showing how to descend from InputBase to create your own input controls. It would be quite trivial to implement a control that honours the format.

https://blazor-university.com/forms/descending-from-inputbase/


问:
Difference between async/await and async/fixture.whenStable in Angular
I want to know the difference between these two methods for dealing with asynchronous calls in the Angular framework while testing:

The first with the jasmine approach async/await

The second with the Angular approach async/fixture.whenStable

Are they similar? If not, what is the difference, and when exactly should I use one rather than the other?

答:
The first approach of async/await is stock JavaScript where you want to run the function asynchronously and you can await for promises before carrying over to the next line.

```<code>it('it block in an async await way', async(done) => {
   await waitForThisFunctionThatReturnsAPromiseBeforeCarringForward();
   // do something, make assertions
   const x = await getXFromAPromise(); // wait for getXFromAPromise() function to return the promise
// and assign the results to x
   // do something, make assertions
   done(); // call done to ensure you have run through the whole it block and tell Jasmine you're done
});
</code>```

The fixture.whenStable basically waits for all promises in the stack to be resolved before carrying forward with assertions.

```<code>it('demonstration of fixture.whenStable', async(done) => {
   // do some actions that will fire off promises
   await fixture.whenStable(); // wait until all promises in the call stack have been resolved
   // do some more assertions
   done(); // call done to tell Jasmine you're done with this test.
});
</code>```

The done callback is optional but I use it to ensure for better engineering (make sure it traversed through the whole it block).

Edit ====================

To handle observables, I use two methods.

async/await with take and toPromise operator where you take the first emission and you convert it to a promise. Feel free to add other operators such as filter to ignore some emissions before the take(1).

```<code>import { take } from 'rxjs/operators';
......
it('should do xyz', async done => {
  const x = await component.observable$.pipe(take(1)).toPromise();
  expect(x).toBe(....);
  done();
});
</code>```

The other way is to subscribe with done callback

```<code>it('should do xyz', done => {
  component.observable$.subscribe(result => {
    expect(result).toBe(...);
    // call done here to ensure the test made it within the subscribe
    // and did the assertions and to let Jasmine know you're done with the tests
    done();
  });
});
</code>```

Body:
The first approach of async/await is stock JavaScript where you want to run the function asynchronously and you can await for promises before carrying over to the next line.

it('it block in an async await way', async(done) => {
   await waitForThisFunctionThatReturnsAPromiseBeforeCarringForward();
   // do something, make assertions
   const x = await getXFromAPromise(); // wait for getXFromAPromise() function to return the promise
// and assign the results to x
   // do something, make assertions
   done(); // call done to ensure you have run through the whole it block and tell Jasmine you're done
});

The fixture.whenStable basically waits for all promises in the stack to be resolved before carrying forward with assertions.

it('demonstration of fixture.whenStable', async(done) => {
   // do some actions that will fire off promises
   await fixture.whenStable(); // wait until all promises in the call stack have been resolved
   // do some more assertions
   done(); // call done to tell Jasmine you're done with this test.
});

The done callback is optional but I use it to ensure for better engineering (make sure it traversed through the whole it block).

Edit ====================

To handle observables, I use two methods.

async/await with take and toPromise operator where you take the first emission and you convert it to a promise. Feel free to add other operators such as filter to ignore some emissions before the take(1).

import { take } from 'rxjs/operators';
......
it('should do xyz', async done => {
  const x = await component.observable$.pipe(take(1)).toPromise();
  expect(x).toBe(....);
  done();
});

The other way is to subscribe with done callback

it('should do xyz', done => {
  component.observable$.subscribe(result => {
    expect(result).toBe(...);
    // call done here to ensure the test made it within the subscribe
    // and did the assertions and to let Jasmine know you're done with the tests
    done();
  });
});