答:
You need the color and fill to be assigned according to imaging_date

ggplot(dt, aes(x=imaging_date, y=norm_diameter, colour = factor(imaging_date)))+
  geom_point()+
  geom_boxplot(aes(fill = after_scale(alpha(colour, 0.4))))
```
<p><img src="https://i.stack.imgur.com/UWOJ8.png" alt="enter image description here" /></p>
<p>Or, with some aesthetics tweaks:</p>
<pre class="lang-r prettyprint-override"><code>library(ggnewscale)

ggplot(dt, aes(x=imaging_date, y=norm_diameter, colour = factor(imaging_date))) +
  geom_boxplot(aes(fill = factor(imaging_date)), alpha = 0.4) +
  scale_color_manual(values = c("orange", "deepskyblue4"), name = "Date") +
  scale_fill_manual(values = c("orange", "deepskyblue4"), name = "Date") +
  new_scale_colour() +
  geom_point(aes(x = imaging_date, y = norm_diameter, colour = region),
             position = position_jitter(width = 1), size = 2, alpha = 0.6,
             shape = 21, fill = "white") +
  scale_color_manual(values = c("red4", "blue4", "green4")) +
  theme_bw() +
  labs(x = "Date", y = "Diameter")
</code>```

Title: Box plot representing the wrong aesthetics

Body:
I have the following data

structure(list(imaging_date = structure(c(19010, 19010, 19024,
19024, 19010, 19024, 19010, 19024, 19010, 19024, 19010, 19024,
19010, 19010, 19024, 19010, 19010, 19010, 19024, 19024, 19024,
19010, 19010, 19010, 19024, 19024, 19010, 19010, 19010, 19010,
19010, 19010, 19010, 19010, 19024, 19024), class = "Date"), diameter_on_mask = c(960L,
960L, 960L, 960L, 480L, 480L, 480L, 480L, 480L, 480L, 480L, 480L,
480L, 480L, 480L, 960L, 960L, 960L, 960L, 960L, 960L, 960L, 960L,
960L, 960L, 960L, 480L, 480L, 480L, 480L, 480L, 480L, 480L, 480L,
480L, 480L), diameter_measured = c(1020L, 1040L, 1210L, 1120L,
532L, 626L, 541L, 595L, 519L, 602L, 515L, 638L, 519L, 518L, 593L,
1030L, 989L, 999L, 1120L, 1140L, 1220L, 1000L, 1010L, 1010L,
1370L, 1290L, 519L, 511L, 505L, 522L, 502L, 501L, 536L, 532L,
686L, 754L), slideno_cno_region_id = c("3_1_1", "3_1_2", "3_1_1",
"3_1_2", "3_1_3", "3_1_3", "3_1_4", "3_1_4", "3_1_5", "3_1_5",
"3_1_6", "3_1_6", "", "", "", "", "", "", "", "", "", "3_1_7",
"", "", "3_1_7", "", "", "", "", "", "", "", "", "", "", ""),
    region = c("inlet", "inlet", "inlet", "inlet", "inlet", "inlet",
    "inlet", "inlet", "inlet", "inlet", "inlet", "inlet", "inlet",
    "inlet", "inlet", "middle", "middle", "middle", "middle",
    "middle", "middle", "outlet", "outlet", "outlet", "outlet",
    "outlet", "outlet", "outlet", "outlet", "outlet", "outlet",
    "outlet", "outlet", "outlet", "outlet", "outlet"), norm_diameter = c(1.0625,
    1.08333333333333, 1.26041666666667, 1.16666666666667, 1.10833333333333,
    1.30416666666667, 1.12708333333333, 1.23958333333333, 1.08125,
    1.25416666666667, 1.07291666666667, 1.32916666666667, 1.08125,
    1.07916666666667, 1.23541666666667, 1.07291666666667, 1.03020833333333,
    1.040625, 1.16666666666667, 1.1875, 1.27083333333333, 1.04166666666667,
    1.05208333333333, 1.05208333333333, 1.42708333333333, 1.34375,
    1.08125, 1.06458333333333, 1.05208333333333, 1.0875, 1.04583333333333,
    1.04375, 1.11666666666667, 1.10833333333333, 1.42916666666667,
    1.57083333333333)), row.names = c(NA, -36L), class = c("data.table",
"data.frame"), .internal.selfref = <pointer: 0x7fc0c100d2e0>, index = structure(integer(0), "`__imaging_date`" = c(1L,
2L, 5L, 7L, 9L, 11L, 13L, 14L, 16L, 17L, 18L, 22L, 23L, 24L,
27L, 28L, 29L, 30L, 31L, 32L, 33L, 34L, 3L, 4L, 6L, 8L, 10L,
12L, 15L, 19L, 20L, 21L, 25L, 26L, 35L, 36L)))

I want to plot tranparent boxplots under the actual data points. I did

ggplot(dt, aes(x=imaging_date, y=norm_diameter, colour = factor(region)))+
  geom_point()+
  geom_boxplot(aes(fill = after_scale(alpha(colour, 0.4))))

and got

First of all, I have data belonging to only 2 different days. Second of all, the location of the boxplots belong to neither of those dates. If I group the data inside with imaging_date, these problems disappear, but then they lose their colors.

What is wrong with my data/code?

Body:
You need the color and fill to be assigned according to imaging_date

ggplot(dt, aes(x=imaging_date, y=norm_diameter, colour = factor(imaging_date)))+
  geom_point()+
  geom_boxplot(aes(fill = after_scale(alpha(colour, 0.4))))

Or, with some aesthetics tweaks:

library(ggnewscale)

ggplot(dt, aes(x=imaging_date, y=norm_diameter, colour = factor(imaging_date))) +
  geom_boxplot(aes(fill = factor(imaging_date)), alpha = 0.4) +
  scale_color_manual(values = c("orange", "deepskyblue4"), name = "Date") +
  scale_fill_manual(values = c("orange", "deepskyblue4"), name = "Date") +
  new_scale_colour() +
  geom_point(aes(x = imaging_date, y = norm_diameter, colour = region),
             position = position_jitter(width = 1), size = 2, alpha = 0.6,
             shape = 21, fill = "white") +
  scale_color_manual(values = c("red4", "blue4", "green4")) +
  theme_bw() +
  labs(x = "Date", y = "Diameter")


来源: stackexchange

问:
How do I stop Python from generating a new line each time?
I have created a translator for Morse code in Python and the code works fine except for one problem. When it translates the message into Morse code, it places each character onto a new line. I need the entire translation to stay in one line and I cannot figure out how to make it stay in one line, nor why it is generating a new line each time for each character. Please help! Here is the code:

```<code>print("\n\tMenu Options: \n")
print("\t1. Type a phrase and have it translated into Morse Code. \n\t2. Exit program \n")

# Define the main function.

def main():
    charactersList = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0',
                      '1','2','3','4','5','6','7','8','9','.',',','?','!',' ']

    morse = ['.- ','-... ','-.-. ','-.. ','. ','..-. ','--. ','.... ','.. ','.--- ','-.- ','.-.. ','-- ','-. ','--- ','.--. ','--.- ',
             '.-. ','... ','- ','..- ','...- ','.-- ','-..- ','-.-- ','--.. ','----- ','.---- ','..--- ','...-- ','....- ','..... ',
             '-.... ','--... ','---.. ','----. ','.-.-.- ','--..-- ','..--.. ','-.-.-- ','/ ']

    print("\nPlease select a menu option by typing 1 or 2.")
    choice = int(input("\nMenu Choice: "))

    # Start the while loop within the main function.

    while choice != 2:

        if choice == 1:

            print("\nPlease type the phrase you would like translated into Morse Code.")
            translatee=input()
            translatee=translatee.lower()

            for x in translatee:

                if x in charactersList:
                    print("Translation: ",morse[charactersList.index(x)])

        else:
            print("Error: Please select a valid menu option.")

        # See what the users' next choices are.

        choice = int(input("\nMenu Choice: "))

    print("\n\tExited.")

# Call the main function.

main()

input(exit)

</code>```

Here is an example of the output:
screenshot of output

答:
You could accomplish this by keeping track of whether or not this is the first iteration of the for loop using a variable such as firstTime, the first time you enter the for loop you will need to check if firstTime is true and then set it to false and print out the morse code with Translation: at the start, this way nn the next iteration of the for loop the print statement will not print out Translation: at the start. You can stop the print function from automatically ending the line by adding end="" at the end of the print statement. The firstTime variable should be inside of the if statement in the while loop so that it is reset to true every time the user wants to translate morse code.

Here is the new code:

```<code>print("\n\tMenu Options: \n")
print("\t1. Type a phrase and have it translated into Morse Code. \n\t2. Exit program \n")

# Define the main function.

def main():
    charactersList = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0',
                      '1','2','3','4','5','6','7','8','9','.',',','?','!',' ']

    morse = ['.- ','-... ','-.-. ','-.. ','. ','..-. ','--. ','.... ','.. ','.--- ','-.- ','.-.. ','-- ','-. ','--- ','.--. ','--.- ',
             '.-. ','... ','- ','..- ','...- ','.-- ','-..- ','-.-- ','--.. ','----- ','.---- ','..--- ','...-- ','....- ','..... ',
             '-.... ','--... ','---.. ','----. ','.-.-.- ','--..-- ','..--.. ','-.-.-- ','/ ']

    print("\nPlease select a menu option by typing 1 or 2.")
    choice = int(input("\nMenu Choice: "))

    # Start the while loop within the main function.

    while choice != 2:

        if choice == 1:
            firstTime = True

            print("\nPlease type the phrase you would like translated into Morse Code.")
            translatee=input()
            translatee=translatee.lower()

            for x in translatee:

                if x in charactersList:
                    if firstTime:
                        firstTime = False
                        print("Translation: ",morse[charactersList.index(x)], end="")
                    else:
                        print(morse[charactersList.index(x)], end="")

        else:
            print("Error: Please select a valid menu option.")

        # See what the users' next choices are.

        choice = int(input("\nMenu Choice: "))

    print("\n\tExited.")

# Call the main function.

main()

input(exit)

</code>```

This is the output when I ran it and told it to translate it works!

