问:
Using for loop to create multiple graphs with ggplot in R
I have data that looks similar to this:

```<code>Criteria         Person A      Person B     Person C      Person D
A                    10           15           12           11
B                    50           55           40           37
C                    10           2             5           3
D                    15           18           22           30
E                    40           25           18           32
F                    12           35           10           12
</code>```

I need to create a ggplot column graph for each of the criteria, but I want to use a for loop to make it more efficient (or any other strategy). One graph for the criteria A, one for the B, and so on. The desired output should be something like:

```<code> ggplot(aes(x = person, y = n)) + geom_col() #for the criteria A
 ggplot(aes(x = person, y = n)) + geom_col() #for the criteria B
 ggplot(aes(x = person, y = n)) + geom_col() #for the criteria C
(...)
</code>```

where x is person A, B, C, and D, and n is the count (10, 15, 12...). The idea is to automatically create one graph for each of the criteria, without the need to manually create and adjust them using filter().

I have found a few options using facet_wrap but it is not exactly what I am looking for. Melt from reshape2 is not an option in this case too, as I want to create different graphs for each criteria.

Any suggestions?

答:
This makes a plot for each "Criteria"

library(tidyverse)

sample_df <- data.frame(
  stringsAsFactors = FALSE,
  check.names = FALSE,
          Criteria = c("A", "B", "C", "D", "E", "F"),
          `Person A` = c(10L, 50L, 10L, 15L, 40L, 12L),
          `Person B` = c(15L, 55L, 2L, 18L, 25L, 35L),
          `Person C` = c(12L, 40L, 5L, 22L, 18L, 10L),
          `Person D` = c(11L, 37L, 3L, 30L, 32L, 12L)
)

sample_df %>%
    pivot_longer(cols = -Criteria,
                 names_to = "person",
                 names_prefix = "Person\\s",
                 values_to = "n") %>%
    group_nest(Criteria) %>%
    mutate(plot = map(data, ~ggplot(.x, aes(x = person, y = n)) + geom_col())) %>%
    pull(plot)
#> [[1]]
```
<p><img src="https://i.imgur.com/X5imkm8.png" alt="" /></p>
```#>
#> [[2]]
```
<p><img src="https://i.imgur.com/HNGzT3l.png" alt="" /></p>
```#>
#> [[3]]
```
<p><img src="https://i.imgur.com/c2edcMW.png" alt="" /></p>
```#>
#> [[4]]
```
<p><img src="https://i.imgur.com/jJ1m5zc.png" alt="" /></p>
```#>
#> [[5]]
```
<p><img src="https://i.imgur.com/zLgIr5f.png" alt="" /></p>
```#>
#> [[6]]
```

Created on 2022-02-11 by the reprex package (v2.0.1)

Body:
I have data that looks similar to this:

Criteria         Person A      Person B     Person C      Person D
A                    10           15           12           11
B                    50           55           40           37
C                    10           2             5           3
D                    15           18           22           30
E                    40           25           18           32
F                    12           35           10           12

I need to create a ggplot column graph for each of the criteria, but I want to use a for loop to make it more efficient (or any other strategy). One graph for the criteria A, one for the B, and so on. The desired output should be something like:

 ggplot(aes(x = person, y = n)) + geom_col() #for the criteria A
 ggplot(aes(x = person, y = n)) + geom_col() #for the criteria B
 ggplot(aes(x = person, y = n)) + geom_col() #for the criteria C
(...)

where x is person A, B, C, and D, and n is the count (10, 15, 12...). The idea is to automatically create one graph for each of the criteria, without the need to manually create and adjust them using filter().

I have found a few options using facet_wrap but it is not exactly what I am looking for. Melt from reshape2 is not an option in this case too, as I want to create different graphs for each criteria.

Any suggestions?

Body:
This makes a plot for each "Criteria"

library(tidyverse)

sample_df <- data.frame(
  stringsAsFactors = FALSE,
  check.names = FALSE,
          Criteria = c("A", "B", "C", "D", "E", "F"),
          `Person A` = c(10L, 50L, 10L, 15L, 40L, 12L),
          `Person B` = c(15L, 55L, 2L, 18L, 25L, 35L),
          `Person C` = c(12L, 40L, 5L, 22L, 18L, 10L),
          `Person D` = c(11L, 37L, 3L, 30L, 32L, 12L)
)

sample_df %>%
    pivot_longer(cols = -Criteria,
                 names_to = "person",
                 names_prefix = "Person\\s",
                 values_to = "n") %>%
    group_nest(Criteria) %>%
    mutate(plot = map(data, ~ggplot(.x, aes(x = person, y = n)) + geom_col())) %>%
    pull(plot)
#> [[1]]

#>
#> [[2]]

#>
#> [[3]]

#>
#> [[4]]

#>
#> [[5]]

#>
#> [[6]]

Created on 2022-02-11 by the reprex package (v2.0.1)


来源: stackexchange

问:
Validate date that is in three separate input fields for Month, Day, and Year
I'm working on building a WebForm that has a set of Date of Birth fields at the bottom. This DOB is actually separated into three fields for Month, Day, and Year per the design of the page. We need to validate that the user is at least 13 years old when submitting the form.

If I had a single TextBox, this would be easy with a RangeValidator as such:

```<code>rvDOB.MaximumValue = DateTime.Now.AddYears(-13).ToShortDateString();
rvDOB.MinimumValue = DateTime.MinValue.ToShortDateString();
</code>```

The issue is that I do not have a single TextBox but three separate ones. How can I accomplish this check for at least 13 years with having three separate TextBox controls?

One approach I tried was to create an additional TextBox and when the form submission click event is raised, combine the three fields into the single textbox and validate on that. This did not work.

答:
My approach would be to have an event fire after a value has been entered into each box, and then place some logic in that event which will validate the users age once each of the boxes has data in them.</p>

```<code>delegate(object sender, EventArgs args) {
    if (!box1.Text.IsNullOrEmpty() &&
        !box2.Text.IsNullOrEmpty() &&
        !box3.Text.IsNullOrEmpty()) {
        // Validate the user is at least 13
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm working on building a WebForm that has a set of Date of Birth fields at the bottom. This DOB is actually separated into three fields for Month, Day, and Year per the design of the page. We need to validate that the user is at least 13 years old when submitting the form.

If I had a single TextBox, this would be easy with a RangeValidator as such:

rvDOB.MaximumValue = DateTime.Now.AddYears(-13).ToShortDateString();
rvDOB.MinimumValue = DateTime.MinValue.ToShortDateString();

The issue is that I do not have a single TextBox but three separate ones. How can I accomplish this check for at least 13 years with having three separate TextBox controls?

One approach I tried was to create an additional TextBox and when the form submission click event is raised, combine the three fields into the single textbox and validate on that. This did not work.

Body:
My approach would be to have an event fire after a value has been entered into each box, and then place some logic in that event which will validate the users age once each of the boxes has data in them.

delegate(object sender, EventArgs args) {
    if (!box1.Text.IsNullOrEmpty() &&
        !box2.Text.IsNullOrEmpty() &&
        !box3.Text.IsNullOrEmpty()) {
        // Validate the user is at least 13
    }
}


问:
sql conditional logic to check for a value in one or more tables sql developer
lets say, I have a page that displays:

```<code>******* Header1 ************
ColumnA columnB  columnC    columnD
value1**V**  123       1234      12345
value1**VA**  123       1234      12345
value1**V**  123       1234      12345
</code>```

so back to the sql developer now.
if you look at the colA, it has values ending with V and/or VA.
V and VA are stored in 2 different values.
So here's my question now:
how would I retrieve its parent id from its own respective table?

so in the query ill have to process, if the colA has/is ending with V, then go to the V table and get its corresponding value (which in our case its value1V, id from the V table).
is this scenario possible?
if so, how?
any help is greatly appreciated.thanks.

答:
There's quite a bit of detail missing from your question, but if I've understood you correctly, I think you want to return a value from one of two tables depending on whether ColumnA contains 'VA' or just 'V'.

In this case I would join to both the tables, then in the select clause, use a case when and like to choose which column from which table is returned.

I have provided a rough example below as I don't have the details. I have also used left outer joins in my rough example, another type of join may be more suitable in your case.

SELECT [ColumnA]
,[ColumnB]
,[ColumnC]
,[ColumnD]

,CASE WHEN [ColumnA] LIKE '%V**' THEN V.[ColumnA] ELSE VA.[ColumnA] END AS [ParentID]

FROM [Table] AS [A]

LEFT OUTER JOIN [Table V] AS [V]
ON A.[ColumnA] = V.[ColumnA]

LEFT OUTER JOIN [Table VA] AS [VA]
ON A.[ColumnA] = VA.[ColumnA]
```

ContentLicense: CC BY-SA 4.0

Body:
lets say, I have a page that displays:

******* Header1 ************
ColumnA columnB  columnC    columnD
value1**V**  123       1234      12345
value1**VA**  123       1234      12345
value1**V**  123       1234      12345

so back to the sql developer now.
if you look at the colA, it has values ending with V and/or VA.
V and VA are stored in 2 different values.
So here's my question now:
how would I retrieve its parent id from its own respective table?

so in the query ill have to process, if the colA has/is ending with V, then go to the V table and get its corresponding value (which in our case its value1V, id from the V table).
is this scenario possible?
if so, how?
any help is greatly appreciated.thanks.


问:
How to use tree or du command to get directory content sizes?
I'm using the tree command to get a list of directories:

tree -ifd --du

This, however, seems to be only displaying the size of the directory itself and not the total for its contents.

How would I modify this command to show the total space used by each directory WITH its contents?

edit:
This du command seems to come close to doing what I want but has a sorting issue:

du -h ./* | sort -k 2

The above produces a list like this:

```<code>62G     ./Directory
78G     ./Directory 3-14-18
36G     ./Directory 3-14-18/#0986
42G     ./Directory 3-14-18/#0987
38G     ./Directory 3-21-18
38G     ./Directory 3-21-18/#1229
31G     ./Directory/#7852
31G     ./Directory/#7853
</code>```

Note that, in the above, the first directory, the one with no date as part of its name, is at the top but it's subs are far below. I find that, if I add even a phony date to the end, something like 0-00-00, it sorts correctly:

```<code>62G     ./Directory 0-00-00
31G     ./Directory 0-00-00/#7852
31G     ./Directory 0-00-00/#7853
78G     ./Directory 3-14-18
36G     ./Directory 3-14-18/#0986
42G     ./Directory 3-14-18/#0987
38G     ./Directory 3-21-18
38G     ./Directory 3-21-18/#1229
</code>```

Additional question here would be:

How do I get the sorting to work WITHOUT having to add phony dates to everyplace I find this issue?

end edit

edit2:
Per the question from AndrewF below, I'll explain that I have a lot of archived media on hard drives. I can't run them all in my system at the same time so I thought it might be a good idea to have printed lists of what's on each drive.

To that end, I'm using tree to list the entire contents of each drive. I'm trying to use du to make a much shorter list of only directories as well.

As I get these drives organized, I expect to have to do a lot of manual digging and being able to view multiple lists should give me an ability to find redundancies that can be eliminated and deleted even though I can't have physical access to all of the drives at the same time. In other words, while I can't mount all of the drives, I can view all of the lists and use them to find redundancies, then mount the drive with the redundancy, and delete the extraneous directories. Having things sorted out of order is just going to make mistakes more likely.

end edit2

thanks,
babag

答:
I wouldn't use tree because I don't have it on all the platforms I use. But I imagine that find . -type d is well-suited for your use case, so:

```<code>find . -type d | xargs du -sh
</code>```

Depending on the directory you choose, you may get a lot of errors like "permission denied" to stderr, and if these are printing to your terminal but you want them to stop:

```<code>find . -type d 2>/dev/null | xargs du -sh 2>/dev/null
</code>```

Those examples will run du once per entry returned by the find.

Note that none of these are going to be efficient -- you're going to be analyzing the same files/directories many times to get those rolled-up summary sizes. Better solutions would involve depth-first traversal and memoization, and I don't know any available tools that do it.

Edit: I don't understand your goal with the sort. If the find does not list out all entries in the order you want, you'll need to provide extra details about what exact kind of sorting you want to do. It might be best to put that sorting problem into a new more specific question.

Body:
I'm using the tree command to get a list of directories:

tree -ifd --du

This, however, seems to be only displaying the size of the directory itself and not the total for its contents.

How would I modify this command to show the total space used by each directory WITH its contents?

edit:
This du command seems to come close to doing what I want but has a sorting issue:

du -h ./* | sort -k 2

The above produces a list like this:

62G     ./Directory
78G     ./Directory 3-14-18
36G     ./Directory 3-14-18/#0986
42G     ./Directory 3-14-18/#0987
38G     ./Directory 3-21-18
38G     ./Directory 3-21-18/#1229
31G     ./Directory/#7852
31G     ./Directory/#7853

Note that, in the above, the first directory, the one with no date as part of its name, is at the top but it's subs are far below. I find that, if I add even a phony date to the end, something like 0-00-00, it sorts correctly:

62G     ./Directory 0-00-00
31G     ./Directory 0-00-00/#7852
31G     ./Directory 0-00-00/#7853
78G     ./Directory 3-14-18
36G     ./Directory 3-14-18/#0986
42G     ./Directory 3-14-18/#0987
38G     ./Directory 3-21-18
38G     ./Directory 3-21-18/#1229

Additional question here would be:

How do I get the sorting to work WITHOUT having to add phony dates to everyplace I find this issue?

end edit

edit2:
Per the question from AndrewF below, I'll explain that I have a lot of archived media on hard drives. I can't run them all in my system at the same time so I thought it might be a good idea to have printed lists of what's on each drive.

To that end, I'm using tree to list the entire contents of each drive. I'm trying to use du to make a much shorter list of only directories as well.

As I get these drives organized, I expect to have to do a lot of manual digging and being able to view multiple lists should give me an ability to find redundancies that can be eliminated and deleted even though I can't have physical access to all of the drives at the same time. In other words, while I can't mount all of the drives, I can view all of the lists and use them to find redundancies, then mount the drive with the redundancy, and delete the extraneous directories. Having things sorted out of order is just going to make mistakes more likely.

end edit2

thanks,
babag

Body:
I wouldn't use tree because I don't have it on all the platforms I use. But I imagine that find . -type d is well-suited for your use case, so:

find . -type d | xargs du -sh

Depending on the directory you choose, you may get a lot of errors like "permission denied" to stderr, and if these are printing to your terminal but you want them to stop:

find . -type d 2>/dev/null | xargs du -sh 2>/dev/null

Those examples will run du once per entry returned by the find.

Note that none of these are going to be efficient -- you're going to be analyzing the same files/directories many times to get those rolled-up summary sizes. Better solutions would involve depth-first traversal and memoization, and I don't know any available tools that do it.

Edit: I don't understand your goal with the sort. If the find does not list out all entries in the order you want, you'll need to provide extra details about what exact kind of sorting you want to do. It might be best to put that sorting problem into a new more specific question.


问:
coroutine'AuthMethods._start' was never awaited
I'm just trying to get into making a bot that can read messages and reply... But I can't even execute the first example code in the documentation:

```<code>import asyncio
from telethon import TelegramClient

# Use your own values from my.telegram.org
api_id = 12345
api_hash = '0123456789abcdef0123456789abcdef'

async def main():
    # The first parameter is the .session file name (absolute paths allowed)
    async with TelegramClient('anon', api_id, api_hash).start() as client:
        await client.send_message('me', 'Hello, myself!')

asyncio.run(main())
</code>```

This is the error I keep getting:

```<code>
d:\Telegram bot\telegram bot\hello.py:10: RuntimeWarning: coroutine 'AuthMethods._start' was never awaited
  async with TelegramClient('anon', api_id, api_hash).start() as client:
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Traceback (most recent call last):
  File "d:\Telegram bot\telegram bot\hello.py", line 13, in <module>
    asyncio.run(main())
  File "C:\Users\Bruh\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "C:\Users\Bruh\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
    return future.result()
  File "d:\Telegram bot\telegram bot\hello.py", line 10, in main
    async with TelegramClient('anon', api_id, api_hash).start() as client:
AttributeError: __aenter__
</code>```

I'm not sure what's my problem exactly as I don't seem many people having the same problem, I've trible checked the dependencies and I have everything up to date (except the optional dependencies which I haven't installed)

答:
async with requires an object that has the method __aenter__ defined. TelegramClient has one but start() incorrectly documents that it returns an instance of itself -- looks like there are conditions that it will return other values.

Source: https://github.com/LonamiWebs/Telethon/blob/a00f74285cf98e2672897ea914163a5067f1caf8/telethon/_client/auth.py#L46

I can't fully reproduce for you because I don't know what Telethon is / don't have the tokens to get a client. Try examining the return-value of TelegramClient(...).start().

def main():
  started = TelegramClient('anon', api_id, api_hash).start()

  if not isinstance(started, TelegramClient):
    raise ValueError(f"Unexpected client: {started}")

  async with started as client:
    ...

asyncio.run(main())
```

Body:
I'm just trying to get into making a bot that can read messages and reply... But I can't even execute the first example code in the documentation:

import asyncio
from telethon import TelegramClient

# Use your own values from my.telegram.org
api_id = 12345
api_hash = '0123456789abcdef0123456789abcdef'

async def main():
    # The first parameter is the .session file name (absolute paths allowed)
    async with TelegramClient('anon', api_id, api_hash).start() as client:
        await client.send_message('me', 'Hello, myself!')

asyncio.run(main())

This is the error I keep getting:

d:\Telegram bot\telegram bot\hello.py:10: RuntimeWarning: coroutine 'AuthMethods._start' was never awaited
  async with TelegramClient('anon', api_id, api_hash).start() as client:
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Traceback (most recent call last):
  File "d:\Telegram bot\telegram bot\hello.py", line 13, in <module>
    asyncio.run(main())
  File "C:\Users\Bruh\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "C:\Users\Bruh\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
    return future.result()
  File "d:\Telegram bot\telegram bot\hello.py", line 10, in main
    async with TelegramClient('anon', api_id, api_hash).start() as client:
AttributeError: __aenter__

I'm not sure what's my problem exactly as I don't seem many people having the same problem, I've trible checked the dependencies and I have everything up to date (except the optional dependencies which I haven't installed)


问:
Adding padding in call to Matplotlib's PdfPages
I've got a few figures that I'm saving to a PDF file with Matplotlib's PdfPages backend. Unfortunately some of my figures are being inserted into the PDF file with a good portion of the y axis labels truncated. How do I specify that additional space should be added to avoid the label truncation? I've tried invoking the subplot_adjust command and passing left= and pad= parameters to no avail.

Any additional suggestions are most welcome!

Chris

答:
When you save your pdf using plt.savefig, use bbox_inches and pad_inches parameters to specify padding:

```<code>plt.savefig('test.pdf', bbox_inches='tight', pad_inches=1)
</code>```

Body:
When you save your pdf using plt.savefig, use bbox_inches and pad_inches parameters to specify padding:

plt.savefig('test.pdf', bbox_inches='tight', pad_inches=1)


问:
Find a substring in cells across multiple columns in a Pandas dataframe
I have a large DataFrame with 50+ columns which I'm simplifying here below:

```<code>students = [('Samurai', 34, '777.0', 'usa--->jp', 'usd--->yen') ,
            ('Jack', 31, '555.5','usa','usd') ,
            ('Mojo', 16,'488.1','n/a','n/a') ,
            ('Jojo', 32,'119.11','uk--->usa','pound--->usd')]

# Create a DataFrame object
df = pd.DataFrame(students, columns=['Name', 'Age', 'Balance', 'Country','Currency'])
</code>```

I'm trying to find

a) whether there are any instances of '--->' in any of the cells across the DataFrame?

b) if so where? (optional)

So far I've tried 2 approaches

```<code>boolDf = df.isin(['--->']).any().any()
</code>```

this only works for strings not substrings

```<code>columns = list(df)
for col in columns:
    df[col].str.find('--->', 0).any()
</code>```

I get:

```<code>AttributeError: Can only use .str accessor with string values!
</code>```

(I believe this may only work for columns with string types)

Would appreciate any help. Open to other approaches as well.

答:
Many solutions, here's another.

```<code>pd.DataFrame({
    col: df[col].str.contains('--->') for col in df.select_dtypes(include=['object'])
})

    Name  Balance  Country  Currency
0  False    False     True      True
1  False    False    False     False
2  False    False    False     False
3  False    False     True      True
</code>```

And another

```<code>pd.concat([s.str.contains('--->') for col, s in df.iteritems()
    if hasattr(s, 'str')], axis=1)
</code>```

Body:
I have a large DataFrame with 50+ columns which I'm simplifying here below:

students = [('Samurai', 34, '777.0', 'usa--->jp', 'usd--->yen') ,
            ('Jack', 31, '555.5','usa','usd') ,
            ('Mojo', 16,'488.1','n/a','n/a') ,
            ('Jojo', 32,'119.11','uk--->usa','pound--->usd')]

# Create a DataFrame object
df = pd.DataFrame(students, columns=['Name', 'Age', 'Balance', 'Country','Currency'])

I'm trying to find

a) whether there are any instances of '--->' in any of the cells across the DataFrame?

b) if so where? (optional)

So far I've tried 2 approaches

boolDf = df.isin(['--->']).any().any()

this only works for strings not substrings

columns = list(df)
for col in columns:
    df[col].str.find('--->', 0).any()

I get:

AttributeError: Can only use .str accessor with string values!

(I believe this may only work for columns with string types)

Would appreciate any help. Open to other approaches as well.

Body:
Many solutions, here's another.

pd.DataFrame({
    col: df[col].str.contains('--->') for col in df.select_dtypes(include=['object'])
})

    Name  Balance  Country  Currency
0  False    False     True      True
1  False    False    False     False
2  False    False    False     False
3  False    False     True      True

And another

pd.concat([s.str.contains('--->') for col, s in df.iteritems()
    if hasattr(s, 'str')], axis=1)


问:
How to keep focusing on the client after it's moved to a new tag in Awesome WM?
How to make the Awesome's window(client) moving behavior the similar like  DWM's ViewonTag patch

Follow a window to the tag it is being moved to.

Patch 20210312 prevents the window being followed if it is being moved
to the "all" tag.

What code should I write here?