```<code>
    Menu Options:

    1. Type a phrase and have it translated into Morse Code.
    2. Exit program

Please select a menu option by typing 1 or 2.

Menu Choice: 1

Please type the phrase you would like translated into Morse Code.
it works!
Translation:  .. - / .-- --- .-. -.- ... -.-.--
Menu Choice:

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have created a translator for Morse code in Python and the code works fine except for one problem. When it translates the message into Morse code, it places each character onto a new line. I need the entire translation to stay in one line and I cannot figure out how to make it stay in one line, nor why it is generating a new line each time for each character. Please help! Here is the code:

print("\n\tMenu Options: \n")
print("\t1. Type a phrase and have it translated into Morse Code. \n\t2. Exit program \n")

# Define the main function.

def main():
    charactersList = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0',
                      '1','2','3','4','5','6','7','8','9','.',',','?','!',' ']

    morse = ['.- ','-... ','-.-. ','-.. ','. ','..-. ','--. ','.... ','.. ','.--- ','-.- ','.-.. ','-- ','-. ','--- ','.--. ','--.- ',
             '.-. ','... ','- ','..- ','...- ','.-- ','-..- ','-.-- ','--.. ','----- ','.---- ','..--- ','...-- ','....- ','..... ',
             '-.... ','--... ','---.. ','----. ','.-.-.- ','--..-- ','..--.. ','-.-.-- ','/ ']

    print("\nPlease select a menu option by typing 1 or 2.")
    choice = int(input("\nMenu Choice: "))

    # Start the while loop within the main function.

    while choice != 2:

        if choice == 1:

            print("\nPlease type the phrase you would like translated into Morse Code.")
            translatee=input()
            translatee=translatee.lower()

            for x in translatee:

                if x in charactersList:
                    print("Translation: ",morse[charactersList.index(x)])

        else:
            print("Error: Please select a valid menu option.")

        # See what the users' next choices are.

        choice = int(input("\nMenu Choice: "))

    print("\n\tExited.")

# Call the main function.

main()

input(exit)

Here is an example of the output:
screenshot of output

Body:
You could accomplish this by keeping track of whether or not this is the first iteration of the for loop using a variable such as firstTime, the first time you enter the for loop you will need to check if firstTime is true and then set it to false and print out the morse code with Translation: at the start, this way nn the next iteration of the for loop the print statement will not print out Translation: at the start. You can stop the print function from automatically ending the line by adding end="" at the end of the print statement. The firstTime variable should be inside of the if statement in the while loop so that it is reset to true every time the user wants to translate morse code.

Here is the new code:

print("\n\tMenu Options: \n")
print("\t1. Type a phrase and have it translated into Morse Code. \n\t2. Exit program \n")

# Define the main function.

def main():
    charactersList = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0',
                      '1','2','3','4','5','6','7','8','9','.',',','?','!',' ']

    morse = ['.- ','-... ','-.-. ','-.. ','. ','..-. ','--. ','.... ','.. ','.--- ','-.- ','.-.. ','-- ','-. ','--- ','.--. ','--.- ',
             '.-. ','... ','- ','..- ','...- ','.-- ','-..- ','-.-- ','--.. ','----- ','.---- ','..--- ','...-- ','....- ','..... ',
             '-.... ','--... ','---.. ','----. ','.-.-.- ','--..-- ','..--.. ','-.-.-- ','/ ']

    print("\nPlease select a menu option by typing 1 or 2.")
    choice = int(input("\nMenu Choice: "))

    # Start the while loop within the main function.

    while choice != 2:

        if choice == 1:
            firstTime = True

            print("\nPlease type the phrase you would like translated into Morse Code.")
            translatee=input()
            translatee=translatee.lower()

            for x in translatee:

                if x in charactersList:
                    if firstTime:
                        firstTime = False
                        print("Translation: ",morse[charactersList.index(x)], end="")
                    else:
                        print(morse[charactersList.index(x)], end="")

        else:
            print("Error: Please select a valid menu option.")

        # See what the users' next choices are.

        choice = int(input("\nMenu Choice: "))

    print("\n\tExited.")

# Call the main function.

main()

input(exit)

This is the output when I ran it and told it to translate it works!

    Menu Options:

    1. Type a phrase and have it translated into Morse Code.
    2. Exit program

Please select a menu option by typing 1 or 2.

Menu Choice: 1

Please type the phrase you would like translated into Morse Code.
it works!
Translation:  .. - / .-- --- .-. -.- ... -.-.--
Menu Choice:


问:
Need guidance in using LISTAGG with Regular Expression
```<code>SELECT
         ID_Col,
         lower(LISTAGG(distinct TEXT_COL,',')WITHIN GROUP(ORDER BY TEXT_COL))
         AS TEXT_COL_TXT
         FROM
         (SELECT
          CREATE_DT,
          ID_Col,
          TEXT_COL,
          TRY_CAST(Q_NO as INTEGER) as Q_NO
          FROM db_name.schema_name.tbl_name
          WHERE Flg = '0'
          AND date_of_cr = '2022-02-05'
          AND P_CODE NOT IN ('1','2','3','4')
          AND ID_Col IN('12345','23456')
          ORDER BY Q_NO)
          GROUP BY 1;
</code>```

When I run the above query, I'm getting results like this:

```<code>ID_COL                                        TEXT_COL

12345                                 ::abcd::0,aforapple
23456                                 ::abcd::0,n:sometext:::empty::
</code>```

I want this value to be removed in the result --> ::abcd::0,

The result should look like below:

```<code>ID_COL                                   TEXT_COL

12345                                 aforapple
23456                                 n:sometext:::empty::
</code>```

Can anyone guide me how to bring such a result?

When I use the below logic, I could see comma in the results now:

LISTAGG(distinct iff(TEXT_COL = '::abcd::0', '', TEXT_COL),',')

Result I could see is:

```<code>ID_COL                                   TEXT_COL

12345                                 ,aforapple
23456                                 ,n:sometext:::empty::
</code>```

I should not display comma in the results

答:
It would nice if you started accepting answershttps://stackoverflow.com/help/accepted-answer

It would also be nice if you posted minimal required SQL.

So you posted SQL

```<code>SELECT
    ID_Col,
    lower(LISTAGG(distinct TEXT_COL,',') WITHIN GROUP (ORDER BY TEXT_COL)) AS TEXT_COL_TXT
FROM
(
    SELECT
        CREATE_DT,
        ID_Col,
        TEXT_COL,
        TRY_CAST(Q_NO as INTEGER) as Q_NO
    FROM db_name.schema_name.tbl_name
    WHERE Flg = '0'
        AND date_of_cr = '2022-02-05'
        AND P_CODE NOT IN ('1','2','3','4')
        AND ID_Col IN('12345','23456')
    ORDER BY Q_NO
)
GROUP BY 1;
</code>```

So because your filters on db_name.schema_name.tbl_name have zero impact on the LISTAGG question, those can be dropped. The ORDER BY should be removed, SQL-Server for example will fail this SQL, because it doesn't make a lot of sense to order a sub-select. Thus it can become:

```<code>SELECT
    ID_Col,
    lower(LISTAGG(distinct TEXT_COL,',') WITHIN GROUP (ORDER BY TEXT_COL)) AS TEXT_COL_TXT
FROM
(
    SELECT
        ID_Col,
        TEXT_COL,
    FROM db_name.schema_name.tbl_name
)
GROUP BY 1;
</code>```

But actually that can become:

```<code>SELECT
    ID_Col,
    lower(LISTAGG(distinct TEXT_COL,',') WITHIN GROUP (ORDER BY TEXT_COL)) AS TEXT_COL_TXT
FROM db_name.schema_name.tbl_name
GROUP BY 1;
</code>```

Now if you want to be friend you can provide some working data in a table

ID_COL
TEXT_COL

12345
::abcd::0

12345
aforapple

23456
::abcd::0

23456
n:sometext:::empty::

Of you could provide the data in the small example query that you provide:

```<code>SELECT
    column1,
    lower(LISTAGG(distinct column2,',') WITHIN GROUP (ORDER BY column2)) AS TEXT_COL_TXT
FROM VALUES
    (12345, '::abcd::0'),
    (12345, 'aforapple'),
    (23456, '::abcd::0'),
    (23456, 'n:sometext:::empty::')