```<code>        awful.key({ modkey, "Shift" }, "#" .. i + 9,
                  function ()
                      if client.focus then
                          local tag = client.focus.screen.tags[i]
                          if tag then
                              client.focus:move_to_tag(tag)
                            ---   ???????? ---
                            ---   How to follow the client window? ---
                          end
                     end
                  end,
                  {description = "move focused client to tag #"..i, group = "tag"}),
</code>```

答:
After many tries I solved this. But I don't know why it needs to declare the variables screen and tag2. Why can't use tag:view_only()

```<code>-- Move client to tag.
awful.key({ modkey, "Shift" }, "#" .. i + 9,
    function ()
        if client.focus then
            local tag = client.focus.screen.tags[i]
            if tag then
                client.focus:move_to_tag(tag)
                local screen = awful.screen.focused()
                local tag2 = screen.tags[i]
                tag2:view_only()
            end
        end
    end,
    { description = "move focused client to tag #"..i, group = "tag" }
),
</code>```

Body:
How to make the Awesome's window(client) moving behavior the similar like  DWM's ViewonTag patch

Follow a window to the tag it is being moved to.

Patch 20210312 prevents the window being followed if it is being moved
to the "all" tag.

What code should I write here?

        awful.key({ modkey, "Shift" }, "#" .. i + 9,
                  function ()
                      if client.focus then
                          local tag = client.focus.screen.tags[i]
                          if tag then
                              client.focus:move_to_tag(tag)
                            ---   ???????? ---
                            ---   How to follow the client window? ---
                          end
                     end
                  end,
                  {description = "move focused client to tag #"..i, group = "tag"}),

Body:
After many tries I solved this. But I don't know why it needs to declare the variables screen and tag2. Why can't use tag:view_only()

-- Move client to tag.
awful.key({ modkey, "Shift" }, "#" .. i + 9,
    function ()
        if client.focus then
            local tag = client.focus.screen.tags[i]
            if tag then
                client.focus:move_to_tag(tag)
                local screen = awful.screen.focused()
                local tag2 = screen.tags[i]
                tag2:view_only()
            end
        end
    end,
    { description = "move focused client to tag #"..i, group = "tag" }
),


问:
ADB.exe is obsolete and has serious performance problems
I am using Windows 10 and when I launch the Virtual Device Emulator in Android Studio I keep getting the message which reads:

"The ADB binary at C:\Users\siviw\AppData\Local\Android\Sdk\platform-tools\adb.exe  is obsolete and has serious performance problems with the Android Emulator. Please update to a newer version to get significantly faster app / file transfer".

I am a new developer with little experience. What do I need to update to a newer version so that message is no longer shown?

答:
I got this error and I tried all the possible solutions that I found on every site, nothing worked.
I was working with flutter, and the command flutter doctor showed me that I need to accept a few agreements
I did that and ADB started to work

So conclusion:
If nothing works, install flutter, run flutter doctor, execute the commands that flutter doctor suggests to you. This should solve your problem

 the command was: flutter doctor --android-licenses


问:
Adding Combinations of Numbers in a Matrix
I found this link that shows you how to make a matrix with random numbers: https://www.tutorialspoint.com/how-to-create-a-matrix-with-random-values-in-r

```<code>  #random symmetric matrix with diagnoal elements as 0
 A <- matrix(runif(16), 4, 4)
A1 = A %*% t(A)

out_1 = A1 - diag(diag(A1))

         [,1]     [,2]     [,3]     [,4]
[1,]     0.00 20371.54 19136.91 18380.49
[2,] 20371.54     0.00 19392.13 19476.78
[3,] 19136.91 19392.13     0.00 16651.73
[4,] 18380.49 19476.78 16651.73     0.00
</code>```

Imagine each index corresponds to a city in this matrix (out_1) - there are 4 cities.

Any (row , column) combination corresponds to the distance between two cities (e.g. [2][3] corresponds to the distance between city 2 and city 3).

Logically, the distance between the same two cities is the same, e.g.. [2] [3] = [3] [2]

Logically, the distance between a city and itself is 0, e.g. [2] [2] = 0

Using this matrix (out_1), I want to calculate all "paths" from this matrix that have the following structure:

The path must start and end from the same city, and with the exception of the first city, no other city can be visited twice.

For example, the end goal would look something like this:

```<code>- Path 1 : [1] [2] , [2] [3], [3] [4], [4] [1] = 20371.54 + 19392.13 + 16651.73 + 18380.49 = 74795.89
- Path 2 : [2] [4] , [4] [3], [3] [1], [1] [2] = 19476.78 + 16651.73 + 19136.91 + 20371.54 =   75636.96
- ....
- Path n: [3] [4] , [4] [1], [1] [2], [2] [3] =  16651.73 + 18380.49 + 20371.54 + 19392.13 =   74795.89
</code>```

I tried to find some library in R to do this (note: I think what I am trying to do is called a "Hamiltonian Cycle of a Graph") : https://www.rdocumentation.org/packages/adagio/versions/0.8.4/topics/hamiltonian

But this did not work:

```<code>    c = c(out_1)
 hamiltonian(c, cycle = TRUE)

    Error in graph_vect2list(edges) :
      Argument 'edges' is not a correct edge list.
</code>```

How can I get a list of all such "paths" that shows the order of the cities and the total distance for each path?

Thanks!

答:
There are factorial(n-1) Hamiltonian cycles on a complete graph of order n—or half as many if you exclude reverse cycles, e.g., if you keep only one of (123) and (132) when n = 3. In some contexts, the distance from A to B is not the same as the distance from B to A, so it can be useful to include reverse cycles.

Here is an approach that counts all factorial(n-1) cycles, relying on function permutations from package gtools to do the "path-finding". There are several alternatives to gtools, which you are free to use instead.

mkX <- function(n) {
    X <- abs(crossprod(matrix(rnorm(n * n), n, n)))
    diag(X) <- 0
    X
}

roundtrips <- function(X) {
    n <- nrow(X)
    if (n < 2L) {
        trips <- matrix(integer(0L), 0L, 0L)
        distances <- double(0L)
    } else {
        trips <- cbind(1L, gtools::permutations(n - 1L, n - 1L, seq.int(2L, n)))
        distances <- apply(trips, 1L, function(i) sum(X[cbind(i, c(i[-1L], 1L))]))
    }
    list(X = X, trips = trips, distances = distances)
}

set.seed(1L)
X <- mkX(4L)
roundtrips(X)
```
<pre class="lang-none prettyprint-override"><code>$X
          [,1]      [,2]     [,3]     [,4]
[1,] 0.0000000 0.4134306 1.058161 1.029243
[2,] 0.4134306 0.0000000 1.465003 2.127536
[3,] 1.0581611 1.4650029 0.000000 2.001777
[4,] 1.0292425 2.1275361 2.001777 0.000000

$trips
     [,1] [,2] [,3] [,4]
[1,]    1    2    3    4
[2,]    1    2    4    3
[3,]    1    3    2    4
[4,]    1    3    4    2
[5,]    1    4    2    3
[6,]    1    4    3    2

$distances
[1] 4.909453 5.600905 5.679943 5.600905 5.679943 4.909453
</code>```

Here, X is a distance matrix; it need not be symmetric, but in this example it is. trips is an integer matrix whose rows define distinct Hamiltonian cycles of the graph. distances is a double vector listing the distances traversed over those cycles. When X is symmetric, the distances come in pairs corresponding to cycles and their reverses.

Choose n carefully: factorial(n-1) grows quite fast.

Body:
I found this link that shows you how to make a matrix with random numbers: https://www.tutorialspoint.com/how-to-create-a-matrix-with-random-values-in-r

  #random symmetric matrix with diagnoal elements as 0
 A <- matrix(runif(16), 4, 4)
A1 = A %*% t(A)

out_1 = A1 - diag(diag(A1))

         [,1]     [,2]     [,3]     [,4]
[1,]     0.00 20371.54 19136.91 18380.49
[2,] 20371.54     0.00 19392.13 19476.78
[3,] 19136.91 19392.13     0.00 16651.73
[4,] 18380.49 19476.78 16651.73     0.00

Imagine each index corresponds to a city in this matrix (out_1) - there are 4 cities.

Any (row , column) combination corresponds to the distance between two cities (e.g. [2][3] corresponds to the distance between city 2 and city 3).

Logically, the distance between the same two cities is the same, e.g.. [2] [3] = [3] [2]

Logically, the distance between a city and itself is 0, e.g. [2] [2] = 0

Using this matrix (out_1), I want to calculate all "paths" from this matrix that have the following structure:

The path must start and end from the same city, and with the exception of the first city, no other city can be visited twice.

For example, the end goal would look something like this:

- Path 1 : [1] [2] , [2] [3], [3] [4], [4] [1] = 20371.54 + 19392.13 + 16651.73 + 18380.49 = 74795.89
- Path 2 : [2] [4] , [4] [3], [3] [1], [1] [2] = 19476.78 + 16651.73 + 19136.91 + 20371.54 =   75636.96
- ....
- Path n: [3] [4] , [4] [1], [1] [2], [2] [3] =  16651.73 + 18380.49 + 20371.54 + 19392.13 =   74795.89

I tried to find some library in R to do this (note: I think what I am trying to do is called a "Hamiltonian Cycle of a Graph") : https://www.rdocumentation.org/packages/adagio/versions/0.8.4/topics/hamiltonian

But this did not work:

    c = c(out_1)
 hamiltonian(c, cycle = TRUE)

    Error in graph_vect2list(edges) :
      Argument 'edges' is not a correct edge list.

How can I get a list of all such "paths" that shows the order of the cities and the total distance for each path?

Thanks!

Body:
There are factorial(n-1) Hamiltonian cycles on a complete graph of order n—or half as many if you exclude reverse cycles, e.g., if you keep only one of (123) and (132) when n = 3. In some contexts, the distance from A to B is not the same as the distance from B to A, so it can be useful to include reverse cycles.

Here is an approach that counts all factorial(n-1) cycles, relying on function permutations from package gtools to do the "path-finding". There are several alternatives to gtools, which you are free to use instead.

mkX <- function(n) {
    X <- abs(crossprod(matrix(rnorm(n * n), n, n)))
    diag(X) <- 0
    X
}

roundtrips <- function(X) {
    n <- nrow(X)
    if (n < 2L) {
        trips <- matrix(integer(0L), 0L, 0L)
        distances <- double(0L)
    } else {
        trips <- cbind(1L, gtools::permutations(n - 1L, n - 1L, seq.int(2L, n)))
        distances <- apply(trips, 1L, function(i) sum(X[cbind(i, c(i[-1L], 1L))]))
    }
    list(X = X, trips = trips, distances = distances)
}

set.seed(1L)
X <- mkX(4L)
roundtrips(X)

$X
          [,1]      [,2]     [,3]     [,4]
[1,] 0.0000000 0.4134306 1.058161 1.029243
[2,] 0.4134306 0.0000000 1.465003 2.127536
[3,] 1.0581611 1.4650029 0.000000 2.001777
[4,] 1.0292425 2.1275361 2.001777 0.000000

$trips
     [,1] [,2] [,3] [,4]
[1,]    1    2    3    4
[2,]    1    2    4    3
[3,]    1    3    2    4
[4,]    1    3    4    2
[5,]    1    4    2    3
[6,]    1    4    3    2

$distances
[1] 4.909453 5.600905 5.679943 5.600905 5.679943 4.909453

Here, X is a distance matrix; it need not be symmetric, but in this example it is. trips is an integer matrix whose rows define distinct Hamiltonian cycles of the graph. distances is a double vector listing the distances traversed over those cycles. When X is symmetric, the distances come in pairs corresponding to cycles and their reverses.

Choose n carefully: factorial(n-1) grows quite fast.


问:
Exclude field from a form in JSF
I have the following question: Let's assume the code below:

```<code>...
     <h:form id="..">
        <table>

        <table border="1">
         <tr>
         <td><h:outputText value="#{msg.prompt1}"/></td>
         <td><h:inputText value="#{personBean.personData1}" />
                  <!-- This field must not participate in the form. There would be
                       other JSF form and tags here -->
              <h:commandButton action="other_action_with_ajax"/>
         </td>
         </tr>
         <tr>
         <td><h:outputText value="#{msg.promp2}"/></td>
         <td><h:inputText value="#{personBean.personData2}" /></td>
         </tr>
         <tr>
         <td><h:outputText value="#{msg.msg}"/></td>
         <td><h:commandButton action="greeting" value="#{msg.button_text}" /></td>
         </tr>
        </table>
     </h:form>
...
</code>```

I need to exclude one field from a form which is in a table (currently plane html) as this field is readonly and handled and treated differently from the others. It will be part of other form which does not the wrapping form of this table. But this field must be placed in this table to be formated correctly. And I cant put form in a form. What is the best way to put two forms in one table without splitting it into two tables wrapped in forms?

答:
Just make use of the input component's readonly or disabled attribute.

E.g.

<h:inputText value="#{bean.value}" disabled="#{!bean.editable}" />
```

Setting readonly="true" will make it uneditable, but submittable. Setting disabled="true" will make it uneditable and unsubmittable (i.e. value isn't submitted to server).

Title: Exclude field from a form in JSF

Body:
I have the following question: Let's assume the code below:

...
     <h:form id="..">

         <h:outputText value="#{msg.prompt1}"/>
         <h:inputText value="#{personBean.personData1}" />

              <h:commandButton action="other_action_with_ajax"/>

         <h:outputText value="#{msg.promp2}"/>
         <h:inputText value="#{personBean.personData2}" />

         <h:outputText value="#{msg.msg}"/>
         <h:commandButton action="greeting" value="#{msg.button_text}" />

     </h:form>
...

I need to exclude one field from a form which is in a table (currently plane html) as this field is readonly and handled and treated differently from the others. It will be part of other form which does not the wrapping form of this table. But this field must be placed in this table to be formated correctly. And I cant put form in a form. What is the best way to put two forms in one table without splitting it into two tables wrapped in forms?

Body:
Just make use of the input component's readonly or disabled attribute.

E.g.

<h:inputText value="#{bean.value}" disabled="#{!bean.editable}" />

Setting readonly="true" will make it uneditable, but submittable. Setting disabled="true" will make it uneditable and unsubmittable (i.e. value isn't submitted to server).


问:
How to extract a certain substring from string using regex in python - dictionary value?
I have a str 'data' below contains some url content. using regex I want to only extract "url":"https://www.google.com". Here's what I tried so far:

```<code>impor re
url = re.findall('"url":.*', data)
</code>```

Any help would be appreciated.

{"__ref":"QXNzZXRDb250cmFjdFR5cGU6NDU0OTE3"},"decimals":null,"relayId":"QXNzZXRUeXBlOjE1MDQ5OTUxMQ==","favoritesCount":10,"isDelisted":false,"isFavorite":false,"isFrozen":false,"hasUnlockableContent":false,"tokenId":"3379","collection":{"__ref":"Q29sbGVjdGlvblR5cGU6MzY3NDA5MQ=="},"orderData":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:orderData"},"name":"Flame River Chumbi","authenticityMetadata":null,"imageUrl":"https:\u002F\u002Flh3.googleusercontent.com\u002FtM1wwmVb1dA5DadG-QXFBd1nWnqi6DRh7fL0nHgjr2eZkSMKIhcPcwSuBLEvRIgOQRuFDKiovy1kpHSGz4NciKw6oSON-_gdz8aXKw","creator":null,"assetOwners(first:1)":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:assetOwners(first:1)"},"animationUrl":null,"backgroundColor":null,"description":"Chumbi are adorable bipedal creatures that inhabit a lush and mysterious forest valley. They have a spiritual connection to the forest and use magical spells to maintain and protect it.","isListable":true,"isReportedSuspicious":false,"traits(first:100)":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:traits(first:100)"},"displayImageUrl":"https:\u002F\u002Flh3.googleusercontent.com\u002FtM1wwmVb1dA5DadG-QXFBd1nWnqi6DRh7fL0nHgjr2eZkSMKIhcPcwSuBLEvRIgOQRuFDKiovy1kpHSGz4NciKw6oSON-_gdz8aXKw","externalLink":null,"isEditableByOwner":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:isEditableByOwner"}, "url":"https:://google.com" ,"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:traits(first:100)","displayImageUrl":"https:\u002F\u002Flh3.googleusercontent.com\u002FtM1wwmVb1dA5DadG-QXFBd1nWnqi6DRh7fL0nHgjr2eZkSMKIhcPcwSuBLEvRIgOQRuFDKiovy1kpHSGz4NciKw6oSON-_gdz8aXKw","externalLink":null,"isEditableByOwner":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:isEditableByOwner"}

答:
What you want to know is non-greedy search.
Try the following regex:

import re
s = '{"__ref":"QXNzZXRDb250cmFjdFR5cGU6NDU0OTE3"},"decimals":null,"relayId":"QXNzZXRUeXBlOjE1MDQ5OTUxMQ==","favoritesCount":10,"isDelisted":false,"isFavorite":false,"isFrozen":false,"hasUnlockableContent":false,"tokenId":"3379","collection":{"__ref":"Q29sbGVjdGlvblR5cGU6MzY3NDA5MQ=="},"orderData":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:orderData"},"name":"Flame River Chumbi","authenticityMetadata":null,"imageUrl":"https:\u002F\u002Flh3.googleusercontent.com\u002FtM1wwmVb1dA5DadG-QXFBd1nWnqi6DRh7fL0nHgjr2eZkSMKIhcPcwSuBLEvRIgOQRuFDKiovy1kpHSGz4NciKw6oSON-_gdz8aXKw","creator":null,"assetOwners(first:1)":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:assetOwners(first:1)"},"animationUrl":null,"backgroundColor":null,"description":"Chumbi are adorable bipedal creatures that inhabit a lush and mysterious forest valley. They have a spiritual connection to the forest and use magical spells to maintain and protect it.","isListable":true,"isReportedSuspicious":false,"traits(first:100)":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:traits(first:100)"},"displayImageUrl":"https:\u002F\u002Flh3.googleusercontent.com\u002FtM1wwmVb1dA5DadG-QXFBd1nWnqi6DRh7fL0nHgjr2eZkSMKIhcPcwSuBLEvRIgOQRuFDKiovy1kpHSGz4NciKw6oSON-_gdz8aXKw","externalLink":null,"isEditableByOwner":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:isEditableByOwner"}, "url":"https:://google.com" ,"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:traits(first:100)","displayImageUrl":"https:\u002F\u002Flh3.googleusercontent.com\u002FtM1wwmVb1dA5DadG-QXFBd1nWnqi6DRh7fL0nHgjr2eZkSMKIhcPcwSuBLEvRIgOQRuFDKiovy1kpHSGz4NciKw6oSON-_gdz8aXKw","externalLink":null,"isEditableByOwner":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:isEditableByOwner"}'
results = re.findall(r'"url":".*?"', s)
```
<hr />
<h3>Answer to the OP's comment:</h3>
<p>You can use grouping.</p>
<pre class="lang-py prettyprint-override"><code>import re
s = '{"__ref":"QXNzZXRDb250cmFjdFR5cGU6NDU0OTE3"},"decimals":null,"relayId":"QXNzZXRUeXBlOjE1MDQ5OTUxMQ==","favoritesCount":10,"isDelisted":false,"isFavorite":false,"isFrozen":false,"hasUnlockableContent":false,"tokenId":"3379","collection":{"__ref":"Q29sbGVjdGlvblR5cGU6MzY3NDA5MQ=="},"orderData":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:orderData"},"name":"Flame River Chumbi","authenticityMetadata":null,"imageUrl":"https:\u002F\u002Flh3.googleusercontent.com\u002FtM1wwmVb1dA5DadG-QXFBd1nWnqi6DRh7fL0nHgjr2eZkSMKIhcPcwSuBLEvRIgOQRuFDKiovy1kpHSGz4NciKw6oSON-_gdz8aXKw","creator":null,"assetOwners(first:1)":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:assetOwners(first:1)"},"animationUrl":null,"backgroundColor":null,"description":"Chumbi are adorable bipedal creatures that inhabit a lush and mysterious forest valley. They have a spiritual connection to the forest and use magical spells to maintain and protect it.","isListable":true,"isReportedSuspicious":false,"traits(first:100)":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:traits(first:100)"},"displayImageUrl":"https:\u002F\u002Flh3.googleusercontent.com\u002FtM1wwmVb1dA5DadG-QXFBd1nWnqi6DRh7fL0nHgjr2eZkSMKIhcPcwSuBLEvRIgOQRuFDKiovy1kpHSGz4NciKw6oSON-_gdz8aXKw","externalLink":null,"isEditableByOwner":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:isEditableByOwner"}, "url":"https:://google.com" ,"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:traits(first:100)","displayImageUrl":"https:\u002F\u002Flh3.googleusercontent.com\u002FtM1wwmVb1dA5DadG-QXFBd1nWnqi6DRh7fL0nHgjr2eZkSMKIhcPcwSuBLEvRIgOQRuFDKiovy1kpHSGz4NciKw6oSON-_gdz8aXKw","externalLink":null,"isEditableByOwner":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:isEditableByOwner"}'
results = re.findall(r'"url":"(.*?)"', s)
</code>```

Body:
I have a str 'data' below contains some url content. using regex I want to only extract "url":"https://www.google.com". Here's what I tried so far:

impor re
url = re.findall('"url":.*', data)

Any help would be appreciated.

{"__ref":"QXNzZXRDb250cmFjdFR5cGU6NDU0OTE3"},"decimals":null,"relayId":"QXNzZXRUeXBlOjE1MDQ5OTUxMQ==","favoritesCount":10,"isDelisted":false,"isFavorite":false,"isFrozen":false,"hasUnlockableContent":false,"tokenId":"3379","collection":{"__ref":"Q29sbGVjdGlvblR5cGU6MzY3NDA5MQ=="},"orderData":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:orderData"},"name":"Flame River Chumbi","authenticityMetadata":null,"imageUrl":"https:\u002F\u002Flh3.googleusercontent.com\u002FtM1wwmVb1dA5DadG-QXFBd1nWnqi6DRh7fL0nHgjr2eZkSMKIhcPcwSuBLEvRIgOQRuFDKiovy1kpHSGz4NciKw6oSON-_gdz8aXKw","creator":null,"assetOwners(first:1)":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:assetOwners(first:1)"},"animationUrl":null,"backgroundColor":null,"description":"Chumbi are adorable bipedal creatures that inhabit a lush and mysterious forest valley. They have a spiritual connection to the forest and use magical spells to maintain and protect it.","isListable":true,"isReportedSuspicious":false,"traits(first:100)":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:traits(first:100)"},"displayImageUrl":"https:\u002F\u002Flh3.googleusercontent.com\u002FtM1wwmVb1dA5DadG-QXFBd1nWnqi6DRh7fL0nHgjr2eZkSMKIhcPcwSuBLEvRIgOQRuFDKiovy1kpHSGz4NciKw6oSON-_gdz8aXKw","externalLink":null,"isEditableByOwner":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:isEditableByOwner"}, "url":"https:://google.com" ,"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:traits(first:100)","displayImageUrl":"https:\u002F\u002Flh3.googleusercontent.com\u002FtM1wwmVb1dA5DadG-QXFBd1nWnqi6DRh7fL0nHgjr2eZkSMKIhcPcwSuBLEvRIgOQRuFDKiovy1kpHSGz4NciKw6oSON-_gdz8aXKw","externalLink":null,"isEditableByOwner":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:isEditableByOwner"}

Body:
What you want to know is non-greedy search.
Try the following regex:

import re
s = '{"__ref":"QXNzZXRDb250cmFjdFR5cGU6NDU0OTE3"},"decimals":null,"relayId":"QXNzZXRUeXBlOjE1MDQ5OTUxMQ==","favoritesCount":10,"isDelisted":false,"isFavorite":false,"isFrozen":false,"hasUnlockableContent":false,"tokenId":"3379","collection":{"__ref":"Q29sbGVjdGlvblR5cGU6MzY3NDA5MQ=="},"orderData":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:orderData"},"name":"Flame River Chumbi","authenticityMetadata":null,"imageUrl":"https:\u002F\u002Flh3.googleusercontent.com\u002FtM1wwmVb1dA5DadG-QXFBd1nWnqi6DRh7fL0nHgjr2eZkSMKIhcPcwSuBLEvRIgOQRuFDKiovy1kpHSGz4NciKw6oSON-_gdz8aXKw","creator":null,"assetOwners(first:1)":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:assetOwners(first:1)"},"animationUrl":null,"backgroundColor":null,"description":"Chumbi are adorable bipedal creatures that inhabit a lush and mysterious forest valley. They have a spiritual connection to the forest and use magical spells to maintain and protect it.","isListable":true,"isReportedSuspicious":false,"traits(first:100)":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:traits(first:100)"},"displayImageUrl":"https:\u002F\u002Flh3.googleusercontent.com\u002FtM1wwmVb1dA5DadG-QXFBd1nWnqi6DRh7fL0nHgjr2eZkSMKIhcPcwSuBLEvRIgOQRuFDKiovy1kpHSGz4NciKw6oSON-_gdz8aXKw","externalLink":null,"isEditableByOwner":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:isEditableByOwner"}, "url":"https:://google.com" ,"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:traits(first:100)","displayImageUrl":"https:\u002F\u002Flh3.googleusercontent.com\u002FtM1wwmVb1dA5DadG-QXFBd1nWnqi6DRh7fL0nHgjr2eZkSMKIhcPcwSuBLEvRIgOQRuFDKiovy1kpHSGz4NciKw6oSON-_gdz8aXKw","externalLink":null,"isEditableByOwner":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:isEditableByOwner"}'
results = re.findall(r'"url":".*?"', s)

Answer to the OP's comment:

You can use grouping.

import re
s = '{"__ref":"QXNzZXRDb250cmFjdFR5cGU6NDU0OTE3"},"decimals":null,"relayId":"QXNzZXRUeXBlOjE1MDQ5OTUxMQ==","favoritesCount":10,"isDelisted":false,"isFavorite":false,"isFrozen":false,"hasUnlockableContent":false,"tokenId":"3379","collection":{"__ref":"Q29sbGVjdGlvblR5cGU6MzY3NDA5MQ=="},"orderData":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:orderData"},"name":"Flame River Chumbi","authenticityMetadata":null,"imageUrl":"https:\u002F\u002Flh3.googleusercontent.com\u002FtM1wwmVb1dA5DadG-QXFBd1nWnqi6DRh7fL0nHgjr2eZkSMKIhcPcwSuBLEvRIgOQRuFDKiovy1kpHSGz4NciKw6oSON-_gdz8aXKw","creator":null,"assetOwners(first:1)":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:assetOwners(first:1)"},"animationUrl":null,"backgroundColor":null,"description":"Chumbi are adorable bipedal creatures that inhabit a lush and mysterious forest valley. They have a spiritual connection to the forest and use magical spells to maintain and protect it.","isListable":true,"isReportedSuspicious":false,"traits(first:100)":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:traits(first:100)"},"displayImageUrl":"https:\u002F\u002Flh3.googleusercontent.com\u002FtM1wwmVb1dA5DadG-QXFBd1nWnqi6DRh7fL0nHgjr2eZkSMKIhcPcwSuBLEvRIgOQRuFDKiovy1kpHSGz4NciKw6oSON-_gdz8aXKw","externalLink":null,"isEditableByOwner":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:isEditableByOwner"}, "url":"https:://google.com" ,"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:traits(first:100)","displayImageUrl":"https:\u002F\u002Flh3.googleusercontent.com\u002FtM1wwmVb1dA5DadG-QXFBd1nWnqi6DRh7fL0nHgjr2eZkSMKIhcPcwSuBLEvRIgOQRuFDKiovy1kpHSGz4NciKw6oSON-_gdz8aXKw","externalLink":null,"isEditableByOwner":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:isEditableByOwner"}'
results = re.findall(r'"url":"(.*?)"', s)


问:
Has anyone successfully run a MoveNet model using tflite in Flutter?
I am trying to use MoveNet in Flutter using tflite. If anyone has experience with it or example with the implementation, an example would be appreciated.</p>

答: I have successfully implemented MoveNet singlepose lightning model with tflite_flutter on my Flutter application. You can refer to this repo I made: https://github.com/AGRapista/FitnessInstructor The code you should be interested in is in lib/test.dart</p>


问:
ActionController::InvalidAuthenticityToken in ActiveAdmin::Devise::SessionsController#create
I'm using Ruby on Rails 5 Api app with modification to enable Active Admin.
Everything was fine until now. I don't remember doing any changes in the app, but now, if I delete cookies and etc on the browser, I can't login to the active admin app and this error is what I get:

I tried to add in application controller both

```<code>protect_from_forgery :with => :exception
</code>```

and

```<code>protect_from_forgery :with => :null_session
</code>```

but none have worked.
This is my application controller:

class ApplicationController < ActionController::Base
  # protect_from_forgery :with => :exception
  before_action :configure_permitted_parameters, if: :devise_controller?

  protected
  def configure_permitted_parameters
    attributes = [:name]
    devise_parameter_sanitizer.permit(:sign_up, keys: attributes)
  end
end```