GROUP BY 1;
</code>```

There is a huge benefit of pulling your SQL down it to the smallest reproducible example. Sometimes as you remove the unneeded bits, you can see the bigger picture and notice the mistake. Sometimes as you pull things out you undo a part that you didn't fully understand, and thus you have smaller code that works and small + just a little more that does not work, and that is enough tell you which commands needs to be reread in the help to understand the interactions.

Body:
SELECT
         ID_Col,
         lower(LISTAGG(distinct TEXT_COL,',')WITHIN GROUP(ORDER BY TEXT_COL))
         AS TEXT_COL_TXT
         FROM
         (SELECT
          CREATE_DT,
          ID_Col,
          TEXT_COL,
          TRY_CAST(Q_NO as INTEGER) as Q_NO
          FROM db_name.schema_name.tbl_name
          WHERE Flg = '0'
          AND date_of_cr = '2022-02-05'
          AND P_CODE NOT IN ('1','2','3','4')
          AND ID_Col IN('12345','23456')
          ORDER BY Q_NO)
          GROUP BY 1;

When I run the above query, I'm getting results like this:

ID_COL                                        TEXT_COL

12345                                 ::abcd::0,aforapple
23456                                 ::abcd::0,n:sometext:::empty::

I want this value to be removed in the result --> ::abcd::0,

The result should look like below:

ID_COL                                   TEXT_COL

12345                                 aforapple
23456                                 n:sometext:::empty::

Can anyone guide me how to bring such a result?

When I use the below logic, I could see comma in the results now:

LISTAGG(distinct iff(TEXT_COL = '::abcd::0', '', TEXT_COL),',')

Result I could see is:

ID_COL                                   TEXT_COL

12345                                 ,aforapple
23456                                 ,n:sometext:::empty::

I should not display comma in the results

Body:
It would nice if you started accepting answershttps://stackoverflow.com/help/accepted-answer

It would also be nice if you posted minimal required SQL.

So you posted SQL

SELECT
    ID_Col,
    lower(LISTAGG(distinct TEXT_COL,',') WITHIN GROUP (ORDER BY TEXT_COL)) AS TEXT_COL_TXT
FROM
(
    SELECT
        CREATE_DT,
        ID_Col,
        TEXT_COL,
        TRY_CAST(Q_NO as INTEGER) as Q_NO
    FROM db_name.schema_name.tbl_name
    WHERE Flg = '0'
        AND date_of_cr = '2022-02-05'
        AND P_CODE NOT IN ('1','2','3','4')
        AND ID_Col IN('12345','23456')
    ORDER BY Q_NO
)
GROUP BY 1;

So because your filters on db_name.schema_name.tbl_name have zero impact on the LISTAGG question, those can be dropped. The ORDER BY should be removed, SQL-Server for example will fail this SQL, because it doesn't make a lot of sense to order a sub-select. Thus it can become:

SELECT
    ID_Col,
    lower(LISTAGG(distinct TEXT_COL,',') WITHIN GROUP (ORDER BY TEXT_COL)) AS TEXT_COL_TXT
FROM
(
    SELECT
        ID_Col,
        TEXT_COL,
    FROM db_name.schema_name.tbl_name
)
GROUP BY 1;

But actually that can become:

SELECT
    ID_Col,
    lower(LISTAGG(distinct TEXT_COL,',') WITHIN GROUP (ORDER BY TEXT_COL)) AS TEXT_COL_TXT
FROM db_name.schema_name.tbl_name
GROUP BY 1;

Now if you want to be friend you can provide some working data in a table

ID_COL
TEXT_COL

12345
::abcd::0

12345
aforapple

23456
::abcd::0

23456
n:sometext:::empty::

Of you could provide the data in the small example query that you provide:

SELECT
    column1,
    lower(LISTAGG(distinct column2,',') WITHIN GROUP (ORDER BY column2)) AS TEXT_COL_TXT
FROM VALUES
    (12345, '::abcd::0'),
    (12345, 'aforapple'),
    (23456, '::abcd::0'),
    (23456, 'n:sometext:::empty::')
GROUP BY 1;

There is a huge benefit of pulling your SQL down it to the smallest reproducible example. Sometimes as you remove the unneeded bits, you can see the bigger picture and notice the mistake. Sometimes as you pull things out you undo a part that you didn't fully understand, and thus you have smaller code that works and small + just a little more that does not work, and that is enough tell you which commands needs to be reread in the help to understand the interactions.


问:
Power Q: how to add conditional col and split based on length if another col contains text of same col
In power Q: creating a custom col based on condition:
If col A contains text of col b then split col A starting at the position of the length of ColumB

example: col A is MyMothersBasement123 and col B is MyMothersBase
col c would =  ment123

Somthing along the lines of :
 if Text.Contains([ColumnA], [ColumnB]) then SplitTextByPositions({length of ColumB}) else [ColumnA]

答:
Try

add column .. custom column ...

```<code>= try Text.Split([Column1],[Column2]){1} otherwise [Column1]
</code>```

or

```<code>= try Text.Replace([Column1],[Column2],"") otherwise [Column1]
</code>```

Body:
Try

add column .. custom column ...

= try Text.Split([Column1],[Column2]){1} otherwise [Column1]

or

= try Text.Replace([Column1],[Column2],"") otherwise [Column1]


问:
No Internet Access In Docker Container When Connected to Cisco AnyConnect VPN
I am connected to a corporate VPN and need to be able to run docker containers while the VPN is connected due to the fact that the container needs to be able to access corporate endpoints. However, when I am connected with AnyConnect VPN, docker has no internet access at all. Neither to our corporate endpoints or the internet.

I am running CentOS7 as my host operating system.

A simple way to reproduce this issue is to install a minimal linux distro, install AnyConnect VPN, connect to vpn and try to run the following docker container:

```<code>docker run -i -t ubuntu:14.04 /bin/bash
</code>```

Once inside the container I try to ping google dns

```<code>[###]$ ping 8.8.8.8
</code>```

There will be no response. If I disconnect from AnyConnect VPN and retry the above, I get a ping response.

How can I fix this issue?

答:
Ping outside and internet access are different. You could access internet but could not ping as limit by your corporation network. I suggest running busybox

```<code>docker run -it --rm busybox
</code>```

and check the dns setup inside

```<code>cat /etc/resolv.conf
</code>```

From there you may see list of nameserver ip addresses. Now you could try to ping those to make sure they are reachable from inside. If not, you could try

```<code>traceroute 1.2.3.4
</code>```

to see how far you could go from inside container, the first 2 lines should be ip of docker and the host machine, and then the ip of your corporation network

```<code>1  172.17.0.1 (172.17.0.1)  0.016 ms  0.011 ms  0.009 ms
2  10.1.249.4 (10.1.249.4)  38.487 ms  35.697 ms  35.558 ms
</code>```

Usually it's problem of the nameserver generated inside /etc/resolv.conf
file. If it's the case, then you need to check /etc/resolv.conf
in the host machine and update the docker setup to generate the nameservers correctly inside container.

Body:
I am connected to a corporate VPN and need to be able to run docker containers while the VPN is connected due to the fact that the container needs to be able to access corporate endpoints. However, when I am connected with AnyConnect VPN, docker has no internet access at all. Neither to our corporate endpoints or the internet.

I am running CentOS7 as my host operating system.

A simple way to reproduce this issue is to install a minimal linux distro, install AnyConnect VPN, connect to vpn and try to run the following docker container:

docker run -i -t ubuntu:14.04 /bin/bash

Once inside the container I try to ping google dns

[###]$ ping 8.8.8.8

There will be no response. If I disconnect from AnyConnect VPN and retry the above, I get a ping response.

How can I fix this issue?

Body:
Ping outside and internet access are different. You could access internet but could not ping as limit by your corporation network. I suggest running busybox

docker run -it --rm busybox

and check the dns setup inside

cat /etc/resolv.conf

From there you may see list of nameserver ip addresses. Now you could try to ping those to make sure they are reachable from inside. If not, you could try

traceroute 1.2.3.4

to see how far you could go from inside container, the first 2 lines should be ip of docker and the host machine, and then the ip of your corporation network

1  172.17.0.1 (172.17.0.1)  0.016 ms  0.011 ms  0.009 ms
2  10.1.249.4 (10.1.249.4)  38.487 ms  35.697 ms  35.558 ms

Usually it's problem of the nameserver generated inside /etc/resolv.conf
file. If it's the case, then you need to check /etc/resolv.conf
in the host machine and update the docker setup to generate the nameservers correctly inside container.


问:
Do I have to check LSRequiresIPhoneOS in order to find out if camera is available?
In my Xcode project there is Info.plist file in resources. It has an attribute like this:

```<code>LSRequiresIPhoneOS
</code>```

So my question is: do I have to check that? What I want is that my app finds out itself weather there is a camera or not. If not, the feature is disabled, and if yes: Cool! It must work on both iPhone and iPod Touch!

I guess that if I disable this in Info.plist, I can still use iPhone features, and Apple will not refuse my code because of that, right?

答:
You should leave LSRequiresIPhoneOS checked (which is the default value). This does not prevent the app from running on the iPod Touch. It may seem confusing, but in this case "IPhoneOS" is referring to the OS that runs on both the iPhone and the iPod Touch (assuming the user has installed iPhone OS on the Touch so that it can run 3rd-party apps).

Regarding camera usage, you can use something like the following to specifically see if the camera is available:

```<code>BOOL isCameraAvailable = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
</code>```

This kind of approach--checking for specific functionality--is usually better than using the iPhone OS version or hardware model.

OwnerDisplayName: Unknown Individual

ContentLicense: CC BY-SA 3.0

Body:
In my Xcode project there is Info.plist file in resources. It has an attribute like this:

LSRequiresIPhoneOS

So my question is: do I have to check that? What I want is that my app finds out itself weather there is a camera or not. If not, the feature is disabled, and if yes: Cool! It must work on both iPhone and iPod Touch!

I guess that if I disable this in Info.plist, I can still use iPhone features, and Apple will not refuse my code because of that, right?

Body:
You should leave LSRequiresIPhoneOS checked (which is the default value). This does not prevent the app from running on the iPod Touch. It may seem confusing, but in this case "IPhoneOS" is referring to the OS that runs on both the iPhone and the iPod Touch (assuming the user has installed iPhone OS on the Touch so that it can run 3rd-party apps).

Regarding camera usage, you can use something like the following to specifically see if the camera is available:

BOOL isCameraAvailable = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];

This kind of approach--checking for specific functionality--is usually better than using the iPhone OS version or hardware model.

OwnerDisplayName: Clint

ContentLicense: CC BY-SA 2.5


问:
Firebase HTTP Function triggered twice when POST request sent with headers
I deployed a firebase HTTP cloud function and am experiencing this (unexpected) behavior:

when I call the function (using POST) from a browser environment with fetch(), the function gets triggered twice, one time without any data sent in the body, and another time as I would expect it. In the frontend (chrome network tab) I can only see 1 request, the successfull one.

this does only happen with POST requests

this does only happen when the request is sending headers

Is this normal behavior that I dont understand or a potential bug?

my minimal cloud function

exports.run = functions.https.onRequest(async (req, res) => {
  // ALLOW CORS FOR POST REQUEST:
  // => https://stackoverflow.com/a/38259193
  res.set('Access-Control-Allow-Origin', '*');
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");

  return res.status(200).send({
    status: "ok",
    body: req.body,
    query: req.query,
  }).end();
});
```
<h2>calling from frontend</h2>
<pre class="lang-js prettyprint-override"><code>// example data (not a real one)
const url = "https://us-central1-myproject.cloudfunctions.net/test";
const postData = { x: 1, y: 2 };

// GET request => ✅ works as expected
fetch(url);

// POST request without headers => ✅ works as expected
fetch(url, {
  method: 'POST',
  body: JSON.stringify(postData),
});

// POST request with headers => ❌ 2 requests get triggered
fetch(url,  {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(postData),
});
</code>```

答:
This behavior is happening because of the CORS preflight request:

A CORS preflight request is a CORS request that checks to see if the CORS protocol is understood and a server is aware using specific methods and headers.
...
A preflight request is automatically issued by a browser, and in normal cases, front-end developers don't need to craft such requests themselves. It appears when a request is qualified as "to be preflighted" and omitted for simple requests.

As pointed in this other question:

As long as you’re adding a Content-Type': 'application/json' header to the request, the browser is going to automatically on its own do a CORS preflight OPTIONS request before trying the request from your code.

Therefore, this is a normal behavior and is not a problem of Cloud Functions for Firebase.

In order to not have the two requests, you can change the header request as suggested by this answer:

// example data (not a real one)
const url = "https://us-central1-myproject.cloudfunctions.net/test";
const postData = { x: 1, y: 2 };

// POST request with different header  => ✅ only one request is triggered
fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: JSON.stringify(postData),
}).then(data => console.log(data));
```

Body:
I deployed a firebase HTTP cloud function and am experiencing this (unexpected) behavior:

when I call the function (using POST) from a browser environment with fetch(), the function gets triggered twice, one time without any data sent in the body, and another time as I would expect it. In the frontend (chrome network tab) I can only see 1 request, the successfull one.

this does only happen with POST requests

this does only happen when the request is sending headers

Is this normal behavior that I dont understand or a potential bug?

my minimal cloud function

exports.run = functions.https.onRequest(async (req, res) => {
  // ALLOW CORS FOR POST REQUEST:
  // => https://stackoverflow.com/a/38259193
  res.set('Access-Control-Allow-Origin', '*');
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");

  return res.status(200).send({
    status: "ok",
    body: req.body,
    query: req.query,
  }).end();
});

calling from frontend

// example data (not a real one)
const url = "https://us-central1-myproject.cloudfunctions.net/test";
const postData = { x: 1, y: 2 };

// GET request => ✅ works as expected
fetch(url);

// POST request without headers => ✅ works as expected
fetch(url, {
  method: 'POST',
  body: JSON.stringify(postData),
});

// POST request with headers => ❌ 2 requests get triggered
fetch(url,  {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(postData),
});


问:
Null/Empty DateTimePicker when cellclicked to a null date in datagridview
I have a Datagridview which is DGV and there's a column name Drop Date(it's for students who dropped the subject) and I have some null cells in there. As the title says, I want the DateTimePicker to be null when clicked on a null cell.

Here's my code.

```<code>   Private Sub DGV_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DGV.CellClick
        If DGV.CurrentRow.Cells(6).Value Is Nothing Then
            DTP.Format = DateTimePickerFormat.Custom
            DTP.CustomFormat = " "
        Else
            DTP.Format = DateTimePickerFormat.Short
            DTP.Text = DGV.CurrentRow.Cells(6).Value.ToString
        End If
   End Sub
</code>```

Here's the problem.

When I 1st clicked on a cell that has a value and then 2nd clicked on the cell without value, it still show the value of the 1st clicked.

答:
Already fixed it.</p>
```<code>       If String.IsNullOrEmpty(DGV.CurrentRow.Cells(6).Value.ToString) = True Then
            DTP.Format = DateTimePickerFormat.Custom
            DTP.CustomFormat = " "
        Else
            DTP.Format = DateTimePickerFormat.Short
            DTP.Text = DGV.CurrentRow.Cells(6).Value.ToString
        End If
</code>```

Body:
I have a Datagridview which is DGV and there's a column name Drop Date(it's for students who dropped the subject) and I have some null cells in there. As the title says, I want the DateTimePicker to be null when clicked on a null cell.

Here's my code.

   Private Sub DGV_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DGV.CellClick
        If DGV.CurrentRow.Cells(6).Value Is Nothing Then
            DTP.Format = DateTimePickerFormat.Custom
            DTP.CustomFormat = " "
        Else
            DTP.Format = DateTimePickerFormat.Short
            DTP.Text = DGV.CurrentRow.Cells(6).Value.ToString
        End If
   End Sub

Here's the problem.

When I 1st clicked on a cell that has a value and then 2nd clicked on the cell without value, it still show the value of the 1st clicked.

Body:
Already fixed it.

       If String.IsNullOrEmpty(DGV.CurrentRow.Cells(6).Value.ToString) = True Then
            DTP.Format = DateTimePickerFormat.Custom
            DTP.CustomFormat = " "
        Else
            DTP.Format = DateTimePickerFormat.Short
            DTP.Text = DGV.CurrentRow.Cells(6).Value.ToString
        End If