I don't know what causing it and how to solve it.
Thanks beforehand.

答:
In my context, I have a custom admin page and to solve I put a authenticity_token hidden field. Like below:

```<code>form method: :post, action: admin_templates_save_template_path do |f|
   f.label "label", for: :base_proposal_url
   f.input id: :base_proposal_url, name: :base_proposal_url

   ### field to handle authenticity token
   f.input type: :hidden, name: :authenticity_token

   f.button "Save", type: :submit
end
</code>```

Body:
I'm using Ruby on Rails 5 Api app with modification to enable Active Admin.
Everything was fine until now. I don't remember doing any changes in the app, but now, if I delete cookies and etc on the browser, I can't login to the active admin app and this error is what I get:

I tried to add in application controller both

protect_from_forgery :with => :exception

and

protect_from_forgery :with => :null_session

but none have worked.
This is my application controller:

class ApplicationController < ActionController::Base
  # protect_from_forgery :with => :exception
  before_action :configure_permitted_parameters, if: :devise_controller?

  protected
  def configure_permitted_parameters
    attributes = [:name]
    devise_parameter_sanitizer.permit(:sign_up, keys: attributes)
  end
end

I don't know what causing it and how to solve it.
Thanks beforehand.

Body:
In my context, I have a custom admin page and to solve I put a authenticity_token hidden field. Like below:

form method: :post, action: admin_templates_save_template_path do |f|
   f.label "label", for: :base_proposal_url
   f.input id: :base_proposal_url, name: :base_proposal_url

   ### field to handle authenticity token
   f.input type: :hidden, name: :authenticity_token

   f.button "Save", type: :submit
end


问:
Testing External Api in ruby using rspec
I am working on a project where I have to test an external api which is making call to github.

Let's take the code below as example, the class below does not have intializer

```<code>Class CodeReviewSignedOff

  def pullrequestreview(github)
     #the following line return a json response, it require two parameter a string and a number

     github.client.pull_request_reviews("string",number).each do |github|
       #block of code which perform some operation
     end

     return count #return integer response
   end
end
</code>```

As you can see my class CodeReviewSignedOff relies on the github object which is defined in my existing project and using the object to make external API call.
But the thing is, I do not want to actually call the API.

I want stub request github.client.pull_request_reviews

```<code>allow(github).to receive_message_chain(:client,:pull_request_review_requests).and_return json
</code>```

My question here is,
How should I return the json response because if I include it in the double quote it will be interpreted as string.

My second question
How do I test my pullrequestreview function.

```<code>github=double #I am creating a fake github
object=CodeReviewSignedOff.new
expect(pullrequestreview).with(double).and_return(3)

</code>```

Is the above logic correct?

答:
Good question!

Disclaimer: I'm still learning about RoR, but I can try to answer this question as best as I can. If anyone has suggestions about how I can improve my response, please let me know!

Testing a class method (using stubs)

So, in order to test your method called "pullrequestreview", you'll need to stub a method within the Github::Client class. I personally have not worked with GitHub's API, so let's assume that it is a static class with a few class methods (including pull_request_reviews).
(Note: I renamed "pullrequestreview" to pull_request_review, because it is more idiomatic in Ruby)

In the example below, I stubbed Github::Client.pull_request_reviews, so that it will return res_data whenever it is called:

Github::Client.stubs(:pull_request_reviews).returns(res_data)

Next, I use a "factory" to generate a github_client argument to pass into code_review_sign_off.pull_request_review. Since the GitHub method is stubbed, it doesn't really matter what I pass into it. In more complex test scenarios, it might be a good idea to make use of a factory bot gem to build out different GitHub related objects (with different trait options). For example, using a factory, you could define a new github_client with a "pull_request" trait like so:

github_client = create(:github_client, :with_pull_request)

In your post, code_review_sign_off.pull_request_review is expecting an iterable object from GitHub. Let's assume that code_review_sign_off.pull_request_review returns the number of elements within the array. Since I have control over GitHub's response, I know that only one element will be returned, so the result should be 1, which I assert using:

assert_equal pull_request_review_response, 1

So, in general when testing, you want to issolate the function that you're interested in and use stubs to keep everything else constant.

```<code>require 'test_helper'

class CodeReviewSignedOffTest < ActionDispatch::IntegrationTest
  test 'with CodeReviewSignedOff method' do
    res_data = [{
      :id => 1,
      :data => "some_data"
    }]

    Github::Client.stubs(:pull_request_reviews).returns(res_data)

    github_client = create(:github_client, :with_pull_request)
    code_review_sign_off = CodeReviewSignedOff.new
    pull_request_review_response = code_review_sign_off.pull_request_review(github_client)
      ...

      assert_equal pull_request_review_response, 1
    end
end
</code>```

(Note: I'm using the mocha/minitest in the examples)

Bonus: Mocking an API endpoint

So, first, I am going to assume you have your test environment for RSpec properly configured (you ran rails generate rspec:install command) and you have the appropriate /spec directory.

The first step to mocking an API endpoint is to stub the calls to the actual endpoints by using a gem like WebMock. So, install the gem and add require 'webmock/rspec' to /spec/spec_helper.rb

Within /spec/spec_helper.rb you'll need to define a few things,

First, add the following to ensure that you're not continuing to make real calls to the API:
WebMock.disable_net_connect!(allow_localhost: true)

Next, you'll need a stub for each API endpoint that you're mocking. For example, in your case, you'd need to define something like:

```<code>RSpec.configure do |config|
  config.before(:each) do
    pull_request_review_response = [
      {
        "id": 80,
        "node_id": "MDE3OlB1bGxSZXF1ZXN0UmV2aWV3ODA=",
        "user": {
          "login": "octocat",
          "id": 1,
          "node_id": "MDQ6VXNlcjE=",
          "avatar_url": "https://github.com/images/error/octocat_happy.gif",
          "gravatar_id": "",
          "url": "https://api.github.com/users/octocat",
          "html_url": "https://github.com/octocat",
          "followers_url": "https://api.github.com/users/octocat/followers",
          "following_url": "https://api.github.com/users/octocat/following{/other_user}",
          "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}",
          "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}",
          "subscriptions_url": "https://api.github.com/users/octocat/subscriptions",
          "organizations_url": "https://api.github.com/users/octocat/orgs",
          "repos_url": "https://api.github.com/users/octocat/repos",
          "events_url": "https://api.github.com/users/octocat/events{/privacy}",
          "received_events_url": "https://api.github.com/users/octocat/received_events",
          "type": "User",
          "site_admin": false
        },
        "body": "Here is the body for the review.",
        "state": "APPROVED",
        "html_url": "https://github.com/octocat/Hello-World/pull/12#pullrequestreview-80",
        "pull_request_url": "https://api.github.com/repos/octocat/Hello-World/pulls/12",
        "_links": {
          "html": {
            "href": "https://github.com/octocat/Hello-World/pull/12#pullrequestreview-80"
          },
          "pull_request": {
            "href": "https://api.github.com/repos/octocat/Hello-World/pulls/12"
          }
        },
        "submitted_at": "2019-11-17T17:43:43Z",
        "commit_id": "ecdd80bb57125d7ba9641ffaa4d7d2c19d3f3091",
        "author_association": "COLLABORATOR"
      }
    ]

    owner = 'octocat',
    repo = 'hello-world',
    pull_number = 42
    stub_request(:get, "https://api.github.com/repos/#{owner}/#{repo}/pulls/#{pull_number}/reviews").
      to_return(status: 200, body: pull_request_review_response.to_json,
        headers: {'Accept'=>'*/*', 'User-Agent'=>'Ruby'})
  end

  # ....
end
</code>```

The important part of this code is stub_request which takes an HTTP request method, a URL path, and it returns the arguments passed into to_return (as an HTTP response). The response object will include a status, body, and a header.

I used the examples from the WebMock README and the API doc from GitHub to produce the example above (Note: It is untested).

Now, you can define a new test that calls the Mock endpoint:

```<code>require 'spec_helper'

class CodeReviewSignedOffTest < ActionDispatch::IntegrationTest
 test 'GET pull_request_review_response endpoint from GitHub mock' do
     uri = URI('https://api.github.com/repos/octocat/hello-world/pulls/42/reviews')
     response = Net::HTTP.get(uri)
     data = JSON.parse(response&.body)

     ...
   end
end
</code>```

Hopefully you'll see the data you defined within your mock API come through. I haven't tested this code, so it might require some debugging.

Let me know if you have any questions or run into trouble writing your tests! Good luck.

Body:
I am working on a project where I have to test an external api which is making call to github.

Let's take the code below as example, the class below does not have intializer

Class CodeReviewSignedOff

  def pullrequestreview(github)
     #the following line return a json response, it require two parameter a string and a number

     github.client.pull_request_reviews("string",number).each do |github|
       #block of code which perform some operation
     end

     return count #return integer response
   end
end

As you can see my class CodeReviewSignedOff relies on the github object which is defined in my existing project and using the object to make external API call.
But the thing is, I do not want to actually call the API.

I want stub request github.client.pull_request_reviews

allow(github).to receive_message_chain(:client,:pull_request_review_requests).and_return json

My question here is,
How should I return the json response because if I include it in the double quote it will be interpreted as string.

My second question
How do I test my pullrequestreview function.

github=double #I am creating a fake github
object=CodeReviewSignedOff.new
expect(pullrequestreview).with(double).and_return(3)

Is the above logic correct?

Body:
Good question!

Disclaimer: I'm still learning about RoR, but I can try to answer this question as best as I can. If anyone has suggestions about how I can improve my response, please let me know!

Testing a class method (using stubs)

So, in order to test your method called "pullrequestreview", you'll need to stub a method within the Github::Client class. I personally have not worked with GitHub's API, so let's assume that it is a static class with a few class methods (including pull_request_reviews).
(Note: I renamed "pullrequestreview" to pull_request_review, because it is more idiomatic in Ruby)

In the example below, I stubbed Github::Client.pull_request_reviews, so that it will return res_data whenever it is called:

Github::Client.stubs(:pull_request_reviews).returns(res_data)

Next, I use a "factory" to generate a github_client argument to pass into code_review_sign_off.pull_request_review. Since the GitHub method is stubbed, it doesn't really matter what I pass into it. In more complex test scenarios, it might be a good idea to make use of a factory bot gem to build out different GitHub related objects (with different trait options). For example, using a factory, you could define a new github_client with a "pull_request" trait like so:

github_client = create(:github_client, :with_pull_request)

In your post, code_review_sign_off.pull_request_review is expecting an iterable object from GitHub. Let's assume that code_review_sign_off.pull_request_review returns the number of elements within the array. Since I have control over GitHub's response, I know that only one element will be returned, so the result should be 1, which I assert using:

assert_equal pull_request_review_response, 1

So, in general when testing, you want to issolate the function that you're interested in and use stubs to keep everything else constant.

require 'test_helper'

class CodeReviewSignedOffTest < ActionDispatch::IntegrationTest
  test 'with CodeReviewSignedOff method' do
    res_data = [{
      :id => 1,
      :data => "some_data"
    }]

    Github::Client.stubs(:pull_request_reviews).returns(res_data)

    github_client = create(:github_client, :with_pull_request)
    code_review_sign_off = CodeReviewSignedOff.new
    pull_request_review_response = code_review_sign_off.pull_request_review(github_client)
      ...

      assert_equal pull_request_review_response, 1
    end
end

(Note: I'm using the mocha/minitest in the examples)

Bonus: Mocking an API endpoint

So, first, I am going to assume you have your test environment for RSpec properly configured (you ran rails generate rspec:install command) and you have the appropriate /spec directory.

The first step to mocking an API endpoint is to stub the calls to the actual endpoints by using a gem like WebMock. So, install the gem and add require 'webmock/rspec' to /spec/spec_helper.rb

Within /spec/spec_helper.rb you'll need to define a few things,

First, add the following to ensure that you're not continuing to make real calls to the API:
WebMock.disable_net_connect!(allow_localhost: true)

Next, you'll need a stub for each API endpoint that you're mocking. For example, in your case, you'd need to define something like:

RSpec.configure do |config|
  config.before(:each) do
    pull_request_review_response = [
      {
        "id": 80,
        "node_id": "MDE3OlB1bGxSZXF1ZXN0UmV2aWV3ODA=",
        "user": {
          "login": "octocat",
          "id": 1,
          "node_id": "MDQ6VXNlcjE=",
          "avatar_url": "https://github.com/images/error/octocat_happy.gif",
          "gravatar_id": "",
          "url": "https://api.github.com/users/octocat",
          "html_url": "https://github.com/octocat",
          "followers_url": "https://api.github.com/users/octocat/followers",
          "following_url": "https://api.github.com/users/octocat/following{/other_user}",
          "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}",
          "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}",
          "subscriptions_url": "https://api.github.com/users/octocat/subscriptions",
          "organizations_url": "https://api.github.com/users/octocat/orgs",
          "repos_url": "https://api.github.com/users/octocat/repos",
          "events_url": "https://api.github.com/users/octocat/events{/privacy}",
          "received_events_url": "https://api.github.com/users/octocat/received_events",
          "type": "User",
          "site_admin": false
        },
        "body": "Here is the body for the review.",
        "state": "APPROVED",
        "html_url": "https://github.com/octocat/Hello-World/pull/12#pullrequestreview-80",
        "pull_request_url": "https://api.github.com/repos/octocat/Hello-World/pulls/12",
        "_links": {
          "html": {
            "href": "https://github.com/octocat/Hello-World/pull/12#pullrequestreview-80"
          },
          "pull_request": {
            "href": "https://api.github.com/repos/octocat/Hello-World/pulls/12"
          }
        },
        "submitted_at": "2019-11-17T17:43:43Z",
        "commit_id": "ecdd80bb57125d7ba9641ffaa4d7d2c19d3f3091",
        "author_association": "COLLABORATOR"
      }
    ]

    owner = 'octocat',
    repo = 'hello-world',
    pull_number = 42
    stub_request(:get, "https://api.github.com/repos/#{owner}/#{repo}/pulls/#{pull_number}/reviews").
      to_return(status: 200, body: pull_request_review_response.to_json,
        headers: {'Accept'=>'*/*', 'User-Agent'=>'Ruby'})
  end

  # ....
end

The important part of this code is stub_request which takes an HTTP request method, a URL path, and it returns the arguments passed into to_return (as an HTTP response). The response object will include a status, body, and a header.

I used the examples from the WebMock README and the API doc from GitHub to produce the example above (Note: It is untested).

Now, you can define a new test that calls the Mock endpoint:

require 'spec_helper'

class CodeReviewSignedOffTest < ActionDispatch::IntegrationTest
 test 'GET pull_request_review_response endpoint from GitHub mock' do
     uri = URI('https://api.github.com/repos/octocat/hello-world/pulls/42/reviews')
     response = Net::HTTP.get(uri)
     data = JSON.parse(response&.body)

     ...
   end
end

Hopefully you'll see the data you defined within your mock API come through. I haven't tested this code, so it might require some debugging.

Let me know if you have any questions or run into trouble writing your tests! Good luck.


问:
Strange behavior of (python) str.split when using the default sep value (None)
Does anyone have a clear way to explain the rule regarding str.split(sep=None)? The Docstring provides some explanation but not enough to understand the following behaviors

```<code>>>> s = '\n Hello\t World\nOpps\t '
>>> print(s.split()) #by default sep = None
['Hello', 'World', 'Opps']
>>> print(s.split(maxsplit = 1))
['Hello', 'World\nOpps\t ']
</code>```

The first print seems reasonable since it splits whenever whitespace appears, and then dump all the empty strings.

The second one is a bit harder to understanding: if it only splits once, then it should condiser the 1st '\n' as the delimiter and results in an empty string '' (which should be dumped next) and ' Hello World\nOpps\t'.

Thank you in advance for any consistent and logical explanation you may provide.

PS: I have included the Docstring in below, and I am aware of this question, and an answer there offers some help but a clear rule with official source is still missing. Without official source explanation, a rule is just something for users to memorize without understanding.

sep

The delimiter according which to split the string.
None (the default value) means split according to any whitespace,
and discard empty strings from the result.

答:
Since the overflow FAQ and this stackoverflow blog post stated that it is encouraged to answer one's own question, I am posting a possible interpretation I can think of (edited after seeing the answer provided by @juanpa-arrivillaga and reading the official doc): when sep=None, the special rule for str.split is as follows.

Attempt to remove all the leading whitespace(s)

As a convention, runs of consecutive whitespace are regarded as a single separator according to the official doc.

Apply the split once at a time using the convention of item 1 until maxsplit is reached.

Disregard any empty string in the resulted list.
An interesting observation is that even when maxsplit=0, python still conducts item 1, as illustrated by the following example.

```<code>>>> s = '\n Hello\t World\nOpps\t '
>>> print(s.split(maxsplit = 0))
['Hello\t World\nOpps\t ']
>>> print(s.split(maxsplit = 1))
['Hello', 'World\nOpps\t ']
>>> print(s.split(maxsplit = 2))
['Hello', 'World', 'Opps\t ']
>>> print(s.split(maxsplit = 3))
['Hello', 'World', 'Opps']
</code>```

Body:
Does anyone have a clear way to explain the rule regarding str.split(sep=None)? The Docstring provides some explanation but not enough to understand the following behaviors

>>> s = '\n Hello\t World\nOpps\t '
>>> print(s.split()) #by default sep = None
['Hello', 'World', 'Opps']
>>> print(s.split(maxsplit = 1))
['Hello', 'World\nOpps\t ']

The first print seems reasonable since it splits whenever whitespace appears, and then dump all the empty strings.

The second one is a bit harder to understanding: if it only splits once, then it should condiser the 1st '\n' as the delimiter and results in an empty string '' (which should be dumped next) and ' Hello World\nOpps\t'.

Thank you in advance for any consistent and logical explanation you may provide.

PS: I have included the Docstring in below, and I am aware of this question, and an answer there offers some help but a clear rule with official source is still missing. Without official source explanation, a rule is just something for users to memorize without understanding.

sep

The delimiter according which to split the string.
None (the default value) means split according to any whitespace,
and discard empty strings from the result.

Body:
Since the overflow FAQ and this stackoverflow blog post stated that it is encouraged to answer one's own question, I am posting a possible interpretation I can think of (edited after seeing the answer provided by @juanpa-arrivillaga and reading the official doc): when sep=None, the special rule for str.split is as follows.

Attempt to remove all the leading whitespace(s)

As a convention, runs of consecutive whitespace are regarded as a single separator according to the official doc.

Apply the split once at a time using the convention of item 1 until maxsplit is reached.

Disregard any empty string in the resulted list.
An interesting observation is that even when maxsplit=0, python still conducts item 1, as illustrated by the following example.

>>> s = '\n Hello\t World\nOpps\t '
>>> print(s.split(maxsplit = 0))
['Hello\t World\nOpps\t ']
>>> print(s.split(maxsplit = 1))
['Hello', 'World\nOpps\t ']
>>> print(s.split(maxsplit = 2))
['Hello', 'World', 'Opps\t ']
>>> print(s.split(maxsplit = 3))
['Hello', 'World', 'Opps']


问:
Can I have one Repo for client which contains all repos for that client?
I have multiple clients and have multiple projects for each client. Some of the projects are forks of core projects in my GitHub.

I wanted to know the best way to structure this. Can I create one client repo, and then add all the repos for that client into directories inside the client repo? I would like to be able to pull updates from the core repos when necessary as well as have branches for each repo that's in each subdirectory.

Would I have to create a repo per client per project? I would like to avoid this because it can get messy because of the number of repositories I would have to create. Some of these repos are microapps so they have some common code as well. From my understanding, I can create subtrees on the core repository of the common code.

I'm not an expert in Github but am learning a lot and would like to make sure I structure everything correctly from the beginning. To avoid technical debt and all that jazz.

答:
The best way to structure this is to not have to fork code for each client. Forking per client is a maintenance nightmare.

Rather than trying to solve this with version control, it is better solved with release and configuration management.

Instead of writing special code per client, have your code use environment variables, configuration files, and asset directories. Then each client has their own configuration files and assets.

For example, let's say you have projects A and B. Project A gets its own repo. Project B gets its own repo. Manage these like regular software releases.

A needs secret keys from environment variables. B has customizable images and strings.

When you have a client which wants to use B, make them a repo for only their configuration files and assets.

```<code>client1.git
  B.config
  assets/
    b/
      logo.png
</code>```

Install A and B for the client. Install their config files and assets. Add their secret keys for A to their environment variables.

If a client really needs special code you can gate it behind a configuration setting. If it's really client specific, write a plugin for the client.

Body:
The best way to structure this is to not have to fork code for each client. Forking per client is a maintenance nightmare.

Rather than trying to solve this with version control, it is better solved with release and configuration management.

Instead of writing special code per client, have your code use environment variables, configuration files, and asset directories. Then each client has their own configuration files and assets.

For example, let's say you have projects A and B. Project A gets its own repo. Project B gets its own repo. Manage these like regular software releases.

A needs secret keys from environment variables. B has customizable images and strings.

When you have a client which wants to use B, make them a repo for only their configuration files and assets.

client1.git
  B.config
  assets/
    b/
      logo.png

Install A and B for the client. Install their config files and assets. Add their secret keys for A to their environment variables.

If a client really needs special code you can gate it behind a configuration setting. If it's really client specific, write a plugin for the client.


问:
Variable is empty when logged outside the block in which it is set

    let studentName: any = '';
    cy.get('app-screen').find('input[id="studentName"]').invoke('val').as('name')
    cy.get('@name').then((name) => {
      studentName = name;
      cy.log('Student Name: ' + studentName )
    })
    cy.log('Student Name: ' + studentName )
```

The code above prints the student name for the first log statement.

The log statement outside the then block is empty in test runner.

Any help as to why the value studentName is not printing outside then block? How do I get the value outside the then block?

答:
What happens is the test runner runs through the test and adds the commands it finds to the Cypress Command Queue.

When it adds the line cy.log('Student Name: ' + studentName ), it gets the value of studentName as it is before the command queue starts running, i.e when studentName = ''.

But it only performs the cy.log() later when the queue gets to that command, giving the impression studentName has not been updated.

You can defer the reading of studentName until later with a .then() Anything inside a .then callback will execute only after preceding queue commands.

let studentName: any = '';
cy.get('app-screen').find('input[id="studentName"]').invoke('val').as('name')
cy.get('@name').then((name) => {
  studentName = name;
  cy.log('Student Name: ' + studentName )
})

// Now get the updated studentName
cy.then(() => {
  cy.log('Student Name: ' + studentName )  // adds this to the queue after
                                           // all previous commands have run
})
```
<hr />
<p><strong>Other options</strong></p>
<p>If <code>student</code> object is important in a lot of tests, consider creating it in a <code>beforeEach()</code> and using <code>function()</code> form of the test</p>
<pre class="lang-js prettyprint-override"><code>beforeEach(() => {
  cy.get('app-screen')
    .find('input[id="studentName"]')
    .invoke('val')
    .as('name')
})

it('tests the student', function() {  // NOTE function not arrow function

  expect(this.name).to.eq('Saran')    // access with "this" prefix

})

it('also tests the student', function() {  // NOTE function not arrow function

  cy.log("Student: ' + this.name)    // still has value

})
</code>```

Script1.js

cy.fixture('studentData.json').then(studentData => {

  cy.get('app-screen')
    .find('input[id="studentName"]')
    .invoke('val')
    .then(name => {
      studentData.name = name
      cy.writeFile('cypress/fixtures/studentData.json', studentData)
    })
})
```
<p><strong>Script2.js</strong></p>
<pre class="lang-js prettyprint-override"><code>import studentData from 'cypress/fixtures/studentData.json'

// Don't use cy.fixture('studentData.json') here
// because the fixture command caches the data
// so update will not always be seen
</code>```

Body:
    let studentName: any = '';
    cy.get('app-screen').find('input[id="studentName"]').invoke('val').as('name')
    cy.get('@name').then((name) => {
      studentName = name;
      cy.log('Student Name: ' + studentName )
    })
    cy.log('Student Name: ' + studentName )

The code above prints the student name for the first log statement.

The log statement outside the then block is empty in test runner.

Any help as to why the value studentName is not printing outside then block? How do I get the value outside the then block?

Body:
What happens is the test runner runs through the test and adds the commands it finds to the Cypress Command Queue.

When it adds the line cy.log('Student Name: ' + studentName ), it gets the value of studentName as it is before the command queue starts running, i.e when studentName = ''.

But it only performs the cy.log() later when the queue gets to that command, giving the impression studentName has not been updated.

You can defer the reading of studentName until later with a .then() Anything inside a .then callback will execute only after preceding queue commands.

let studentName: any = '';
cy.get('app-screen').find('input[id="studentName"]').invoke('val').as('name')
cy.get('@name').then((name) => {
  studentName = name;
  cy.log('Student Name: ' + studentName )
})

// Now get the updated studentName
cy.then(() => {
  cy.log('Student Name: ' + studentName )  // adds this to the queue after
                                           // all previous commands have run
})

Other options

If student object is important in a lot of tests, consider creating it in a beforeEach() and using function() form of the test

beforeEach(() => {
  cy.get('app-screen')
    .find('input[id="studentName"]')
    .invoke('val')
    .as('name')
})

it('tests the student', function() {  // NOTE function not arrow function

  expect(this.name).to.eq('Saran')    // access with "this" prefix

})

it('also tests the student', function() {  // NOTE function not arrow function

  cy.log("Student: ' + this.name)    // still has value

})

Script1.js

cy.fixture('studentData.json').then(studentData => {

  cy.get('app-screen')
    .find('input[id="studentName"]')
    .invoke('val')
    .then(name => {
      studentData.name = name
      cy.writeFile('cypress/fixtures/studentData.json', studentData)
    })
})

Script2.js

import studentData from 'cypress/fixtures/studentData.json'

// Don't use cy.fixture('studentData.json') here
// because the fixture command caches the data
// so update will not always be seen


问:
Today's date -30 days in JavaScript
I need to get today's date -30 days but in the format of: "2016-06-08"

I have tried setDate(date.getDate() - 30); for -30 days.

I have tried date.toISOString().split('T')[0] for the format.

Both work, but somehow cannot be used together.

答:
// Format date object into a YYYY-MM-DD string
const formatDate = (date) => (date.toISOString().split('T')[0]);

const currentDate = new Date();

// Values in milliseconds
const currentDateInMs = currentDate.valueOf();
const ThirtyDaysInMs = 1000 * 60 * 60 * 24 * 30;

const calculatedDate = new Date(currentDateInMs - ThirtyDaysInMs);

console.log(formatDate(currentDate));
console.log(formatDate(calculatedDate));```

Title: Today's date -30 days in JavaScript


问:
What is Test-and-Set used for?
After reading the Test-and-Set Wikipedia entry, I am still left with the question "What would a Test-and-Set be used for?"

I realize that you can use it to implement Mutex (as described in wikipedia), but what other uses does it have?

答:
It can also be used to implement spinlock:</p>
```<code>void spin_lock(struct spinlock *lock)
{
        while (test_and_set(&lock->locked));
}
</code>```

OwnerDisplayName: Benoit

ContentLicense: CC BY-SA 2.5

Title: What is Test-and-Set used for?

Body:
It can also be used to implement spinlock:

void spin_lock(struct spinlock *lock)
{
        while (test_and_set(&lock->locked));
}


问:
I want to Consume a URL given by twitter to obtain the JSON file?
How does one consume web services that return JSON data in the response?

I am trying to build an app around twitter's API (for ex: http://search.twitter.com/search.json?q=shivkumarganesh)

I have a Twitter URL  . Now this when queried returns a JSON file. Can you help me to identify that how can I consume this in order to retrieve the results. I want to build an application around it. Please let me koow. I am using Netbeans 7 as my IDE so if there is a tutorial for such a thing in Netbeans and that too in Java then please let me know.

答: You're just needing to decode the JSON, so look into Gson: http://code.google.com/p/google-gson/</p>


问:
Printing date from Year, Month and Day columns in Pandas
I am looking to add a new column - "date" to my Pandas dataframe. Below are the first 5 rows of my dataframe:
First 5 rows of the dataframe
As seen from the image, the first column is year, second month, and third day. Below is what I have tried to do:

```<code>df['Year'] = pd.to_datetime(df[['Year','Month','Day']])
</code>```

But, I keep getting the error as below:

```<code>ValueError: cannot assemble the datetimes: time data '610101' does not match format
'%Y%m%d' (match)
</code>```

It would be great if I can get any help for the same.

答:
What about printing out what is actually showing for your selection first ?

```<code>print(df[['Year','Month','Day']])
</code>```

if the data is indeed "610101", then you would likely need to modify it with '19':

```<code>pd.to_datetime('19' + df[['Year','Month','Day']])
</code>```
```<code></code>```

Body:
I am looking to add a new column - "date" to my Pandas dataframe. Below are the first 5 rows of my dataframe:
First 5 rows of the dataframe
As seen from the image, the first column is year, second month, and third day. Below is what I have tried to do:

df['Year'] = pd.to_datetime(df[['Year','Month','Day']])

But, I keep getting the error as below:

ValueError: cannot assemble the datetimes: time data '610101' does not match format
'%Y%m%d' (match)

It would be great if I can get any help for the same.

Body:
What about printing out what is actually showing for your selection first ?

print(df[['Year','Month','Day']])

if the data is indeed "610101", then you would likely need to modify it with '19':

pd.to_datetime('19' + df[['Year','Month','Day']])


问:
How can I write characters such as § into a file using Python?
This is my code for creating the string to be written ('result' is the variable that holds the final text):

```<code>    fileobj = open('file_name.yml','a+')
    begin = initial+":0 "
    n_name = '"§'+tag+name+'§!"'
    begin_d = initial+"_desc:0 "
    n_desc = '"§3'+desc+'§!"'
    title = ' '+begin + n_name
    descript = ' '+begin_d + n_desc
    result = title+'\n'+descript
    print()
    fileobj.close()
    return result
</code>```

This is my code for actually writing it into the file:

```<code>    text = writing(initial, tag, name, desc)
    override = inserter(fileobj, country, text)
    fileobj.close()
    fileobj = open('file_name.yml','w+')
    fileobj.write(override)
    fileobj.close()
</code>```

(P.S: Override is a function which works perfectly. It returns a longer string to be written into the file.)

I have tried this with .txt and .yml files but in both cases, instead of §, this is what takes its place: xA7 (I cannot copy the actual text into the internet as it changes into the correct character. It is, however, appearing as xA7 in the file.) Everything else is unaffected, and the code runs fine.

Do let me know if I can improve the question in any way.

答:
You're running into a problem called character encoding. There are two parts to the problem - first is to get the encoding you want in the file, the second is to get the OS to use the same encoding.

The most flexible and common encoding is UTF-8, because it can handle any Unicode character while remaining backwards compatible with the very old 7-bit ASCII character set.  Most Unix-like systems like Linux will handle it automatically.

```<code>fileobj = open('file_name.yml','w+',encoding='utf-8')
</code>```

You can set your PYTHONIOENCODING environment value to make it the default.

Windows operating systems are a little trickier because they'll rarely assume UTF-8, especially if it's a Microsoft program opening the file.  There's a magic byte sequence called a BOM that will trigger Microsoft to use UTF-8 if it's at the beginning of a file.  Python can add that automatically for you:

```<code>fileobj = open('file_name.yml','w+',encoding='utf_8_sig')
</code>```

Body:
This is my code for creating the string to be written ('result' is the variable that holds the final text):

    fileobj = open('file_name.yml','a+')
    begin = initial+":0 "
    n_name = '"§'+tag+name+'§!"'
    begin_d = initial+"_desc:0 "
    n_desc = '"§3'+desc+'§!"'
    title = ' '+begin + n_name
    descript = ' '+begin_d + n_desc
    result = title+'\n'+descript
    print()
    fileobj.close()
    return result

This is my code for actually writing it into the file:

    text = writing(initial, tag, name, desc)
    override = inserter(fileobj, country, text)
    fileobj.close()
    fileobj = open('file_name.yml','w+')
    fileobj.write(override)
    fileobj.close()

(P.S: Override is a function which works perfectly. It returns a longer string to be written into the file.)

I have tried this with .txt and .yml files but in both cases, instead of §, this is what takes its place: xA7 (I cannot copy the actual text into the internet as it changes into the correct character. It is, however, appearing as xA7 in the file.) Everything else is unaffected, and the code runs fine.

Do let me know if I can improve the question in any way.

Body:
You're running into a problem called character encoding. There are two parts to the problem - first is to get the encoding you want in the file, the second is to get the OS to use the same encoding.

The most flexible and common encoding is UTF-8, because it can handle any Unicode character while remaining backwards compatible with the very old 7-bit ASCII character set.  Most Unix-like systems like Linux will handle it automatically.

fileobj = open('file_name.yml','w+',encoding='utf-8')

You can set your PYTHONIOENCODING environment value to make it the default.

Windows operating systems are a little trickier because they'll rarely assume UTF-8, especially if it's a Microsoft program opening the file.  There's a magic byte sequence called a BOM that will trigger Microsoft to use UTF-8 if it's at the beginning of a file.  Python can add that automatically for you:

fileobj = open('file_name.yml','w+',encoding='utf_8_sig')


问:
Using a Storyboard animation on a programmatically-added control
I'm trying to fade in a new control to my application's "app" area which is programmatically added after the existing controls are removed. My code looks like this:

```<code>        void settingsButton_Clicked(object sender, EventArgs e)
    {
        ContentCanvas.Children.Clear();

        // Fade in settings panel
        NameScope.SetNameScope(this, new NameScope());

        SettingsPane s = new SettingsPane();
        s.Name = "settingsPane";

        this.RegisterName(s.Name, s);
        this.Resources.Add(s.Name, s);

        Storyboard sb = new Storyboard();

        DoubleAnimation settingsFade = new DoubleAnimation();
        settingsFade.From = 0;
        settingsFade.To = 1;
        settingsFade.Duration = new Duration(TimeSpan.FromSeconds(0.33));
        settingsFade.RepeatBehavior = new RepeatBehavior(1);
        Storyboard.SetTargetName(settingsFade, s.Name);
        Storyboard.SetTargetProperty(settingsFade, new PropertyPath(UserControl.OpacityProperty));

        ContentCanvas.Children.Add(s);

        sb.Children.Add(settingsFade);
        sb.Begin();
    }
</code>```

However, when I run this code, I get the error "No applicable name scope exists to resolve the name 'settingsPane'."

What am I possibly doing wrong? I'm pretty sure I've registered everything properly :(

答:
I agree, the namescopes are probably the wrong thing to use for this scenario.  Much simpler and easier to use SetTarget rather than SetTargetName.  </p>

<p>In case it helps anyone else, here's what I used to highlight a particular cell in a table with a highlight that decays to nothing. It's a little like the StackOverflow highlight when you add a new answer.   </p>

```<code>    TableCell cell = table.RowGroups[0].Rows[row].Cells[col];

    // The cell contains just one paragraph; it is the first block
    Paragraph p = (Paragraph)cell.Blocks.FirstBlock;

    // Animate the paragraph: fade the background from Yellow to White,
    // once, through a span of 6 seconds.

    SolidColorBrush brush = new SolidColorBrush(Colors.Yellow);
    p.Background = brush;
    ColorAnimation ca1 = new ColorAnimation()
    {
            From = Colors.Yellow,
            To = Colors.White,
            Duration = new Duration(TimeSpan.FromSeconds(6.0)),
            RepeatBehavior = new RepeatBehavior(1),
            AutoReverse = false,
    };

    brush.BeginAnimation(SolidColorBrush.ColorProperty, ca1);
</code>```

OwnerDisplayName: Eric Smith

Body:
I'm trying to fade in a new control to my application's "app" area which is programmatically added after the existing controls are removed. My code looks like this:

        void settingsButton_Clicked(object sender, EventArgs e)
    {
        ContentCanvas.Children.Clear();

        // Fade in settings panel
        NameScope.SetNameScope(this, new NameScope());

        SettingsPane s = new SettingsPane();
        s.Name = "settingsPane";

        this.RegisterName(s.Name, s);
        this.Resources.Add(s.Name, s);

        Storyboard sb = new Storyboard();

        DoubleAnimation settingsFade = new DoubleAnimation();
        settingsFade.From = 0;
        settingsFade.To = 1;
        settingsFade.Duration = new Duration(TimeSpan.FromSeconds(0.33));
        settingsFade.RepeatBehavior = new RepeatBehavior(1);
        Storyboard.SetTargetName(settingsFade, s.Name);
        Storyboard.SetTargetProperty(settingsFade, new PropertyPath(UserControl.OpacityProperty));

        ContentCanvas.Children.Add(s);

        sb.Children.Add(settingsFade);
        sb.Begin();
    }

However, when I run this code, I get the error "No applicable name scope exists to resolve the name 'settingsPane'."

What am I possibly doing wrong? I'm pretty sure I've registered everything properly :(

Body:
I agree, the namescopes are probably the wrong thing to use for this scenario.  Much simpler and easier to use SetTarget rather than SetTargetName.

In case it helps anyone else, here's what I used to highlight a particular cell in a table with a highlight that decays to nothing. It's a little like the StackOverflow highlight when you add a new answer.

    TableCell cell = table.RowGroups[0].Rows[row].Cells[col];

    // The cell contains just one paragraph; it is the first block
    Paragraph p = (Paragraph)cell.Blocks.FirstBlock;

    // Animate the paragraph: fade the background from Yellow to White,
    // once, through a span of 6 seconds.

    SolidColorBrush brush = new SolidColorBrush(Colors.Yellow);
    p.Background = brush;
    ColorAnimation ca1 = new ColorAnimation()
    {
            From = Colors.Yellow,
            To = Colors.White,
            Duration = new Duration(TimeSpan.FromSeconds(6.0)),
            RepeatBehavior = new RepeatBehavior(1),
            AutoReverse = false,
    };

    brush.BeginAnimation(SolidColorBrush.ColorProperty, ca1);

OwnerDisplayName: Cheeso