问:
Unable to specify Resource Identifier for AWS::ApiGateway::Resource in Cloudformation Template
I am using SAM to deploy a simple Hello world application. One with one API Endpoint, which will trigger a lambda function that returns the text hello world.
I have defined the following resources:

IAM Role so that APIGateway can invoke lambda functions.

AWS::ApiGateway::RestApi

AWS::ApiGateway::Resource

AWS::ApiGateway::Method

AWS::Serverless::Function

Admittedly, I do not know the difference in functionality between 2. and 3. yet.

During sam deploy I see the following error.

```<code>ROLLBACK_IN_PROGRESS                              AWS::CloudFormation::Stack                        go-hello-world                                    The following resource(s) failed to create:
                                                                                [HelloWorldAPIResource,
                                                                                HelloWorldFunctionRole]. Rollback requested by
                                                                                user.
CREATE_FAILED                                     AWS::IAM::Role                                    HelloWorldFunctionRole                            Resource creation cancelled
CREATE_FAILED                                     AWS::ApiGateway::Resource                         HelloWorldAPIResource                             Resource handler returned message: "Invalid
                                                                                Resource identifier specified (Service:
                                                                                ApiGateway, Status Code: 404, Request ID:
                                                                                62f34d79-86ab-47fd-85b1-5fbb55071520, Extended
                                                                                Request ID: null)" (RequestToken:
                                                                                9633d7db-7b6d-881b-f54e-ca0114862fd8,
                                                                                HandlerErrorCode: NotFound)
</code>```

Which means that the AWS::ApiGateway::Resource is not getting a valid reference to AWS::ApiGateway::RestApi.

Here is the relevant part from my template.yml

```<code>  HelloWorldAPI:
    Type: AWS::ApiGateway::RestApi
    Properties:
      Name: HelloWorldApi

  HelloWorldAPIResource:
    Type: AWS::ApiGateway::Resource
    Properties:
      RestApiId: !Ref HelloWorldAPI
      ParentId: "/"
      PathPart: hello
</code>```

I am new to both CloudFormation and AWS in general, any help is appreciated.

答:
It should be:</p>
```<code> ParentId: !GetAtt HelloWorldAPI.RootResourceId
</code>```

Body:
I am using SAM to deploy a simple Hello world application. One with one API Endpoint, which will trigger a lambda function that returns the text hello world.
I have defined the following resources:

IAM Role so that APIGateway can invoke lambda functions.

AWS::ApiGateway::RestApi

AWS::ApiGateway::Resource

AWS::ApiGateway::Method

AWS::Serverless::Function

Admittedly, I do not know the difference in functionality between 2. and 3. yet.

During sam deploy I see the following error.

ROLLBACK_IN_PROGRESS                              AWS::CloudFormation::Stack                        go-hello-world                                    The following resource(s) failed to create:
                                                                                [HelloWorldAPIResource,
                                                                                HelloWorldFunctionRole]. Rollback requested by
                                                                                user.
CREATE_FAILED                                     AWS::IAM::Role                                    HelloWorldFunctionRole                            Resource creation cancelled
CREATE_FAILED                                     AWS::ApiGateway::Resource                         HelloWorldAPIResource                             Resource handler returned message: "Invalid
                                                                                Resource identifier specified (Service:
                                                                                ApiGateway, Status Code: 404, Request ID:
                                                                                62f34d79-86ab-47fd-85b1-5fbb55071520, Extended
                                                                                Request ID: null)" (RequestToken:
                                                                                9633d7db-7b6d-881b-f54e-ca0114862fd8,
                                                                                HandlerErrorCode: NotFound)

Which means that the AWS::ApiGateway::Resource is not getting a valid reference to AWS::ApiGateway::RestApi.

Here is the relevant part from my template.yml

  HelloWorldAPI:
    Type: AWS::ApiGateway::RestApi
    Properties:
      Name: HelloWorldApi

  HelloWorldAPIResource:
    Type: AWS::ApiGateway::Resource
    Properties:
      RestApiId: !Ref HelloWorldAPI
      ParentId: "/"
      PathPart: hello

I am new to both CloudFormation and AWS in general, any help is appreciated.

Body:
It should be:

 ParentId: !GetAtt HelloWorldAPI.RootResourceId


问:
How to use an information sent on httpResponse?
I am learning about making requests to an api using my backend and when i make this i receive a response with some informations i want to use but i don't know how to use this.

Let me clarify this for you.

I HAVE THIS CODE TO MAKE THE REQUEST

```<code>try
{
    //Set Basic Auth
    var userPagarme = test_key;
    var password = "";
    var base64String = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{userPagarme}:{password}"));
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", base64String);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var clienteToAdd = new PagarmeCliente()
    {
        Name = registerUser.Name,
        Code = registerUser.Code,
        Document = registerUser.Document,
        Type = registerUser.Type,
        Document_Type = registerUser.Document_Type,
        Birthdate = registerUser.Birthdate,
        Email = registerUser.Email,
        Gender = registerUser.Gender,
        Address = new PagarmeClienteEndereco()
        {
            city = registerUser.City,
            country = registerUser.Country,
            line_1 = registerUser.Line_1,
            line_2 = registerUser.Line_2,
            state = registerUser.State,
            zip_code = registerUser.Zip_Code
        },
        Phones = new PagarmeClienteTelefone()
        {
            mobile_phone = new PagarmeClienteTelefoneMobile()
            {
                area_code = registerUser.Mobile_phone_area_code,
                country_code = registerUser.Mobile_phone_country_code,
                number = registerUser.Mobile_phone_number
            },
        }
    };

    var jsonString = JsonConvert.SerializeObject(clienteToAdd);

    HttpResponseMessage response = await client.PostAsJsonAsync(urlPagarme + "customers", clienteToAdd);

    response.EnsureSuccessStatusCode();

    string responseBody = await response.Content.ReadAsStringAsync();

    this.responseBodyJSON = JsonConvert.DeserializeObject(responseBody); // I have created this prop as an OBJ to receive the obj that was sent. I don't know if it is correct
}
catch (HttpRequestException e)
{
    return BadRequest("\nException Caught - Message :{0} " + e.Message);
}
</code>```

That is what i have in this responseBodyJSON and i want to use this property ID to insert on my database but if i make something like this below it doesn't work:

string idThatIWant = responseBodyJSON.id... or something like that.

答:
```<code>var respBody = JsonConvert.DeserializeObject<PagarmeCliente>(responseBody);
</code>```

respBody.ID should be available if the class PagarmeCliente has the ID field you wanted populated.

Body:
I am learning about making requests to an api using my backend and when i make this i receive a response with some informations i want to use but i don't know how to use this.

Let me clarify this for you.

I HAVE THIS CODE TO MAKE THE REQUEST

try
{
    //Set Basic Auth
    var userPagarme = test_key;
    var password = "";
    var base64String = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{userPagarme}:{password}"));
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", base64String);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var clienteToAdd = new PagarmeCliente()
    {
        Name = registerUser.Name,
        Code = registerUser.Code,
        Document = registerUser.Document,
        Type = registerUser.Type,
        Document_Type = registerUser.Document_Type,
        Birthdate = registerUser.Birthdate,
        Email = registerUser.Email,
        Gender = registerUser.Gender,
        Address = new PagarmeClienteEndereco()
        {
            city = registerUser.City,
            country = registerUser.Country,
            line_1 = registerUser.Line_1,
            line_2 = registerUser.Line_2,
            state = registerUser.State,
            zip_code = registerUser.Zip_Code
        },
        Phones = new PagarmeClienteTelefone()
        {
            mobile_phone = new PagarmeClienteTelefoneMobile()
            {
                area_code = registerUser.Mobile_phone_area_code,
                country_code = registerUser.Mobile_phone_country_code,
                number = registerUser.Mobile_phone_number
            },
        }
    };

    var jsonString = JsonConvert.SerializeObject(clienteToAdd);

    HttpResponseMessage response = await client.PostAsJsonAsync(urlPagarme + "customers", clienteToAdd);

    response.EnsureSuccessStatusCode();

    string responseBody = await response.Content.ReadAsStringAsync();

    this.responseBodyJSON = JsonConvert.DeserializeObject(responseBody); // I have created this prop as an OBJ to receive the obj that was sent. I don't know if it is correct
}
catch (HttpRequestException e)
{
    return BadRequest("\nException Caught - Message :{0} " + e.Message);
}

That is what i have in this responseBodyJSON and i want to use this property ID to insert on my database but if i make something like this below it doesn't work:

string idThatIWant = responseBodyJSON.id... or something like that.

Body:
var respBody = JsonConvert.DeserializeObject<PagarmeCliente>(responseBody);

respBody.ID should be available if the class PagarmeCliente has the ID field you wanted populated.


问:
Alternating lines with Nested Loops
This is the exercise I need to complete:
Using nested loops, write some code that outputs the following:

```<code>##########
**********
##########
**********
##########
</code>```

Following is all the code I have so far. I assume I need to combine these two loop functions to one but I'm struggling with it. I'm early on in my first class and any help with this would be appreciated!

```<code>for a in range (0, 5, 2):
    for b in range(10):
        print("#", end = "")
    print("")
for a in range (1, 5, 2):
    for b in range(10):
        print("*", end = "")
    print("")
</code>```

答:
```<code>def printStripes(row_length, number_of_rows):
    for _ in '_':
        print( "".join(
            [ "\n" if n%(row_length+1)==row_length else
              "#"  if (n//(row_length+1))%2==0 else
              "*"
              for n in range(number_of_rows*(row_length+1))
            ]
        ),end="")

printStripes(row_length=5,number_of_rows=8)
</code>```

But don't tell your teacher that you got if from stackoverflow. (Thanks Kelly, for how to deal with the nested loop constraint.)

Title: Alternating lines with Nested Loops

Body:
This is the exercise I need to complete:
Using nested loops, write some code that outputs the following:

##########
**********
##########
**********
##########

Following is all the code I have so far. I assume I need to combine these two loop functions to one but I'm struggling with it. I'm early on in my first class and any help with this would be appreciated!

for a in range (0, 5, 2):
    for b in range(10):
        print("#", end = "")
    print("")
for a in range (1, 5, 2):
    for b in range(10):
        print("*", end = "")
    print("")

Body:
def printStripes(row_length, number_of_rows):
    for _ in '_':
        print( "".join(
            [ "\n" if n%(row_length+1)==row_length else
              "#"  if (n//(row_length+1))%2==0 else
              "*"
              for n in range(number_of_rows*(row_length+1))
            ]
        ),end="")

printStripes(row_length=5,number_of_rows=8)

But don't tell your teacher that you got if from stackoverflow. (Thanks Kelly, for how to deal with the nested loop constraint.)


问:
route or applogic
trying to get rails routing to "click" and just not getting it

have a project and a task model:

```<code>class Task
  include Mongoid::Document

  field :title,                     :type => String
  has_many :projects
  belongs_to :user
end

class Project

  include Mongoid::Document

  field :title,                     :type => String
  has_and_belongs_to_many           :tasks
  belongs_to                        :user
end
</code>```

I want to "associate" a task with a project
so I have this in the project controller:

```<code>def connect
  @project = Project.find(params[:id])
  @project.tasks_ids.push(params[:task_id])
  @project.save
  redirect_to project
end
</code>```

with this route:

```<code>resources :projects do
    match 'connect/:id' => 'projects#connect', :as => :connect, :via => :put
    resources :tasks
end
</code>```

I cant seem to get this to work in the view:

```<code> = link_to 'Associate Task', project_connect_path(@task)
</code>```

fails with:

No route matches {:controller=>"projects", :action=>"connect"}

答:
```<code>resources :projects do
  member do
   put :connect
  end
  resources :tasks
end
</code>```

Your path should look like this:

= link_to 'Associate Task', project_connect_path(@project, :task_id => @task.id), :method => :put

Title: route or applogic

Body:
trying to get rails routing to "click" and just not getting it

have a project and a task model:

class Task
  include Mongoid::Document

  field :title,                     :type => String
  has_many :projects
  belongs_to :user
end

class Project

  include Mongoid::Document

  field :title,                     :type => String
  has_and_belongs_to_many           :tasks
  belongs_to                        :user
end

I want to "associate" a task with a project
so I have this in the project controller:

def connect
  @project = Project.find(params[:id])
  @project.tasks_ids.push(params[:task_id])
  @project.save
  redirect_to project
end

with this route:

resources :projects do
    match 'connect/:id' => 'projects#connect', :as => :connect, :via => :put
    resources :tasks
end

I cant seem to get this to work in the view:

 = link_to 'Associate Task', project_connect_path(@task)

fails with:

No route matches {:controller=>"projects", :action=>"connect"}

Body:
resources :projects do
  member do
   put :connect
  end
  resources :tasks
end

Your path should look like this:

= link_to 'Associate Task', project_connect_path(@project, :task_id => @task.id), :method => :put


问:
UITableView custom cell images disappear after scrolling.
I am in the process of creating my open grid view.

I created a custom cell that looks like so:

I handle populating it like so:

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *MyIdentifier = @"Cell";

    TableGalleryCustomCell *cell = (TableGalleryCustomCell*)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];

    if( cell == nil) {
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"TableGalleryCustomCell" owner:nil options:nil];
        for (id currentObject in topLevelObjects) {
            if ([currentObject isKindOfClass:[UITableViewCell class]]) {
                cell = (TableGalleryCustomCell*)currentObject;
                break;
            }
        }
    }

    if (countingIndex < [[[self.appDelegate rssParser] rssItems] count]) {
        cell.firstAddress.text = [[[[self.appDelegate rssParser] rssItems] objectAtIndex:countingIndex] Address];
        cell.firstPrice.text = [[[[self.appDelegate rssParser] rssItems] objectAtIndex:countingIndex] Deposit];
        if ([[[[[[self appDelegate] rssParser]rssItems]objectAtIndex:countingIndex] imageURLs] count] != 0 ) {
            [cell.firstImage setImageWithURL:[NSURL URLWithString:[[[[[self.appDelegate rssParser] rssItems] objectAtIndex:countingIndex] imageURLs] objectAtIndex:0.0]]];
            cell.firstImage.tag = countingIndex;
        }
    }

    countingIndex++;
    if (countingIndex < [[[self.appDelegate rssParser] rssItems] count]) {
        cell.secondAddress.text = [[[[self.appDelegate rssParser] rssItems] objectAtIndex:countingIndex] Address];
        cell.secondPrice.text = [[[[self.appDelegate rssParser] rssItems] objectAtIndex:countingIndex] Deposit];
        if ([[[[[[self appDelegate] rssParser]rssItems]objectAtIndex:countingIndex] imageURLs] count] != 0 ) {
            [cell.secondImage setImageWithURL:[NSURL URLWithString:[[[[[self.appDelegate rssParser] rssItems] objectAtIndex:countingIndex] imageURLs] objectAtIndex:0.0]]];
            cell.secondImage.tag = countingIndex;
        }
    }

    countingIndex++;
    if (countingIndex < [[[self.appDelegate rssParser] rssItems] count]) {
        cell.thirdAddress.text = [[[[self.appDelegate rssParser] rssItems] objectAtIndex:countingIndex] Address];
        cell.thirdPrice.text = [[[[self.appDelegate rssParser] rssItems] objectAtIndex:countingIndex] Deposit];
        if ([[[[[[self appDelegate] rssParser]rssItems]objectAtIndex:countingIndex] imageURLs] count] != 0 ) {
            [cell.thirdImage setImageWithURL:[NSURL URLWithString:[[[[[self.appDelegate rssParser] rssItems] objectAtIndex:countingIndex] imageURLs] objectAtIndex:0.0]]];
            cell.thirdImage.tag = countingIndex;
        }
    }

    countingIndex++;
    if (countingIndex < [[[self.appDelegate rssParser] rssItems] count]) {
        cell.fourthAddress.text = [[[[self.appDelegate rssParser] rssItems] objectAtIndex:countingIndex] Address];
        cell.fourthPrice.text = [[[[self.appDelegate rssParser] rssItems] objectAtIndex:countingIndex] Deposit];
        if ([[[[[[self appDelegate] rssParser]rssItems]objectAtIndex:countingIndex] imageURLs] count] != 0 ) {
            [cell.fourthImage setImageWithURL:[NSURL URLWithString:[[[[[self.appDelegate rssParser] rssItems] objectAtIndex:countingIndex] imageURLs] objectAtIndex:0.0]]];
            cell.fourthImage.tag = countingIndex;
        }
    }

    countingIndex++;

    return cell;
}
</code>```

It is a bit messy but it works.....until I scroll. After the image is loaded then scrolled off the screen the image disappears.

I believe that it maybe due to the imageViews of the cells being lost?

I tried the exact same implementation but with only 1 imageView in each cell and all works great.

Any point in the right direction would be very much appreciated.

I appreciate any help and thank you for your time.

答:
I had the similar problem, but solved by putting the actual image loading part inside "willDisplayCell" not in "cellForRow".</p>
```<code>- (void)tableView:(UITableView *)tableView willDisplayCell:(CalendarTableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {

    PHImageRequestOptions *options = [[PHImageRequestOptions alloc]init];
    options.networkAccessAllowed = YES; //NO; //ver3.9.4
    options.synchronous  = NO;
    options.deliveryMode = PHImageRequestOptionsDeliveryModeOpportunistic;
    options.resizeMode   = PHImageRequestOptionsResizeModeNone;
    options.version      = PHImageRequestOptionsVersionCurrent;
    options.progressHandler = ^(double progress, NSError *error, BOOL *stop, NSDictionary *dictionary) {
        dispatch_async(dispatch_get_main_queue(), ^{
            // self.progressView.progress = progress;
            // self.progressView.hidden = (progress <= 0.0 || progress >= 1.0);
        });
    };
    cell.tag = indexPath.row; //ver3.8.3

    cell.imageRequestID = [self.imageManager requestImageForAsset:asset
                                                               targetSize:targetSize
                                                              contentMode:PHImageContentModeAspectFit
                                                                  options:options
                                                            resultHandler:^(UIImage *result, NSDictionary *info) {
                                                                if (cell != nil) {
                                                                    if (cell.tag == indexPath.row) {
                                                                        dispatch_async(dispatch_get_main_queue(), ^{
                                                                            cell.photoImageView.image = result;
                                                                            cell.timesUpdated++;
                                                                            NSLog(@"cell.photoImageView.image SUCCESS!!");
                                                                            NSLog(@"indexPath.row = %ld",(long)indexPath.row);
                                                                        });
                                                                    }
                                                                }
                                                            }];

}
</code>```

Body:
I am in the process of creating my open grid view.

I created a custom cell that looks like so:

I handle populating it like so:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *MyIdentifier = @"Cell";

    TableGalleryCustomCell *cell = (TableGalleryCustomCell*)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];

    if( cell == nil) {
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"TableGalleryCustomCell" owner:nil options:nil];
        for (id currentObject in topLevelObjects) {
            if ([currentObject isKindOfClass:[UITableViewCell class]]) {
                cell = (TableGalleryCustomCell*)currentObject;
                break;
            }
        }
    }

    if (countingIndex < [[[self.appDelegate rssParser] rssItems] count]) {
        cell.firstAddress.text = [[[[self.appDelegate rssParser] rssItems] objectAtIndex:countingIndex] Address];
        cell.firstPrice.text = [[[[self.appDelegate rssParser] rssItems] objectAtIndex:countingIndex] Deposit];
        if ([[[[[[self appDelegate] rssParser]rssItems]objectAtIndex:countingIndex] imageURLs] count] != 0 ) {
            [cell.firstImage setImageWithURL:[NSURL URLWithString:[[[[[self.appDelegate rssParser] rssItems] objectAtIndex:countingIndex] imageURLs] objectAtIndex:0.0]]];
            cell.firstImage.tag = countingIndex;
        }
    }

    countingIndex++;
    if (countingIndex < [[[self.appDelegate rssParser] rssItems] count]) {
        cell.secondAddress.text = [[[[self.appDelegate rssParser] rssItems] objectAtIndex:countingIndex] Address];
        cell.secondPrice.text = [[[[self.appDelegate rssParser] rssItems] objectAtIndex:countingIndex] Deposit];
        if ([[[[[[self appDelegate] rssParser]rssItems]objectAtIndex:countingIndex] imageURLs] count] != 0 ) {
            [cell.secondImage setImageWithURL:[NSURL URLWithString:[[[[[self.appDelegate rssParser] rssItems] objectAtIndex:countingIndex] imageURLs] objectAtIndex:0.0]]];
            cell.secondImage.tag = countingIndex;
        }
    }

    countingIndex++;
    if (countingIndex < [[[self.appDelegate rssParser] rssItems] count]) {
        cell.thirdAddress.text = [[[[self.appDelegate rssParser] rssItems] objectAtIndex:countingIndex] Address];
        cell.thirdPrice.text = [[[[self.appDelegate rssParser] rssItems] objectAtIndex:countingIndex] Deposit];
        if ([[[[[[self appDelegate] rssParser]rssItems]objectAtIndex:countingIndex] imageURLs] count] != 0 ) {
            [cell.thirdImage setImageWithURL:[NSURL URLWithString:[[[[[self.appDelegate rssParser] rssItems] objectAtIndex:countingIndex] imageURLs] objectAtIndex:0.0]]];
            cell.thirdImage.tag = countingIndex;
        }
    }

    countingIndex++;
    if (countingIndex < [[[self.appDelegate rssParser] rssItems] count]) {
        cell.fourthAddress.text = [[[[self.appDelegate rssParser] rssItems] objectAtIndex:countingIndex] Address];
        cell.fourthPrice.text = [[[[self.appDelegate rssParser] rssItems] objectAtIndex:countingIndex] Deposit];
        if ([[[[[[self appDelegate] rssParser]rssItems]objectAtIndex:countingIndex] imageURLs] count] != 0 ) {
            [cell.fourthImage setImageWithURL:[NSURL URLWithString:[[[[[self.appDelegate rssParser] rssItems] objectAtIndex:countingIndex] imageURLs] objectAtIndex:0.0]]];
            cell.fourthImage.tag = countingIndex;
        }
    }

    countingIndex++;

    return cell;
}

It is a bit messy but it works.....until I scroll. After the image is loaded then scrolled off the screen the image disappears.

I believe that it maybe due to the imageViews of the cells being lost?

I tried the exact same implementation but with only 1 imageView in each cell and all works great.

Any point in the right direction would be very much appreciated.

I appreciate any help and thank you for your time.

Body:
I had the similar problem, but solved by putting the actual image loading part inside "willDisplayCell" not in "cellForRow".

- (void)tableView:(UITableView *)tableView willDisplayCell:(CalendarTableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {

    PHImageRequestOptions *options = [[PHImageRequestOptions alloc]init];
    options.networkAccessAllowed = YES; //NO; //ver3.9.4
    options.synchronous  = NO;
    options.deliveryMode = PHImageRequestOptionsDeliveryModeOpportunistic;
    options.resizeMode   = PHImageRequestOptionsResizeModeNone;
    options.version      = PHImageRequestOptionsVersionCurrent;
    options.progressHandler = ^(double progress, NSError *error, BOOL *stop, NSDictionary *dictionary) {
        dispatch_async(dispatch_get_main_queue(), ^{
            // self.progressView.progress = progress;
            // self.progressView.hidden = (progress <= 0.0 || progress >= 1.0);
        });
    };
    cell.tag = indexPath.row; //ver3.8.3

    cell.imageRequestID = [self.imageManager requestImageForAsset:asset
                                                               targetSize:targetSize
                                                              contentMode:PHImageContentModeAspectFit
                                                                  options:options
                                                            resultHandler:^(UIImage *result, NSDictionary *info) {
                                                                if (cell != nil) {
                                                                    if (cell.tag == indexPath.row) {
                                                                        dispatch_async(dispatch_get_main_queue(), ^{
                                                                            cell.photoImageView.image = result;
                                                                            cell.timesUpdated++;
                                                                            NSLog(@"cell.photoImageView.image SUCCESS!!");
                                                                            NSLog(@"indexPath.row = %ld",(long)indexPath.row);
                                                                        });
                                                                    }
                                                                }
                                                            }];

}


问:
How can I change css for the React code depending on the Redux state (true or false)
I'm using the react-calendar. In the UI you can choose the starting date of a range. The end of the range is made automatically depending on what user choose. They can choose between 7, 14, 21, 28 days. In  component the range is set to false as if it is true user has to click second time and then I can't use automatic end date selection. This works fine.
But I've added a checkbox (with weekends). It should work in the way that if it is not checked the range excludes weekends. I can do it only visually changing the css file. I've prepared two css files where in one weekends background is white. The problem is that it works fine at the beginning. Then when I check the checkbox it shows the range with weekends but when i uncheck the checkbox nothing changes. I think I know where is the problem but I can't solve it...

The Calendar.js file:

```<code>import "react-calendar/dist/Calendar.css";
//import './Calendar.css';
//I use default react-calendar css plus the customized one

import React from "react";
import Calendar from "react-calendar";

import { setDateAction } from "./calendarSlice";

export const CalendarFull = (props) => {
  const { chosenDate, chosenDuration, withWeekends, dispatch } = props;
    // I take the chosenDuration and pass through dispatch to use it in the calendar Reducer (setCurrentDateReducer)
    // where I need it for adding a range

  if (withWeekends === true) {
    const x = require('./Calendar.css');
  } else {
    const x = require("./Calendar1.css");
  }

  const onChangeSetDate = (date) => {
        dispatch(setDateAction(date, chosenDuration));
  };

  return (
    <div className="calendar">
      <div className="calendar-container">
        <Calendar
          onChange={onChangeSetDate}
          value={chosenDate}
          minDate={new Date()}
        />
      </div>
    </div>
  );
};
</code>```

The Calendar.css file:

```<code>.react-calendar {
 width: 400px;
 max-width: 100%;
 background-color: #fff;
 color: #222;
 border-radius: 8px;
 box-shadow: 0 12px 24px rgba(0, 0, 0, 0.2);
 font-family: Arial, Helvetica, sans-serif;
 line-height: 1.125em;
 margin-top: 2rem;
 margin-left: 1rem;

}
.react-calendar__navigation button {
 color: #6f48eb;
 min-width: 44px;
 background: none;
 font-size: 16px;
 margin-top: 8px;
}
.react-calendar__navigation button:enabled:hover,
.react-calendar__navigation button:enabled:focus {
 background-color: #f8f8fa;
}
.react-calendar__navigation button[disabled] {
 background-color: #f0f0f0;
}
abbr[title] {
 text-decoration: none;
}
 .react-calendar__month-view__days__day--weekend {
 color: #d10000;
}
.react-calendar__tile:enabled:hover,
.react-calendar__tile:enabled:focus {
 background: #6565b8;
 color: #6f48eb;
 border-radius: 6px;
}
.react-calendar__tile--now {
 background: white;
 border-radius: 6px;
 font-weight: bold;
 color: #0d9924;
}
.react-calendar__tile--now:enabled:hover,
.react-calendar__tile--now:enabled:focus {
 background: #6f48eb33;
 border-radius: 6px;
 font-weight: bold;
 color: white;
}
.react-calendar__tile--hasActive:enabled:hover,
.react-calendar__tile--hasActive:enabled:focus {
 background: #a4a4e2;
}
.react-calendar__tile--active {
 background: #6f48eb;
 border-radius: 6px;
 font-weight: bold;
 color: white;
}
.react-calendar__tile--active:enabled:hover,
.react-calendar__tile--active:enabled:focus {
 background: #a4a4e2;
 color: white;
}
.react-calendar--selectRange .react-calendar__tile--hover {
 background-color: #a8a8f3;
}
.react-calendar__tile--range {
 background: #a4a4e2;
 color: white;
 border-radius: 0;
}
/*.react-calendar__month-view__days__day--weekend {
 color: #d10000;
 background-color: white;
}*/
.react-calendar__tile--rangeStart {
 border-top-right-radius: 0;
 border-bottom-right-radius: 0;
 border-top-left-radius: 6px;
 border-bottom-left-radius: 6px;
 background: #a4a4e2;
 color: white;
}
.react-calendar__tile--rangeEnd {
 border-top-left-radius: 0;
 border-bottom-left-radius: 0;
 border-top-right-radius: 6px;
 border-bottom-right-radius: 6px;
 background: #a4a4e2;
 color: white;
}
</code>```

In the Calendar1.css at the end I have:

```<code> .react-calendar__month-view__days__day--weekend {
 color: #d10000;
 background-color: white;
}
</code>```

This is the only difference.

Is there any way to make it working or maybe some completly diffferent approach?

答:
I've tried a different approach and modified the Calendar.js file like that:

```<code>import './Calendar.css';
.
...
       return (
         <div>
          <Calendar
            onChange={onChangeSetDate}
            value={chosenDate}
            minDate={new Date()}
            className={
              withWeekends
              ? "react-calendar"
              : "react-calendar__month-view__days__day--weekend1"
            }
          />
        </div>
);
</code>```

and in the css file:

```<code>.react-calendar__month-view__days__day--weekend1 {
 color: #d10000;
 background-color: white;
}
</code>```

I doesn't change weekends but changes the color of days of the week - like Mon, Tue, etc.
In a separate file the same changes weekends.
I'm quite confused and running out of ideas.

I've also tried:

```<code> className={
              withWeekends
              ? "react-calendar"
              : "react-calendar1"
            }
</code>```

with in css:

```<code>.react-calendar1__month-view__days__day--weekend {
 color: #d10000;
 background-color: white;
}
</code>```

Result - nothing changes. I'm not good at BAM (quite bad I would say)...

Body:
I'm using the react-calendar. In the UI you can choose the starting date of a range. The end of the range is made automatically depending on what user choose. They can choose between 7, 14, 21, 28 days. In  component the range is set to false as if it is true user has to click second time and then I can't use automatic end date selection. This works fine.
But I've added a checkbox (with weekends). It should work in the way that if it is not checked the range excludes weekends. I can do it only visually changing the css file. I've prepared two css files where in one weekends background is white. The problem is that it works fine at the beginning. Then when I check the checkbox it shows the range with weekends but when i uncheck the checkbox nothing changes. I think I know where is the problem but I can't solve it...

The Calendar.js file:

import "react-calendar/dist/Calendar.css";
//import './Calendar.css';
//I use default react-calendar css plus the customized one

import React from "react";
import Calendar from "react-calendar";

import { setDateAction } from "./calendarSlice";

export const CalendarFull = (props) => {
  const { chosenDate, chosenDuration, withWeekends, dispatch } = props;
    // I take the chosenDuration and pass through dispatch to use it in the calendar Reducer (setCurrentDateReducer)
    // where I need it for adding a range

  if (withWeekends === true) {
    const x = require('./Calendar.css');
  } else {
    const x = require("./Calendar1.css");
  }

  const onChangeSetDate = (date) => {
        dispatch(setDateAction(date, chosenDuration));
  };

  return (

        <Calendar
          onChange={onChangeSetDate}
          value={chosenDate}
          minDate={new Date()}
        />

  );
};

The Calendar.css file:

.react-calendar {
 width: 400px;
 max-width: 100%;
 background-color: #fff;
 color: #222;
 border-radius: 8px;
 box-shadow: 0 12px 24px rgba(0, 0, 0, 0.2);
 font-family: Arial, Helvetica, sans-serif;
 line-height: 1.125em;
 margin-top: 2rem;
 margin-left: 1rem;

}
.react-calendar__navigation button {
 color: #6f48eb;
 min-width: 44px;
 background: none;
 font-size: 16px;
 margin-top: 8px;
}
.react-calendar__navigation button:enabled:hover,
.react-calendar__navigation button:enabled:focus {
 background-color: #f8f8fa;
}
.react-calendar__navigation button[disabled] {
 background-color: #f0f0f0;
}
abbr[title] {
 text-decoration: none;
}
 .react-calendar__month-view__days__day--weekend {
 color: #d10000;
}
.react-calendar__tile:enabled:hover,
.react-calendar__tile:enabled:focus {
 background: #6565b8;
 color: #6f48eb;
 border-radius: 6px;
}
.react-calendar__tile--now {
 background: white;
 border-radius: 6px;
 font-weight: bold;
 color: #0d9924;
}
.react-calendar__tile--now:enabled:hover,
.react-calendar__tile--now:enabled:focus {
 background: #6f48eb33;
 border-radius: 6px;
 font-weight: bold;
 color: white;
}
.react-calendar__tile--hasActive:enabled:hover,
.react-calendar__tile--hasActive:enabled:focus {
 background: #a4a4e2;
}
.react-calendar__tile--active {
 background: #6f48eb;
 border-radius: 6px;
 font-weight: bold;
 color: white;
}
.react-calendar__tile--active:enabled:hover,
.react-calendar__tile--active:enabled:focus {
 background: #a4a4e2;
 color: white;
}
.react-calendar--selectRange .react-calendar__tile--hover {
 background-color: #a8a8f3;
}
.react-calendar__tile--range {
 background: #a4a4e2;
 color: white;
 border-radius: 0;
}
/*.react-calendar__month-view__days__day--weekend {
 color: #d10000;
 background-color: white;
}*/
.react-calendar__tile--rangeStart {
 border-top-right-radius: 0;
 border-bottom-right-radius: 0;
 border-top-left-radius: 6px;
 border-bottom-left-radius: 6px;
 background: #a4a4e2;
 color: white;
}
.react-calendar__tile--rangeEnd {
 border-top-left-radius: 0;
 border-bottom-left-radius: 0;
 border-top-right-radius: 6px;
 border-bottom-right-radius: 6px;
 background: #a4a4e2;
 color: white;
}

In the Calendar1.css at the end I have:

 .react-calendar__month-view__days__day--weekend {
 color: #d10000;
 background-color: white;
}

This is the only difference.

Is there any way to make it working or maybe some completly diffferent approach?

Body:
I've tried a different approach and modified the Calendar.js file like that:

import './Calendar.css';
.
...
       return (
         <div>
          <Calendar
            onChange={onChangeSetDate}
            value={chosenDate}
            minDate={new Date()}
            className={
              withWeekends
              ? "react-calendar"
              : "react-calendar__month-view__days__day--weekend1"
            }
          />
        </div>
);

and in the css file:

.react-calendar__month-view__days__day--weekend1 {
 color: #d10000;
 background-color: white;
}

I doesn't change weekends but changes the color of days of the week - like Mon, Tue, etc.
In a separate file the same changes weekends.
I'm quite confused and running out of ideas.

I've also tried:

 className={
              withWeekends
              ? "react-calendar"
              : "react-calendar1"
            }

with in css:

.react-calendar1__month-view__days__day--weekend {
 color: #d10000;
 background-color: white;
}

Result - nothing changes. I'm not good at BAM (quite bad I would say)...


问:
Show as Html on vuejs
i have json file for translate ( en.json ) and this line :

```<code>{
  "cancel order": "Hi, How can i <b> Cancel </b> ?",
}

      <div class="d-flex align-items-center justify-content-center align-content-center mb-4">
    <span class="description col-sm-11 col-md-7 col-lg-10">

    {{ $t('cancel order') }}

    </span>
  </div>
</code>```

now my result is  " Hi, How can i  Cancel  "

The problem is that the html code does not apply like this  code and the tags are displayed exactly without being applied.

答:
use this :</p>
```<code><div v-html="$t('cancel order')"></div>
</code>```

Title: Show as Html on vuejs

Body:
i have json file for translate ( en.json ) and this line :

{
  "cancel order": "Hi, How can i  Cancel  ?",
}

    {{ $t('cancel order') }}

now my result is  " Hi, How can i  Cancel  "

The problem is that the html code does not apply like this  code and the tags are displayed exactly without being applied.

Body:
use this :

<div v-html="$t('cancel order')"></div>


问:
My custom Regex email validator is not working as intended
I am trying to create a custom Regex to validate emails that follow the rules stated below:

Email should start with a alphabet (a-z) and should not start with special characters or numeric values

after the first letter, it could contains numbers(0-9), letters(a-z), underscores(_) and dot(.)

it should have only one @ symbol in it

after the @ symbol, it should only allow to contain alphabets and dot (no more special characters or numbers other than dot(.))

email should not end with dot(.) but rather end with an alphabet

it should not have any whitespace anywhere

I have two arrays: trueEmails contains valid emails and notEmails contains invalid emails.

I created the following Regex:

```<code>const email = /^[a-zA-Z]+(\d|.|\w)*@[a-zA-Z]+.[a-zA-Z]+.*[a-zA-Z]+$/;
</code>```

My Regex is not working for rule no. 2, 3, 4 and 6. Here is my code.

const notEmails = [
    // rule 1
    '_test@email.com',
    '#test@email.com',
    '1test@email.com',
    // rule 2
    'test&131@yahoo.com',
    // rule 3
    'test@gmail@yahoo.com',
    // rule 4
    'test@yahoo23.com',
    // rule 5
    'test@yahdsd.com.',
    // rule 6
    'white space@gmail.com'

]

const trueEmails = [
    // rule 1
    'test@email.com',
    // rule 2
    'test2email@yahoo.com',
    'test_email@yahoo.com',
    'test.123_.emai.l@yahoo.com',
    // rule 3
    'test@gmail.com',
    // rule 4
    'testsample@yahoo.co.in',
    // rule 5
    'testdample232@gmail.com',
    // rule 6
    'no_white_space@gmail.com'
]

const email = /^[a-zA-Z]+(\d|.|\w)*@[a-zA-Z]+.[a-zA-Z]+.*[a-zA-Z]+$/;

console.log("NotEmails, should return false")
console.log(notEmails.map((each) => each + ' => ' + email.test(each)));

console.log("trueEmails, should return true")
console.log(trueEmails.map((each) => each + ' => ' +  email.test(each)));```

Thanks in advance.

答:
I've updated the regex to work for you. It's not fool proof but works for the restrictions you've put in place.

const notEmails = [
    // rule 1
    '_test@email.com',
    '#test@email.com',
    '1test@email.com',
    // rule 2
    'test&131@yahoo.com',
    // rule 3
    'test@gmail@yahoo.com',
    // rule 4
    'test@yahoo23.com',
    // rule 5
    'test@yahdsd.com.',
    // rule 6
    'white space@gmail.com'

]

const trueEmails = [
    // rule 1
    'test@email.com',
    // rule 2
    'test2email@yahoo.com',
    'test_email@yahoo.com',
    'test.123_.emai.l@yahoo.com',
    // rule 3
    'test@gmail.com',
    // rule 4
    'testsample@yahoo.co.in',
    // rule 5
    'testdample232@gmail.com',
    // rule 6
    'no_white_space@gmail.com'
]

const email = /^[a-zA-Z]+[a-zA-Z0-9_.]+@[a-zA-Z.]+[a-zA-Z]$/;

console.log("NotEmails, should return false")
console.log(notEmails.map((each) => each + ' => ' + email.test(each)));

console.log("trueEmails, should return true")
console.log(trueEmails.map((each) => each + ' => ' +  email.test(each)));```

Description

Regex: /^[a-zA-Z]+[a-zA-Z0-9_.]+@[a-zA-Z.]+[a-zA-Z]$/

^ Start of line

[a-zA-Z] any character from a-z

+ one or more times

[a-zA-Z0-9_.] any character from a-z, and number, underscores and periods.

+ one or more times

@ matches literal @ sign

[a-zA-Z.]+ any character from a-z and periods

+ one or more times

[a-zA-Z]` any character from a-z

$ end of line

Body:
I am trying to create a custom Regex to validate emails that follow the rules stated below:

Email should start with a alphabet (a-z) and should not start with special characters or numeric values

after the first letter, it could contains numbers(0-9), letters(a-z), underscores(_) and dot(.)

it should have only one @ symbol in it

after the @ symbol, it should only allow to contain alphabets and dot (no more special characters or numbers other than dot(.))

email should not end with dot(.) but rather end with an alphabet

it should not have any whitespace anywhere

I have two arrays: trueEmails contains valid emails and notEmails contains invalid emails.

I created the following Regex:

const email = /^[a-zA-Z]+(\d|.|\w)*@[a-zA-Z]+.[a-zA-Z]+.*[a-zA-Z]+$/;

My Regex is not working for rule no. 2, 3, 4 and 6. Here is my code.

const notEmails = [
    // rule 1
    '_test@email.com',
    '#test@email.com',
    '1test@email.com',
    // rule 2
    'test&131@yahoo.com',
    // rule 3
    'test@gmail@yahoo.com',
    // rule 4
    'test@yahoo23.com',
    // rule 5
    'test@yahdsd.com.',
    // rule 6
    'white space@gmail.com'

]

const trueEmails = [
    // rule 1
    'test@email.com',
    // rule 2
    'test2email@yahoo.com',
    'test_email@yahoo.com',
    'test.123_.emai.l@yahoo.com',
    // rule 3
    'test@gmail.com',
    // rule 4
    'testsample@yahoo.co.in',
    // rule 5
    'testdample232@gmail.com',
    // rule 6
    'no_white_space@gmail.com'
]

const email = /^[a-zA-Z]+(\d|.|\w)*@[a-zA-Z]+.[a-zA-Z]+.*[a-zA-Z]+$/;

console.log("NotEmails, should return false")
console.log(notEmails.map((each) => each + ' => ' + email.test(each)));

console.log("trueEmails, should return true")
console.log(trueEmails.map((each) => each + ' => ' +  email.test(each)));

Thanks in advance.

Body:
I've updated the regex to work for you. It's not fool proof but works for the restrictions you've put in place.

const notEmails = [
    // rule 1
    '_test@email.com',
    '#test@email.com',
    '1test@email.com',
    // rule 2
    'test&131@yahoo.com',
    // rule 3
    'test@gmail@yahoo.com',
    // rule 4
    'test@yahoo23.com',
    // rule 5
    'test@yahdsd.com.',
    // rule 6
    'white space@gmail.com'

]

const trueEmails = [
    // rule 1
    'test@email.com',
    // rule 2
    'test2email@yahoo.com',
    'test_email@yahoo.com',
    'test.123_.emai.l@yahoo.com',
    // rule 3
    'test@gmail.com',
    // rule 4
    'testsample@yahoo.co.in',
    // rule 5
    'testdample232@gmail.com',
    // rule 6
    'no_white_space@gmail.com'
]

const email = /^[a-zA-Z]+[a-zA-Z0-9_.]+@[a-zA-Z.]+[a-zA-Z]$/;

console.log("NotEmails, should return false")
console.log(notEmails.map((each) => each + ' => ' + email.test(each)));

console.log("trueEmails, should return true")
console.log(trueEmails.map((each) => each + ' => ' +  email.test(each)));

Description

Regex: /^[a-zA-Z]+[a-zA-Z0-9_.]+@[a-zA-Z.]+[a-zA-Z]$/

^ Start of line

[a-zA-Z] any character from a-z

+ one or more times

[a-zA-Z0-9_.] any character from a-z, and number, underscores and periods.

+ one or more times

@ matches literal @ sign

[a-zA-Z.]+ any character from a-z and periods

+ one or more times

[a-zA-Z]` any character from a-z

$ end of line


问:
Unusual problem when dragging a child control in C#
I found some code here and elsewhere on the net about how to drag child controls inside of a form with the mouse at runtime.  The goal is to let the user arrange these and other child controls on the form.  Right now my main form has two controls, pictureBox1 and panel1.  pictureBox1 has a photo in it, and panel1 has a button and some text boxes.  Each of these controls can be moved when the user left-clicks inside either one of them and drags it, so I handle mouse down, mouse move and mouse up events. The code is working with just these two child controls, but I'm not sure why.  Below are my mouse down and mouse move event handlers:

```<code>    private Point MouseDownLocation;
    private Point controlDestinationLocation;
    private void control_MouseDown(object sender, MouseEventArgs e)
    {
        // label1 shows e.X and e.Y whenever the mouse is over panel1 or pictureBox1
        label1.Text = "Mouseover (e.X,e.Y): (" + e.X + "," + e.Y + ")";
        // If the left mouse button is down, set MouseDownLocation to the current mouse coordinates
        // and controlDestinationLocation to the upper left corner of either panel1 or pictureBox1
        if (e.Button == MouseButtons.Left)
        {
            MouseDownLocation = e.Location;
            Control ctrl = (Control)sender;
            ctrl.BringToFront();
            controlDestinationLocation = ctrl.Location;
            // ...and display the locations
            label2.Text = "MouseDown: (" + MouseDownLocation.X + "," + MouseDownLocation.Y + ")";
            label3.Text = "Destination: (" + controlDestinationLocation.X + "," + controlDestinationLocation.Y + ")";
            label4.Text = "Left button pressed (e.X,e.Y): (" + e.X + "," + e.Y + ")";
        }
    }

    private void control_MouseMove(object sender, MouseEventArgs e)
    {
        // label1 shows e.X and e.Y whenever the mouse is over panel1 or pictureBox1
        label1.Text = "Mouseover (e.X,e.Y): (" + e.X + "," + e.Y + ")";
        if (e.Button == MouseButtons.Left)
        {
            // If the left mouse button is down, move the child control first
            Control thisCtrl = (Control)sender;
            int dX = e.X - MouseDownLocation.X;
            int dY = e.Y - MouseDownLocation.Y;
            thisCtrl.Left += dX;
            thisCtrl.Top += dY;
            // Then display all the locations in text boxes
            label2.Text = "MouseDown: (" + MouseDownLocation.X + "," + MouseDownLocation.Y + ")";
            label3.Text = "Destination: (" + controlDestinationLocation.X + "," + controlDestinationLocation.Y + ")";
            label4.Text = "Left button pressed (e.X,e.Y): (" + e.X + "," + e.Y + ")";
            label5.Text = "(dX,dY): (" + dX + "," + dY + ")";
            int X1 = pictureBox1.Location.X;
            int Y1 = pictureBox1.Location.Y;
            int X2 = pictureBox1.Right;
            int Y2 = pictureBox1.Bottom;
            label6.Text = "pictureBox1: (" + X1 + "," + Y1 + ") - (" + X2 + ", " + Y2 + ")";
            X1 = panel1.Location.X;
            Y1 = panel1.Location.Y;
            X2 = panel1.Right;
            Y2 = panel1.Bottom;
            label7.Text = "panel1: (" + X1 + "," + Y1 + ") - (" + X2 + ", " + Y2 + ")";
        }
    }
</code>```

In control_MouseMove(), thisCtrl.Left and thisCtrl.Top (the upper left corner of the child control), are updated correctly by the variables dX and dY, but what I don't understand is this: When I display dX and dY (using a text box inside panel1), they both turn out to be zero, but at the same time thisCtrl.Left and thisCtrl.Top are both updated by some nonzero values because the child control I drag is moving.  So, either dX is one value when updating thisCtrl.Left than it is when displayed in a text box (same goes for dY), or I am missing something.  Thanks for any help on this.

答:
Jimi, I think you are exactly right that seeing 0 most of the time is the answer.

I assumed if I didn't move the mouse then I'd see dX and/or dY as nonzero at least sometimes, but I think the label controls I'm using get updated so often that I am only seeing 0.

Instead of using text labels to watch the mouse move, I copied e.X and e.Y to an array of Point values while the mouse was moving and saw nonzero values.

Thanks.

Body:
I found some code here and elsewhere on the net about how to drag child controls inside of a form with the mouse at runtime.  The goal is to let the user arrange these and other child controls on the form.  Right now my main form has two controls, pictureBox1 and panel1.  pictureBox1 has a photo in it, and panel1 has a button and some text boxes.  Each of these controls can be moved when the user left-clicks inside either one of them and drags it, so I handle mouse down, mouse move and mouse up events. The code is working with just these two child controls, but I'm not sure why.  Below are my mouse down and mouse move event handlers:

    private Point MouseDownLocation;
    private Point controlDestinationLocation;
    private void control_MouseDown(object sender, MouseEventArgs e)
    {
        // label1 shows e.X and e.Y whenever the mouse is over panel1 or pictureBox1
        label1.Text = "Mouseover (e.X,e.Y): (" + e.X + "," + e.Y + ")";
        // If the left mouse button is down, set MouseDownLocation to the current mouse coordinates
        // and controlDestinationLocation to the upper left corner of either panel1 or pictureBox1
        if (e.Button == MouseButtons.Left)
        {
            MouseDownLocation = e.Location;
            Control ctrl = (Control)sender;
            ctrl.BringToFront();
            controlDestinationLocation = ctrl.Location;
            // ...and display the locations
            label2.Text = "MouseDown: (" + MouseDownLocation.X + "," + MouseDownLocation.Y + ")";
            label3.Text = "Destination: (" + controlDestinationLocation.X + "," + controlDestinationLocation.Y + ")";
            label4.Text = "Left button pressed (e.X,e.Y): (" + e.X + "," + e.Y + ")";
        }
    }

    private void control_MouseMove(object sender, MouseEventArgs e)
    {
        // label1 shows e.X and e.Y whenever the mouse is over panel1 or pictureBox1
        label1.Text = "Mouseover (e.X,e.Y): (" + e.X + "," + e.Y + ")";
        if (e.Button == MouseButtons.Left)
        {
            // If the left mouse button is down, move the child control first
            Control thisCtrl = (Control)sender;
            int dX = e.X - MouseDownLocation.X;
            int dY = e.Y - MouseDownLocation.Y;
            thisCtrl.Left += dX;
            thisCtrl.Top += dY;
            // Then display all the locations in text boxes
            label2.Text = "MouseDown: (" + MouseDownLocation.X + "," + MouseDownLocation.Y + ")";
            label3.Text = "Destination: (" + controlDestinationLocation.X + "," + controlDestinationLocation.Y + ")";
            label4.Text = "Left button pressed (e.X,e.Y): (" + e.X + "," + e.Y + ")";
            label5.Text = "(dX,dY): (" + dX + "," + dY + ")";
            int X1 = pictureBox1.Location.X;
            int Y1 = pictureBox1.Location.Y;
            int X2 = pictureBox1.Right;
            int Y2 = pictureBox1.Bottom;
            label6.Text = "pictureBox1: (" + X1 + "," + Y1 + ") - (" + X2 + ", " + Y2 + ")";
            X1 = panel1.Location.X;
            Y1 = panel1.Location.Y;
            X2 = panel1.Right;
            Y2 = panel1.Bottom;
            label7.Text = "panel1: (" + X1 + "," + Y1 + ") - (" + X2 + ", " + Y2 + ")";
        }
    }

In control_MouseMove(), thisCtrl.Left and thisCtrl.Top (the upper left corner of the child control), are updated correctly by the variables dX and dY, but what I don't understand is this: When I display dX and dY (using a text box inside panel1), they both turn out to be zero, but at the same time thisCtrl.Left and thisCtrl.Top are both updated by some nonzero values because the child control I drag is moving.  So, either dX is one value when updating thisCtrl.Left than it is when displayed in a text box (same goes for dY), or I am missing something.  Thanks for any help on this.


问:
VS Code: ModuleNotFoundError: No module named 'pandas'
Tried to import pandas in VS Code with

```<code>import pandas
</code>```

and got

```<code>Traceback (most recent call last):
  File "c:\Users\xxxx\hello\sqltest.py", line 2, in <module>
    import pandas
ModuleNotFoundError: No module named 'pandas'
</code>```

Tried to install pandas with

```<code>pip install pandas

pip3 install pandas

python -m pip install pandas
</code>```

separately which returned

```<code>(.venv) PS C:\Users\xxxx\hello> pip3 install pandas

Requirement already satisfied: pandas in c:\users\xxxx\hello\.venv\lib\site-packages (1.1.0)
Requirement already satisfied: pytz>=2017.2 in c:\users\xxxx\hello\.venv\lib\site-packages (from pandas) (2020.1)
Requirement already satisfied: numpy>=1.15.4 in c:\users\xxxx\hello\.venv\lib\site-packages (from pandas) (1.19.1)
Requirement already satisfied: python-dateutil>=2.7.3 in c:\users\xxxx\hello\.venv\lib\site-packages (from pandas) (2.8.1)
Requirement already satisfied: six>=1.5 in c:\users\xxxx\hello\.venv\lib\site-packages (from python-dateutil>=2.7.3->pandas) (1.15.0)
</code>```

Tried:

```<code>sudo pip install pandas
</code>```

and got

```<code>(.venv) PS C:\Users\xxxx\hello> sudo pip install pandas

sudo : The term 'sudo' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ sudo pip install pandas
+ ~~~~
    + CategoryInfo          : ObjectNotFound: (sudo:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
</code>```

I also tried to change the python path under workspace settings following this answer. with C:\Users\xxxx\AppData\Local\Microsoft\WindowsApps\python.exe which is the python path I found in Command Prompt using where python but didn't work.

Then I tried

```<code>python -m venv .venv
</code>```

which returned

```<code>(.venv) PS C:\Users\xxxx\hello> python -m venv .venv

Error: [Errno 13] Permission denied: 'C:\\Users\\xxxx\\hello\\.venv\\Scripts\\python.exe'
</code>```

Update:

Tried

```<code>python3.8.5 -m pip install pandas
</code>```

and returned

```<code>(.venv) PS C:\Users\xxxx\hello> python3.8.5 -m pip install pandas

python3.8.5 : The term 'python3.8.5' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ python3.8.5 -m pip install pandas
+ ~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (python3.8.5:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
</code>```

答:
Download anaconda interpreter from this link

After installation, open anaconda prompt (anaconda3) and execute this code conda install ipykernel. It will install all necessary packages.

Restart vs code and change interpreter to base conda and voala!

Body:
Tried to import pandas in VS Code with

import pandas

and got

Traceback (most recent call last):
  File "c:\Users\xxxx\hello\sqltest.py", line 2, in <module>
    import pandas
ModuleNotFoundError: No module named 'pandas'

Tried to install pandas with

pip install pandas

pip3 install pandas

python -m pip install pandas

separately which returned

(.venv) PS C:\Users\xxxx\hello> pip3 install pandas

Requirement already satisfied: pandas in c:\users\xxxx\hello\.venv\lib\site-packages (1.1.0)
Requirement already satisfied: pytz>=2017.2 in c:\users\xxxx\hello\.venv\lib\site-packages (from pandas) (2020.1)
Requirement already satisfied: numpy>=1.15.4 in c:\users\xxxx\hello\.venv\lib\site-packages (from pandas) (1.19.1)
Requirement already satisfied: python-dateutil>=2.7.3 in c:\users\xxxx\hello\.venv\lib\site-packages (from pandas) (2.8.1)
Requirement already satisfied: six>=1.5 in c:\users\xxxx\hello\.venv\lib\site-packages (from python-dateutil>=2.7.3->pandas) (1.15.0)

Tried:

sudo pip install pandas

and got

(.venv) PS C:\Users\xxxx\hello> sudo pip install pandas

sudo : The term 'sudo' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ sudo pip install pandas
+ ~~~~
    + CategoryInfo          : ObjectNotFound: (sudo:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

I also tried to change the python path under workspace settings following this answer. with C:\Users\xxxx\AppData\Local\Microsoft\WindowsApps\python.exe which is the python path I found in Command Prompt using where python but didn't work.

Then I tried

python -m venv .venv

which returned

(.venv) PS C:\Users\xxxx\hello> python -m venv .venv

Error: [Errno 13] Permission denied: 'C:\\Users\\xxxx\\hello\\.venv\\Scripts\\python.exe'

Update:

Tried

python3.8.5 -m pip install pandas

and returned

(.venv) PS C:\Users\xxxx\hello> python3.8.5 -m pip install pandas

python3.8.5 : The term 'python3.8.5' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ python3.8.5 -m pip install pandas
+ ~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (python3.8.5:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException


问:
How to return a react component with the for in statement?
I'm trying to iterate over a nested object with the for..in statement an return text component for each object iterated over.

```<code>const animals = {
  "cat": Object {
    "number": 0,
  },
  "dog": Object {
    "number": 1,
  }
{
      for(let item in animals) {
        for(let property in animals[item]){
          return (
            <Text>{item}</Text>
            <Text>{animals[item][property]}</Text>
          )
      }
    }
}
</code>```

As you see above, I tried to wrap the function in curly brackets in hopes of using jsx to render the components much like one would do with .map, but I got a slew of errors, so I'm pretty sure this incorrect.

My Linter says Expression expected for the two for(s) and the return ().

I can console.log item, and animals[item][property] so I am confident everything outside the return () is correct.

How would I go about correctly returning the Text elements?

答:
You have to use react fragment, like this</p>
```<code><>
<Text>{item}</Text>
<Text>{animals[item][property]}</Text>
</>
</code>```

Body:
I'm trying to iterate over a nested object with the for..in statement an return text component for each object iterated over.

const animals = {
  "cat": Object {
    "number": 0,
  },
  "dog": Object {
    "number": 1,
  }
{
      for(let item in animals) {
        for(let property in animals[item]){
          return (
            <Text>{item}</Text>
            <Text>{animals[item][property]}</Text>
          )
      }
    }
}

As you see above, I tried to wrap the function in curly brackets in hopes of using jsx to render the components much like one would do with .map, but I got a slew of errors, so I'm pretty sure this incorrect.

My Linter says Expression expected for the two for(s) and the return ().

I can console.log item, and animals[item][property] so I am confident everything outside the return () is correct.

How would I go about correctly returning the Text elements?

Body:
You have to use react fragment, like this

<>
<Text>{item}</Text>
<Text>{animals[item][property]}</Text>
</>