问:
Batch - Cleaner way to find largest given variable?
The following code works for my problem but as you can see it is heavily protracted. So i was wondering if there was a more efficient way to find the largest of 6 given variables.

Code

```<code>
    @echo off
    Set /a picture0 = 4
    Set /a picture1 = 10
    Set /a picture2 = 9
    Set /a picture3 = 6
    Set /a picture4 = 71
    Set /a picture5 = 6
    Set /a picture6 = 5

    Call :TestPicture0
    Call :TestPicture1
    Call :TestPicture2
    Call :TestPicture3
    Call :TestPicture4
    Call :TestPicture5
    Call :TestPicture6
    @pause
    GoTo :EOF
</code>```

So I have the six variables I want to use right, and I call each of them separately because they are rather long.

```<code>
  :TestPicture0

    Set /a Test01 = %picture0% - %picture0%
    Set /a Result01 = 0
    Set /a Test02 = %picture0% - %picture2%
    Set /a Result02 = 0
    Set /a Test03 = %picture0% - %picture3%
    Set /a Result03 = 0
    Set /a Test04 = %picture0% - %picture4%
    Set /a Result04 = 0
    Set /a Test05 = %picture0% - %picture5%
    Set /a Result05 = 0
    Set /a Test06 = %picture0% - %picture6%
    Set /a Result06 = 0

    if %Test01% GEQ 0 (Set /a Result01 = 1)else (Set /a Result01 = 0)
    if %Test02% GEQ 0 (Set /a Result02 = 1)else (Set /a Result02 = 0)
    if %Test03% GEQ 0 (Set /a Result03 = 1)else (Set /a Result03 = 0)
    if %Test04% GEQ 0 (Set /a Result04 = 1)else (Set /a Result04 = 0)
    if %Test05% GEQ 0 (Set /a Result05 = 1)else (Set /a Result05 = 0)
    if %Test06% GEQ 0 (Set /a Result06 = 1)else (Set /a Result06 = 0)

    Set /a Picture0Final = %Result06% + %Result05% + %Result04% + %Result03% + %Result02% + %Result01%

    If %Picture0Final% EQU 6 (Echo Picture Zero) Else (Echo no)
    GoTo :EOF

    :TestPicture1
    Set /a Test10 = %picture1% - %picture0%
    Set /a Result10 = 0
    Set /a Test12 = %picture1% - %picture2%
    Set /a Result12 = 0
    Set /a Test13 = %picture1% - %picture3%
    Set /a Result13 = 0
    Set /a Test14 = %picture1% - %picture4%
    Set /a Result14 = 0
    Set /a Test15 = %picture1% - %picture5%
    Set /a Result15 = 0
    Set /a Test16 = %picture1% - %picture6%
    Set /a Result16 = 0

    if %Test10% GEQ 0 (Set /a Result10 = 1)else (Set /a Result10 = 0)
    if %Test12% GEQ 0 (Set /a Result12 = 1)else (Set /a Result12 = 0)
    if %Test13% GEQ 0 (Set /a Result13 = 1)else (Set /a Result13 = 0)
    if %Test14% GEQ 0 (Set /a Result14 = 1)else (Set /a Result14 = 0)
    if %Test15% GEQ 0 (Set /a Result15 = 1)else (Set /a Result15 = 0)
    if %Test16% GEQ 0 (Set /a Result16 = 1)else (Set /a Result16 = 0)

    Set /a Picture1Final = %Result16% + %Result15% + %Result14% + %Result13% + %Result12% + %Result10%

    If %Picture1Final% EQU 6 (Echo Picture one) Else (Echo no)
    GoTo :EOF

    :TestPicture2
    Set /a Test20 = %picture2% - %picture0%
    Set /a Result20 = 0
    Set /a Test21 = %picture2% - %picture1%
    Set /a Result21 = 0
    Set /a Test23 = %picture2% - %picture3%
    Set /a Result23 = 0
    Set /a Test24 = %picture2% - %picture4%
    Set /a Result24 = 0
    Set /a Test25 = %picture2% - %picture5%
    Set /a Result25 = 0
    Set /a Test26 = %picture2% - %picture6%
    Set /a Result26 = 0

    if %Test20% GEQ 0 (Set /a Result20 = 1)else (Set /a Result20 = 0)
    if %Test21% GEQ 0 (Set /a Result21 = 1)else (Set /a Result21 = 0)
    if %Test23% GEQ 0 (Set /a Result23 = 1)else (Set /a Result23 = 0)
    if %Test24% GEQ 0 (Set /a Result24 = 1)else (Set /a Result24 = 0)
    if %Test25% GEQ 0 (Set /a Result25 = 1)else (Set /a Result25 = 0)
    if %Test26% GEQ 0 (Set /a Result26 = 1)else (Set /a Result26 = 0)

    Set /a Picture2Final = %Result26% + %Result25% + %Result24% + %Result23% + %Result21% + %Result20%

    If %Picture2Final% EQU 6 (Echo Picture Two) Else (Echo no)
    GoTo :EOF

    :TestPicture3
    Set /a Test30 = %picture3% - %picture0%
    Set /a Result30 = 0
    Set /a Test31 = %picture3% - %picture1%
    Set /a Result11 = 0
    Set /a Test32 = %picture3% - %picture2%
    Set /a Result32 = 0
    Set /a Test34 = %picture3% - %picture4%
    Set /a Result34 = 0
    Set /a Test35 = %picture3% - %picture5%
    Set /a Result35 = 0
    Set /a Test36 = %picture3% - %picture6%
    Set /a Result36 = 0

    if %Test30% GEQ 0 (Set /a Result30 = 1)else (Set /a Result30 = 0)
    if %Test31% GEQ 0 (Set /a Result31 = 1)else (Set /a Result31 = 0)
    if %Test32% GEQ 0 (Set /a Result32 = 1)else (Set /a Result32 = 0)
    if %Test34% GEQ 0 (Set /a Result34 = 1)else (Set /a Result34 = 0)
    if %Test35% GEQ 0 (Set /a Result35 = 1)else (Set /a Result35 = 0)
    if %Test36% GEQ 0 (Set /a Result36 = 1)else (Set /a Result36 = 0)

    Set /a Picture3Final = %Result36% + %Result35% + %Result34% + %Result32% + %Result31% + %Result30%

    If %Picture3Final% EQU 6 (Echo Picture Three) Else (Echo no)
    GoTo :EOF

    :TestPicture4

    Set /a Test40 = %picture4% - %picture0%
    Set /a Result40 = 0
    Set /a Test42 = %picture4% - %picture2%
    Set /a Result42 = 0
    Set /a Test43 = %picture4% - %picture3%
    Set /a Result43 = 0
    Set /a Test41 = %picture4% - %picture1%
    Set /a Result41 = 0
    Set /a Test45 = %picture4% - %picture5%
    Set /a Result45 = 0
    Set /a Test46 = %picture4% - %picture6%
    Set /a Result46 = 0

    if %Test40% GEQ 0 (Set /a Result40 = 1)else (Set /a Result40 = 0)
    if %Test42% GEQ 0 (Set /a Result42 = 1)else (Set /a Result42 = 0)
    if %Test43% GEQ 0 (Set /a Result43 = 1)else (Set /a Result43 = 0)
    if %Test41% GEQ 0 (Set /a Result41 = 1)else (Set /a Result41 = 0)
    if %Test45% GEQ 0 (Set /a Result45 = 1)else (Set /a Result45 = 0)
    if %Test46% GEQ 0 (Set /a Result46 = 1)else (Set /a Result46 = 0)

    Set /a Picture4Final = %Result46% + %Result45% + %Result41% + %Result43% + %Result42% + %Result40%

    If %Picture4Final% GEQ 6 (Echo Picture Four) Else (Echo no)

    GoTo :EOF

    :TestPicture5
    Set /a Test50 = %picture5% - %picture0%
    Set /a Result50 = 0
    Set /a Test51 = %picture5% - %picture1%
    Set /a Result51 = 0
    Set /a Test52 = %picture5% - %picture2%
    Set /a Result52 = 0
    Set /a Test53 = %picture5% - %picture3%
    Set /a Result53 = 0
    Set /a Test54 = %picture5% - %picture5%
    Set /a Result54 = 0
    Set /a Test56 = %picture5% - %picture6%
    Set /a Result56 = 0

    if %Test50% GEQ 0 (Set /a Result50 = 1)else (Set /a Result50 = 0)
    if %Test51% GEQ 0 (Set /a Result51 = 1)else (Set /a Result51 = 0)
    if %Test52% GEQ 0 (Set /a Result52 = 1)else (Set /a Result52 = 0)
    if %Test53% GEQ 0 (Set /a Result53 = 1)else (Set /a Result53 = 0)
    if %Test54% GEQ 0 (Set /a Result54 = 1)else (Set /a Result54 = 0)
    if %Test56% GEQ 0 (Set /a Result56 = 1)else (Set /a Result56 = 0)

    Set /a Picture5Final = %Result56% + %Result54% + %Result53% + %Result52% + %Result51% + %Result50%

    If %Picture5Final% EQU 6 (Echo Picture Five) Else (Echo no)
    GoTo :EOF

    :TestPicture6
    Set /a Test60 = %picture6% - %picture0%
    Set /a Result60 = 0
    Set /a Test61 = %picture6% - %picture1%
    Set /a Result61 = 0
    Set /a Test62 = %picture6% - %picture2%
    Set /a Result62 = 0
    Set /a Test63 = %picture6% - %picture3%
    Set /a Result63 = 0
    Set /a Test64 = %picture6% - %picture6%
    Set /a Result64 = 0
    Set /a Test65 = %picture6% - %picture6%
    Set /a Result65 = 0

    if %Test60% GEQ 0 (Set /a Result60 = 1)else (Set /a Result60 = 0)
    if %Test61% GEQ 0 (Set /a Result61 = 1)else (Set /a Result61 = 0)
    if %Test62% GEQ 0 (Set /a Result62 = 1)else (Set /a Result62 = 0)
    if %Test63% GEQ 0 (Set /a Result63 = 1)else (Set /a Result63 = 0)
    if %Test64% GEQ 0 (Set /a Result64 = 1)else (Set /a Result64 = 0)
    if %Test65% GEQ 0 (Set /a Result65 = 1)else (Set /a Result65 = 0)

    Set /a Picture6Final = %Result65% + %Result64% + %Result63% + %Result62% + %Result61% + %Result60%

    If %Picture6Final% EQU 6 (Echo Picture Six) Else (Echo no)
    GoTo :EOF

</code>```

If yall know a way to make this better please let me know :D----<-<
*Edit: fixed some 0's to ones ... literally

答:
you asked how to

find the largest of 6 given variables

There is no need to minus each and compare the result to 0. It isn't even neccessary to compare the variables.

```<code>@echo off
====SETLOCAL EnableDelayedExpansion EnableExtensions

set/a"picture0=4,picture1=10,picture2=9,picture3=6,picture4=71,picture5=6,picture6=5,MAX=0"
FOR /L %%# in (0 1 6) do if !picture%%#! GTR !max! set/a"max=!picture%%#!,max_var=%%#"
echo MAX is picture%max_var%=%max%
</code>```

Limitations:

If %picture3% == %picture4% == 6, %max% will be picture3.

Works for 32-bits integers only. See Windows batch file IF failure - How can 30000000000000 equal 40000000000?

In this case, because the variables are in a "list", I used a FOR /L loop . But in case it's not, use FOR.

Body:
The following code works for my problem but as you can see it is heavily protracted. So i was wondering if there was a more efficient way to find the largest of 6 given variables.

Code

    @echo off
    Set /a picture0 = 4
    Set /a picture1 = 10
    Set /a picture2 = 9
    Set /a picture3 = 6
    Set /a picture4 = 71
    Set /a picture5 = 6
    Set /a picture6 = 5

    Call :TestPicture0
    Call :TestPicture1
    Call :TestPicture2
    Call :TestPicture3
    Call :TestPicture4
    Call :TestPicture5
    Call :TestPicture6
    @pause
    GoTo :EOF

So I have the six variables I want to use right, and I call each of them separately because they are rather long.

  :TestPicture0

    Set /a Test01 = %picture0% - %picture0%
    Set /a Result01 = 0
    Set /a Test02 = %picture0% - %picture2%
    Set /a Result02 = 0
    Set /a Test03 = %picture0% - %picture3%
    Set /a Result03 = 0
    Set /a Test04 = %picture0% - %picture4%
    Set /a Result04 = 0
    Set /a Test05 = %picture0% - %picture5%
    Set /a Result05 = 0
    Set /a Test06 = %picture0% - %picture6%
    Set /a Result06 = 0

    if %Test01% GEQ 0 (Set /a Result01 = 1)else (Set /a Result01 = 0)
    if %Test02% GEQ 0 (Set /a Result02 = 1)else (Set /a Result02 = 0)
    if %Test03% GEQ 0 (Set /a Result03 = 1)else (Set /a Result03 = 0)
    if %Test04% GEQ 0 (Set /a Result04 = 1)else (Set /a Result04 = 0)
    if %Test05% GEQ 0 (Set /a Result05 = 1)else (Set /a Result05 = 0)
    if %Test06% GEQ 0 (Set /a Result06 = 1)else (Set /a Result06 = 0)

    Set /a Picture0Final = %Result06% + %Result05% + %Result04% + %Result03% + %Result02% + %Result01%

    If %Picture0Final% EQU 6 (Echo Picture Zero) Else (Echo no)
    GoTo :EOF

    :TestPicture1
    Set /a Test10 = %picture1% - %picture0%
    Set /a Result10 = 0
    Set /a Test12 = %picture1% - %picture2%
    Set /a Result12 = 0
    Set /a Test13 = %picture1% - %picture3%
    Set /a Result13 = 0
    Set /a Test14 = %picture1% - %picture4%
    Set /a Result14 = 0
    Set /a Test15 = %picture1% - %picture5%
    Set /a Result15 = 0
    Set /a Test16 = %picture1% - %picture6%
    Set /a Result16 = 0

    if %Test10% GEQ 0 (Set /a Result10 = 1)else (Set /a Result10 = 0)
    if %Test12% GEQ 0 (Set /a Result12 = 1)else (Set /a Result12 = 0)
    if %Test13% GEQ 0 (Set /a Result13 = 1)else (Set /a Result13 = 0)
    if %Test14% GEQ 0 (Set /a Result14 = 1)else (Set /a Result14 = 0)
    if %Test15% GEQ 0 (Set /a Result15 = 1)else (Set /a Result15 = 0)
    if %Test16% GEQ 0 (Set /a Result16 = 1)else (Set /a Result16 = 0)

    Set /a Picture1Final = %Result16% + %Result15% + %Result14% + %Result13% + %Result12% + %Result10%

    If %Picture1Final% EQU 6 (Echo Picture one) Else (Echo no)
    GoTo :EOF

    :TestPicture2
    Set /a Test20 = %picture2% - %picture0%
    Set /a Result20 = 0
    Set /a Test21 = %picture2% - %picture1%
    Set /a Result21 = 0
    Set /a Test23 = %picture2% - %picture3%
    Set /a Result23 = 0
    Set /a Test24 = %picture2% - %picture4%
    Set /a Result24 = 0
    Set /a Test25 = %picture2% - %picture5%
    Set /a Result25 = 0
    Set /a Test26 = %picture2% - %picture6%
    Set /a Result26 = 0

    if %Test20% GEQ 0 (Set /a Result20 = 1)else (Set /a Result20 = 0)
    if %Test21% GEQ 0 (Set /a Result21 = 1)else (Set /a Result21 = 0)
    if %Test23% GEQ 0 (Set /a Result23 = 1)else (Set /a Result23 = 0)
    if %Test24% GEQ 0 (Set /a Result24 = 1)else (Set /a Result24 = 0)
    if %Test25% GEQ 0 (Set /a Result25 = 1)else (Set /a Result25 = 0)
    if %Test26% GEQ 0 (Set /a Result26 = 1)else (Set /a Result26 = 0)

    Set /a Picture2Final = %Result26% + %Result25% + %Result24% + %Result23% + %Result21% + %Result20%

    If %Picture2Final% EQU 6 (Echo Picture Two) Else (Echo no)
    GoTo :EOF

    :TestPicture3
    Set /a Test30 = %picture3% - %picture0%
    Set /a Result30 = 0
    Set /a Test31 = %picture3% - %picture1%
    Set /a Result11 = 0
    Set /a Test32 = %picture3% - %picture2%
    Set /a Result32 = 0
    Set /a Test34 = %picture3% - %picture4%
    Set /a Result34 = 0
    Set /a Test35 = %picture3% - %picture5%
    Set /a Result35 = 0
    Set /a Test36 = %picture3% - %picture6%
    Set /a Result36 = 0

    if %Test30% GEQ 0 (Set /a Result30 = 1)else (Set /a Result30 = 0)
    if %Test31% GEQ 0 (Set /a Result31 = 1)else (Set /a Result31 = 0)
    if %Test32% GEQ 0 (Set /a Result32 = 1)else (Set /a Result32 = 0)
    if %Test34% GEQ 0 (Set /a Result34 = 1)else (Set /a Result34 = 0)
    if %Test35% GEQ 0 (Set /a Result35 = 1)else (Set /a Result35 = 0)
    if %Test36% GEQ 0 (Set /a Result36 = 1)else (Set /a Result36 = 0)

    Set /a Picture3Final = %Result36% + %Result35% + %Result34% + %Result32% + %Result31% + %Result30%

    If %Picture3Final% EQU 6 (Echo Picture Three) Else (Echo no)
    GoTo :EOF

    :TestPicture4

    Set /a Test40 = %picture4% - %picture0%
    Set /a Result40 = 0
    Set /a Test42 = %picture4% - %picture2%
    Set /a Result42 = 0
    Set /a Test43 = %picture4% - %picture3%
    Set /a Result43 = 0
    Set /a Test41 = %picture4% - %picture1%
    Set /a Result41 = 0
    Set /a Test45 = %picture4% - %picture5%
    Set /a Result45 = 0
    Set /a Test46 = %picture4% - %picture6%
    Set /a Result46 = 0

    if %Test40% GEQ 0 (Set /a Result40 = 1)else (Set /a Result40 = 0)
    if %Test42% GEQ 0 (Set /a Result42 = 1)else (Set /a Result42 = 0)
    if %Test43% GEQ 0 (Set /a Result43 = 1)else (Set /a Result43 = 0)
    if %Test41% GEQ 0 (Set /a Result41 = 1)else (Set /a Result41 = 0)
    if %Test45% GEQ 0 (Set /a Result45 = 1)else (Set /a Result45 = 0)
    if %Test46% GEQ 0 (Set /a Result46 = 1)else (Set /a Result46 = 0)

    Set /a Picture4Final = %Result46% + %Result45% + %Result41% + %Result43% + %Result42% + %Result40%

    If %Picture4Final% GEQ 6 (Echo Picture Four) Else (Echo no)

    GoTo :EOF

    :TestPicture5
    Set /a Test50 = %picture5% - %picture0%
    Set /a Result50 = 0
    Set /a Test51 = %picture5% - %picture1%
    Set /a Result51 = 0
    Set /a Test52 = %picture5% - %picture2%
    Set /a Result52 = 0
    Set /a Test53 = %picture5% - %picture3%
    Set /a Result53 = 0
    Set /a Test54 = %picture5% - %picture5%
    Set /a Result54 = 0
    Set /a Test56 = %picture5% - %picture6%
    Set /a Result56 = 0

    if %Test50% GEQ 0 (Set /a Result50 = 1)else (Set /a Result50 = 0)
    if %Test51% GEQ 0 (Set /a Result51 = 1)else (Set /a Result51 = 0)
    if %Test52% GEQ 0 (Set /a Result52 = 1)else (Set /a Result52 = 0)
    if %Test53% GEQ 0 (Set /a Result53 = 1)else (Set /a Result53 = 0)
    if %Test54% GEQ 0 (Set /a Result54 = 1)else (Set /a Result54 = 0)
    if %Test56% GEQ 0 (Set /a Result56 = 1)else (Set /a Result56 = 0)

    Set /a Picture5Final = %Result56% + %Result54% + %Result53% + %Result52% + %Result51% + %Result50%

    If %Picture5Final% EQU 6 (Echo Picture Five) Else (Echo no)
    GoTo :EOF

    :TestPicture6
    Set /a Test60 = %picture6% - %picture0%
    Set /a Result60 = 0
    Set /a Test61 = %picture6% - %picture1%
    Set /a Result61 = 0
    Set /a Test62 = %picture6% - %picture2%
    Set /a Result62 = 0
    Set /a Test63 = %picture6% - %picture3%
    Set /a Result63 = 0
    Set /a Test64 = %picture6% - %picture6%
    Set /a Result64 = 0
    Set /a Test65 = %picture6% - %picture6%
    Set /a Result65 = 0

    if %Test60% GEQ 0 (Set /a Result60 = 1)else (Set /a Result60 = 0)
    if %Test61% GEQ 0 (Set /a Result61 = 1)else (Set /a Result61 = 0)
    if %Test62% GEQ 0 (Set /a Result62 = 1)else (Set /a Result62 = 0)
    if %Test63% GEQ 0 (Set /a Result63 = 1)else (Set /a Result63 = 0)
    if %Test64% GEQ 0 (Set /a Result64 = 1)else (Set /a Result64 = 0)
    if %Test65% GEQ 0 (Set /a Result65 = 1)else (Set /a Result65 = 0)

    Set /a Picture6Final = %Result65% + %Result64% + %Result63% + %Result62% + %Result61% + %Result60%

    If %Picture6Final% EQU 6 (Echo Picture Six) Else (Echo no)
    GoTo :EOF

If yall know a way to make this better please let me know :D----<-<
*Edit: fixed some 0's to ones ... literally

Body:
you asked how to

find the largest of 6 given variables

There is no need to minus each and compare the result to 0. It isn't even neccessary to compare the variables.

@echo off
====SETLOCAL EnableDelayedExpansion EnableExtensions

set/a"picture0=4,picture1=10,picture2=9,picture3=6,picture4=71,picture5=6,picture6=5,MAX=0"
FOR /L %%# in (0 1 6) do if !picture%%#! GTR !max! set/a"max=!picture%%#!,max_var=%%#"
echo MAX is picture%max_var%=%max%

Limitations:

If %picture3% == %picture4% == 6, %max% will be picture3.

Works for 32-bits integers only. See Windows batch file IF failure - How can 30000000000000 equal 40000000000?

In this case, because the variables are in a "list", I used a FOR /L loop . But in case it's not, use FOR.


来源: stackexchange

问:
how to run single test case from jenkins
I have 10 test cases in testng suite,i need to execute single or individual test cases from jenkinks,can any one help me out how to execute single test case from jenkins,i tried maven surfire commands mvn -Dtest=TestCircle test include test command into golas and executed but its not working,please refer data and correct me how to set goals in jenkins for execute single test case.
"mvn clean compile install  -DPICK_CONFIGURATION_FROM="JENKINS" -DEXECUTION_MODE="Remote" -Dtest=TestCircle#EAConsoleLandingPageTest test -DPLATFORM="WEB"  -DOPERATING_SYSTEM="WINDOWS" -DBROWSER="chrome" -DCOMPUTERNAME="Test" -DTEST_ENVIRONMENT="RUNFC" -DPLAN_ID="" -DTEST_TYPE="Smoke" -DGRID_URL="http://localhost:4444/wd/hub""

Below is the sample test suite:
classes>

```<code>        <class
            name="com.ea.automation.tests.EAConsoleLandingPageTest">
            <methods>
                <include name="clickOnGetStartedBtn" />
                <include name="selectProjectFromLandingPage" />
                <include name="clickOnEAConsoleIcon" />
                <include name="verifyRequestProjectAccess" />
                <include name="verifyProjectAccess" />
                <include name="verifyHomePageRedierecting" />
            </methods>
        </class>
        <class
            name="com.ea.automation.tests.EAConsoleSelfServiceTest">
            <methods>
                <include name="clickOnCreateNewproject" />
                <include name="verifyProjectUserAcess" />
                <include name="switchProjects" />
                <include name="clickOnProjectSettings" />
            </methods>
        </class>
        <class
            name="com.ea.automation.tests.EAConsoleNotificationAppTest">
            <methods>
                <include name="selectProject" />
                <include name="clickOnNotification" />
                <include name="checkAllWdgetNotifications" />
            </methods>
        </class>
        <class
            name="com.ea.automation.tests.EAConsoleSupportAppTest">
            <methods>
                <include name="clickOnSupportApp" />
                <include name="checkCreateTicket" />
                <include name="clickOnCloseErrorMessageModel" />
                <include name="clickOnSupportFromApp" />
                <include name="clickOnSupportEmail" />
            </methods>
        </class>
        <class
            name="com.ea.automation.tests.EAConsoleSDKDownloadsAppTest">
            <methods>
                <include name="selectProject" />
                <include name="clickOnSDKDownloads" />
            </methods>
        </class>
</code>```

答:
The approach I am suggesting is not preferable. Because the sole purpose of running Jenkins is to run a suite of test cases and not individual ones. But you could implement your idea in the following way.

Add three string parameters to the Jenkins job. One parameter points to the testng xml file name, second parameter points to the class name, and the third parameter points to the test name.

Create and have another testng.xml file in your project repo. Rename this file as small.xml

So the first Build parameter should be small.xml

Jenkins has the capability to execute shell script before the maven build starts.

So we are going to fetch the arguments that we used as Jenkins Build parameters inside the shell script to modify the small.xml file and modify the pom.xml file to point to the small.xml.

sed command in a shell script will help to replace the existing text in pom.xml and small.xml file. You could search this on the internet.

I had implemented this approach in one of the projects that I worked on for picking different suite files based on the Jenkins build parameters. This approach works. So during runtime, based on the Jenkins Build Parameters you pass, the corresponding tests will be run by Jenkins.

ContentLicense: CC BY-SA 4.0

Body:
I have 10 test cases in testng suite,i need to execute single or individual test cases from jenkinks,can any one help me out how to execute single test case from jenkins,i tried maven surfire commands mvn -Dtest=TestCircle test include test command into golas and executed but its not working,please refer data and correct me how to set goals in jenkins for execute single test case.
"mvn clean compile install  -DPICK_CONFIGURATION_FROM="JENKINS" -DEXECUTION_MODE="Remote" -Dtest=TestCircle#EAConsoleLandingPageTest test -DPLATFORM="WEB"  -DOPERATING_SYSTEM="WINDOWS" -DBROWSER="chrome" -DCOMPUTERNAME="Test" -DTEST_ENVIRONMENT="RUNFC" -DPLAN_ID="" -DTEST_TYPE="Smoke" -DGRID_URL="http://localhost:4444/wd/hub""

Below is the sample test suite:
classes>

        <class
            name="com.ea.automation.tests.EAConsoleLandingPageTest">
            <methods>
                <include name="clickOnGetStartedBtn" />
                <include name="selectProjectFromLandingPage" />
                <include name="clickOnEAConsoleIcon" />
                <include name="verifyRequestProjectAccess" />
                <include name="verifyProjectAccess" />
                <include name="verifyHomePageRedierecting" />
            </methods>
        </class>
        <class
            name="com.ea.automation.tests.EAConsoleSelfServiceTest">
            <methods>
                <include name="clickOnCreateNewproject" />
                <include name="verifyProjectUserAcess" />
                <include name="switchProjects" />
                <include name="clickOnProjectSettings" />
            </methods>
        </class>
        <class
            name="com.ea.automation.tests.EAConsoleNotificationAppTest">
            <methods>
                <include name="selectProject" />
                <include name="clickOnNotification" />
                <include name="checkAllWdgetNotifications" />
            </methods>
        </class>
        <class
            name="com.ea.automation.tests.EAConsoleSupportAppTest">
            <methods>
                <include name="clickOnSupportApp" />
                <include name="checkCreateTicket" />
                <include name="clickOnCloseErrorMessageModel" />
                <include name="clickOnSupportFromApp" />
                <include name="clickOnSupportEmail" />
            </methods>
        </class>
        <class
            name="com.ea.automation.tests.EAConsoleSDKDownloadsAppTest">
            <methods>
                <include name="selectProject" />
                <include name="clickOnSDKDownloads" />
            </methods>
        </class>


问:
Should I build the object in the constructor?
I have a class called book consists off the book name and List of chapters. I read the information about the chapters ( such as the chapters name, chapter number ... etc) from some txt file on the hard desktop.

The book object itself is meaningless without loading the chapters.
For best practices, should I write a build method and I build my object like the below ?

```<code>Book newBook = new Book(bookName).build();
</code>```

Where build has the logic of loading the file form hard disk and filling the chapters list, or I should just make this build method private and create an object like the below.

```<code>Book newBook = new Book(bookName);
</code>```

and inside the constructor of the book I should call the private method called build ?

答:
Since the book object is incomplete or stale without the details of chapter and chapter numbers. The process of object creation cannot be considered as complete without filling the chapter details.

But doing a heavy operation of reading file and creating chapter in the book object is not needed. Instead, create the chapter objects before creating the book objects.  And dependency injection can be used while creating the book object.

Body:
I have a class called book consists off the book name and List of chapters. I read the information about the chapters ( such as the chapters name, chapter number ... etc) from some txt file on the hard desktop.

The book object itself is meaningless without loading the chapters.
For best practices, should I write a build method and I build my object like the below ?

Book newBook = new Book(bookName).build();

Where build has the logic of loading the file form hard disk and filling the chapters list, or I should just make this build method private and create an object like the below.

Book newBook = new Book(bookName);

and inside the constructor of the book I should call the private method called build ?


问:
SwiftUI - Only one object property true in Array
I'm trying to model my data with the Model, View, Viewmodel framework.

In my project, i have a Model called Category which is a class.
Each Category have and id, a name and a var isActive of type bool.

I'm currently displaying a Hstack ScrollView with all my categories as buttons.
Click here to visually see my view.

I added a OnTapGesture on each category button to change the size of the button when tapped.
My problem is that i can have more than one category selected at the same time.

I'm wondering what's the best way to structure my data so that i can only select one category.

Should i delete the isActive variable on my Category Model ?
What should i try next ?

Category Model -

```<code>Category Model
struct Category: Identifiable {

    var id = UUID().uuidString
    var category: categories
    var isActive: Bool

}

/// Represent all possible categories cases
enum categories: String, CaseIterable {
    case love = "❤"
    case family = ""
    case urgent = ""
    case sex = ""
    case funny = ""
    case school = ""
    case sport = ""
}

#if DEBUG
let categoryTest = [
    Category(category: .love, isActive: false),
    Category(category: .family, isActive: false),
    Category(category: .urgent, isActive: false),
    Category(category: .sex, isActive: false),
    Category(category: .funny, isActive: false),
    Category(category: .school, isActive: false),
    Category(category: .sport, isActive: false)
]
#endif
</code>```

CategoriesView -

```<code>//Categories View - Looping all categories & CategoryView - The way i display each category and add the Tap Gesture
import SwiftUI
import Foundation
import Combine

struct CategoriesView: View {

    @ObservedObject var categoriesVM = CategoriesViewModel()

    var body: some View {
        VStack(alignment: .leading) {

            Text("Catégories")
                .font(.title).bold()
                .offset(y: 20)

            ScrollView(.horizontal, showsIndicators: false) {
                HStack {
                    ForEach(categoriesVM.categoryViewModel) { categoryVM in
                        CategoryView(categoryVM: categoryVM)
                    }

                }
            }
        }
        .padding(.leading, 15)
    }
}

struct CategoriesView_Previews: PreviewProvider {
    static var previews: some View {
        CategoriesView()
    }
}

struct CategoryView: View {
    @ObservedObject var categoryVM: CategoryViewModel

    var onComit: (Category) -> (Void) = { _ in }

    var body: some View {
        HStack {

            Text(categoryVM.category.category.rawValue)
                .font(.system(size: self.categoryVM.category.isActive ? 26 : 22, weight: .bold))
            .frame(
                width: self.categoryVM.category.isActive ? 80 : 60,
                height: self.categoryVM.category.isActive ? 80 : 60
            )
            .background(Color.white)
            .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous))
            .shadow(color: Color.black.opacity(0.1), radius: 10, x: 10, y: 10)
            .onTapGesture {
                self.categoryVM.category.isActive.toggle()
                print("Tapped, state: \(self.categoryVM.category.isActive)")
            }

        }
        .frame(height: 130)
    }
}
</code>```

Category View Model -

```<code>import SwiftUI
import Foundation
import Combine

class CategoryViewModel: ObservableObject, Identifiable {

    @Published var category: Category
    var id: String = ""
    private var cancellables = Set<AnyCancellable>()
//    @Published var categoryIcon = ""

    init(category: Category) {
        self.category = category

        $category // (7)
        .map { $0.id }
        .assign(to: \.id, on: self)
        .store(in: &cancellables)

}

}
</code>```

Categories View Model -

```<code>import SwiftUI
import Foundation
import Combine

class CategoriesViewModel: ObservableObject, Identifiable {

    @Published var categoryViewModel = [CategoryViewModel]()

    private var cancellables =  Set<AnyCancellable>()

    init() {
        self.categoryViewModel = categoryTest.map { category in
            CategoryViewModel(category: category)
        }
    }
}
</code>```

答:
So my first thought is remove isActive from Category and create a @State var currentCategory: UUID in CategoriesView:

```<code>struct CategoriesView: View {

    @ObservedObject var categoriesVM = CategoriesViewModel()
    @State var currentCategory: UUID = UUID()

    var body: some View {
        VStack(alignment: .leading) {

            Text("Catégories")
                .font(.title).bold()
                .offset(y: 20)

            ScrollView(.horizontal, showsIndicators: false) {
                HStack {
                    ForEach(categoriesVM.categoryViewModel) { categoryVM in
                        CategoryView(categoryVM: categoryVM, currentCategory: $currentCategory)
                    }

                }
            }
        }
        .padding(.leading, 15)
    }
}
</code>```

and then check and assign currentCategory in your CategoryView:

```<code>struct CategoryView: View {
    @ObservedObject var categoryVM: CategoryViewModel
    @Binding var currentCategory

    var onComit: (Category) -> (Void) = { _ in }

    var body: some View {
        HStack {

            Text(categoryVM.category.category.rawValue)
                .font(.system(size: isCurrentCategory() ? 26 : 22, weight: .bold))
            .frame(
                width: isCurrentCategory() ? 80 : 60,
                height: isCurrentCategory() ? 80 : 60
            )
            .background(Color.white)
            .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous))
            .shadow(color: Color.black.opacity(0.1), radius: 10, x: 10, y: 10)
            .onTapGesture {
                self.currentCategory = self.categoryVM.category.id
            }

        }
        .frame(height: 130)
    }

    private func isCurrentCategory() -> Bool {
      return categoryVM.category.id == currentCategory
    }
}
</code>```

I didnt check if my code compiles or not, but this way you cant have more than one active category.

Body:
I'm trying to model my data with the Model, View, Viewmodel framework.

In my project, i have a Model called Category which is a class.
Each Category have and id, a name and a var isActive of type bool.

I'm currently displaying a Hstack ScrollView with all my categories as buttons.
Click here to visually see my view.

I added a OnTapGesture on each category button to change the size of the button when tapped.
My problem is that i can have more than one category selected at the same time.

I'm wondering what's the best way to structure my data so that i can only select one category.

Should i delete the isActive variable on my Category Model ?
What should i try next ?

Category Model -

Category Model
struct Category: Identifiable {

    var id = UUID().uuidString
    var category: categories
    var isActive: Bool

}

/// Represent all possible categories cases
enum categories: String, CaseIterable {
    case love = "❤"
    case family = ""
    case urgent = ""
    case sex = ""
    case funny = ""
    case school = ""
    case sport = ""
}

#if DEBUG
let categoryTest = [
    Category(category: .love, isActive: false),
    Category(category: .family, isActive: false),
    Category(category: .urgent, isActive: false),
    Category(category: .sex, isActive: false),
    Category(category: .funny, isActive: false),
    Category(category: .school, isActive: false),
    Category(category: .sport, isActive: false)
]
#endif

CategoriesView -

//Categories View - Looping all categories & CategoryView - The way i display each category and add the Tap Gesture
import SwiftUI
import Foundation
import Combine

struct CategoriesView: View {

    @ObservedObject var categoriesVM = CategoriesViewModel()

    var body: some View {
        VStack(alignment: .leading) {

            Text("Catégories")
                .font(.title).bold()
                .offset(y: 20)

            ScrollView(.horizontal, showsIndicators: false) {
                HStack {
                    ForEach(categoriesVM.categoryViewModel) { categoryVM in
                        CategoryView(categoryVM: categoryVM)
                    }

                }
            }
        }
        .padding(.leading, 15)
    }
}

struct CategoriesView_Previews: PreviewProvider {
    static var previews: some View {
        CategoriesView()
    }
}

struct CategoryView: View {
    @ObservedObject var categoryVM: CategoryViewModel

    var onComit: (Category) -> (Void) = { _ in }

    var body: some View {
        HStack {

            Text(categoryVM.category.category.rawValue)
                .font(.system(size: self.categoryVM.category.isActive ? 26 : 22, weight: .bold))
            .frame(
                width: self.categoryVM.category.isActive ? 80 : 60,
                height: self.categoryVM.category.isActive ? 80 : 60
            )
            .background(Color.white)
            .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous))
            .shadow(color: Color.black.opacity(0.1), radius: 10, x: 10, y: 10)
            .onTapGesture {
                self.categoryVM.category.isActive.toggle()
                print("Tapped, state: \(self.categoryVM.category.isActive)")
            }

        }
        .frame(height: 130)
    }
}

Category View Model -

import SwiftUI
import Foundation
import Combine

class CategoryViewModel: ObservableObject, Identifiable {

    @Published var category: Category
    var id: String = ""
    private var cancellables = Set<AnyCancellable>()
//    @Published var categoryIcon = ""

    init(category: Category) {
        self.category = category

        $category // (7)
        .map { $0.id }
        .assign(to: \.id, on: self)
        .store(in: &cancellables)

}

}

Categories View Model -

import SwiftUI
import Foundation
import Combine

class CategoriesViewModel: ObservableObject, Identifiable {

    @Published var categoryViewModel = [CategoryViewModel]()

    private var cancellables =  Set<AnyCancellable>()

    init() {
        self.categoryViewModel = categoryTest.map { category in
            CategoryViewModel(category: category)
        }
    }
}

Body:
So my first thought is remove isActive from Category and create a @State var currentCategory: UUID in CategoriesView:

struct CategoriesView: View {

    @ObservedObject var categoriesVM = CategoriesViewModel()
    @State var currentCategory: UUID = UUID()

    var body: some View {
        VStack(alignment: .leading) {

            Text("Catégories")
                .font(.title).bold()
                .offset(y: 20)

            ScrollView(.horizontal, showsIndicators: false) {
                HStack {
                    ForEach(categoriesVM.categoryViewModel) { categoryVM in
                        CategoryView(categoryVM: categoryVM, currentCategory: $currentCategory)
                    }

                }
            }
        }
        .padding(.leading, 15)
    }
}

and then check and assign currentCategory in your CategoryView:

struct CategoryView: View {
    @ObservedObject var categoryVM: CategoryViewModel
    @Binding var currentCategory

    var onComit: (Category) -> (Void) = { _ in }

    var body: some View {
        HStack {

            Text(categoryVM.category.category.rawValue)
                .font(.system(size: isCurrentCategory() ? 26 : 22, weight: .bold))
            .frame(
                width: isCurrentCategory() ? 80 : 60,
                height: isCurrentCategory() ? 80 : 60
            )
            .background(Color.white)
            .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous))
            .shadow(color: Color.black.opacity(0.1), radius: 10, x: 10, y: 10)
            .onTapGesture {
                self.currentCategory = self.categoryVM.category.id
            }

        }
        .frame(height: 130)
    }

    private func isCurrentCategory() -> Bool {
      return categoryVM.category.id == currentCategory
    }
}

I didnt check if my code compiles or not, but this way you cant have more than one active category.


问:
Cannot Resolve Symbol: FusedLocationProviderClient. Google play services version used 11.0.1

Cannot Resolve Symbol: FusedLocationProviderClient.

Google play services version used 11.0.1.

code : while declaration

```<code>private FusedLocationProviderClient mfusedLocationProviderclient;
</code>```

答:
In build.gradle (Module: app) add:

```<code>dependencies {
    ...
    implementation 'com.google.android.gms:play-services-location:17.0.0'
   ...
}
</code>```

Don't forget to sync the build.gradle (on the up right corner of the build.gradle, you will have a notification to sync the changes, click it).

ContentLicense: CC BY-SA 3.0

Body:
Cannot Resolve Symbol: FusedLocationProviderClient.

Google play services version used 11.0.1.

code : while declaration

private FusedLocationProviderClient mfusedLocationProviderclient;

Body:
In build.gradle (Module: app) add:

dependencies {
    ...
    implementation 'com.google.android.gms:play-services-location:17.0.0'
   ...
}

Don't forget to sync the build.gradle (on the up right corner of the build.gradle, you will have a notification to sync the changes, click it).


问:
a zend framework routing question
i want to route my url /resolution/index/res/1024x768 to /resolution/1024x768
the routing code in application.ini is:

```<code>resources.router.routes.resolution.route = '/resolution/:res/'
resources.router.routes.resolution.type = "Zend_Controller_Router_Route"
resources.router.routes.resolution.defaults.module = default
resources.router.routes.resolution.defaults.controller = resolution
resources.router.routes.resolution.defaults.action = index
resources.router.routes.resolution.defaults.res=
</code>```

the problem is that its working in my local computer but not in my host.
this url mysite.com/resolution/index/res/1024x768 works but /resolution/1024x768 doesnt. is there something more i need to do in production environment ?

i get the follow request parameters when accessing /resolution/1024x768:

```<code>Request Parameters:
array (
  'controller' => 'resolution',
  'action' => '1024x768',
  'module' => 'default',
)
</code>```

Update: as weird as it may sound, the first line in above routing code needed to be placed inside double quotes, like this:

```<code>resources.router.routes.resolution.route = "/resolution/:res/"
</code>```

答:
You can try:

```<code>resources.router.routes.resolution.type = "Zend_Controller_Router_Route_Regex"
resources.router.routes.resolution.route = '/resolution/(.*)'
resources.router.routes.resolution.defaults.module = default
resources.router.routes.resolution.defaults.controller = resolution
resources.router.routes.resolution.defaults.action = index
resources.router.routes.resolution.map.1 = "res"
</code>```

[Updated]

Title: a zend framework routing question

Body:
i want to route my url /resolution/index/res/1024x768 to /resolution/1024x768
the routing code in application.ini is:

resources.router.routes.resolution.route = '/resolution/:res/'
resources.router.routes.resolution.type = "Zend_Controller_Router_Route"
resources.router.routes.resolution.defaults.module = default
resources.router.routes.resolution.defaults.controller = resolution
resources.router.routes.resolution.defaults.action = index
resources.router.routes.resolution.defaults.res=

the problem is that its working in my local computer but not in my host.
this url mysite.com/resolution/index/res/1024x768 works but /resolution/1024x768 doesnt. is there something more i need to do in production environment ?

i get the follow request parameters when accessing /resolution/1024x768:

Request Parameters:
array (
  'controller' => 'resolution',
  'action' => '1024x768',
  'module' => 'default',
)

Update: as weird as it may sound, the first line in above routing code needed to be placed inside double quotes, like this:

resources.router.routes.resolution.route = "/resolution/:res/"

Body:
You can try:

resources.router.routes.resolution.type = "Zend_Controller_Router_Route_Regex"
resources.router.routes.resolution.route = '/resolution/(.*)'
resources.router.routes.resolution.defaults.module = default
resources.router.routes.resolution.defaults.controller = resolution
resources.router.routes.resolution.defaults.action = index
resources.router.routes.resolution.map.1 = "res"

[Updated]


问:
Spring Boot without the web server
I have a simple Spring Boot application that gets messages from a JMS queue and saves some data to a log file, but does not need a web server. Is there any way of starting Spring Boot without the web server?</p>

答:
Similar to @nayun oh answer above, but for older versions of Spring, use this code:</p>

```<code>SpringApplication application = new SpringApplication(DemoApplication.class);
application.setApplicationContextClass(AnnotationConfigApplicationContext.class);
application.run(args);
</code>```

Title: Spring Boot without the web server

Body:
Similar to @nayun oh answer above, but for older versions of Spring, use this code:

SpringApplication application = new SpringApplication(DemoApplication.class);
application.setApplicationContextClass(AnnotationConfigApplicationContext.class);
application.run(args);


问:
Difference between distm function or the distVincentyEllipsoid in R
Could you fully explain the big difference in using the distm function or the distVincentyEllipsoid function to calculate the distance of geodesic coordinates in R?

I noticed that using distm for this calculation, it takes much longer. Could you please explain to me beyond the difference, why does this happen?

Thank you!

答:
Following on from your previous question here: Distance calculation optimization in R

The speed relates to the level of computation required to produce the returned object, not necessarily the difference between the computation of distances (I am not sure what great circle computation the distm() function uses as it's default). Indeed the geosphere:: documentation here: https://cran.r-project.org/web/packages/geosphere/geosphere.pdf suggests that distVincentyEllipsoid() calculation is "very accurate" but "computationally more intensive" than other great circle methods while this would make you suspect a slower computation, it is because of the way I have structured the code in my answer to return a vector of distances between each row (not a matrix of distances between each and every point).

Conversely, your distm() calculation in your original code returns a matrix of multiple vectors between each and every point. For your problem, this is not necessary so long as the data is ordered, that is why I have done so. Additionally, the use of hierarchical clustering to cluster the points based on these distances into 3 (your defined number) clusters is also not necessary as we can use the percentile of distances between each point values to do the same. Again the speed benefit relates to computing the clusters on a single vector rather than a matrix.

Please note, I am a data analyst with a background in accounting/finance and not a GIS specialist by any means. That being said my use of the distVincentyEllipsoid() function comes from my general understanding that this returns a pretty accurate estimation of great circle distances as a vector (as a opposed to a matrix). Moreover, having used this in the past to optimise logistics operations for pricing purposes, I can attest to the fact these computations have been tested in the market and found to be sound.


问:
how do I remove question mark(?) from a data set in R
Hello everyone I am analysing UCI adult census data. The data has question marks (?) for every missing value.

I want to replace all the question marks with NA.

i tried:

```<code>library(XML)
census<-read.csv("https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data",header=F,na.strings="?")
names(census)<-c("Age","Workclass","Fnlwght","Education","EducationNum","MaritalStatus","Occupation"
  ,"Relationship" , "Race","Gender","CapitalGain","CapitalLoss","HoursPerWeek","NativeCountry","Salary"  )

table(census$Workclass)

                ?       Federal-gov         Local-gov      Never-worked           Private      Self-emp-inc
             1836               960              2093                 7             22696              1116
 Self-emp-not-inc         State-gov       Without-pay
             2541              1298                14

x

<-ifelse(census$Workclass=="?",NA,census$Workclass)
 table(x)
x
    1     2     3     4     5     6     7     8     9
 1836   960  2093     7 22696  1116  2541  1298    14
</code>```

but it did not work.

Please help.

答:
For whatever reason, when I import this dataset into R, the question marks are read in as integers.

Here's what I did to code all of the question marks to N/A's. I'm sure there are better ways of doing this but my R skills aren't the greatest and this worked for me.

col_names:

```<code>names <- list(
    'age','workclass','fnlwgt',
    'education','education-num',
    'marital-status','occupation',
    'relationship','race','sex',
    'capital-gain','capital-loss',
    'hours-per-week','native-country', 'salary'
)
</code>```

Code:

```<code># Save csv as variable adult
adult <- read.csv("~/.../adult.data", col.names = names)

for(i in 1:length(adult)) {
    matches <- grepl("\\?", adult[ ,i])
    for(j in 1:length(matches)) {
        ifelse(matches[j] == TRUE, adult[j,i] <- "NA", matches[j])
    }
}
</code>```

Body:
Hello everyone I am analysing UCI adult census data. The data has question marks (?) for every missing value.

I want to replace all the question marks with NA.

i tried:

library(XML)
census<-read.csv("https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data",header=F,na.strings="?")
names(census)<-c("Age","Workclass","Fnlwght","Education","EducationNum","MaritalStatus","Occupation"
  ,"Relationship" , "Race","Gender","CapitalGain","CapitalLoss","HoursPerWeek","NativeCountry","Salary"  )

table(census$Workclass)

                ?       Federal-gov         Local-gov      Never-worked           Private      Self-emp-inc
             1836               960              2093                 7             22696              1116
 Self-emp-not-inc         State-gov       Without-pay
             2541              1298                14

x

<-ifelse(census$Workclass=="?",NA,census$Workclass)
 table(x)
x
    1     2     3     4     5     6     7     8     9
 1836   960  2093     7 22696  1116  2541  1298    14

but it did not work.

Please help.

Body:
For whatever reason, when I import this dataset into R, the question marks are read in as integers.

Here's what I did to code all of the question marks to N/A's. I'm sure there are better ways of doing this but my R skills aren't the greatest and this worked for me.

col_names:

names <- list(
    'age','workclass','fnlwgt',
    'education','education-num',
    'marital-status','occupation',
    'relationship','race','sex',
    'capital-gain','capital-loss',
    'hours-per-week','native-country', 'salary'
)

Code:

# Save csv as variable adult
adult <- read.csv("~/.../adult.data", col.names = names)

for(i in 1:length(adult)) {
    matches <- grepl("\\?", adult[ ,i])
    for(j in 1:length(matches)) {
        ifelse(matches[j] == TRUE, adult[j,i] <- "NA", matches[j])
    }
}


问:
Using jquery, extract each group of adjacent siblings, matching selector, from a larger group of siblings
I have the following markup:

```<code><div id="parent">
    <div class="special child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="special child"></div>
    <div class="special child"></div>
    <div class="special child"></div>
    <div class="child"></div>
    <div class="child"></div>
</div>
</code>```

What I need to do is extract 2 sub collections of div.special (for the 2 groups of adjacent siblings), then wrap each group with another parent, ending up with:

```<code><div id="parent">
    <div class="special_parent">
        <div class="special child"></div>
    </div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="special_parent">
        <div class="special child"></div>
        <div class="special child"></div>
        <div class="special child"></div>
    </div>
    <div class="child"></div>
    <div class="child"></div>
</div>
</code>```

I could begin with iterating through the sibling elements and doing some heavy lifting, but I feel convinced there should be a more elegant approach.

答:
Using each() and nextUntil()

$('.special').each(function() {
  if ($(this).parent().hasClass('special_parent')) return
  $(this)
    .nextUntil(':not(.special)')
    .add(this)
    .wrapAll('
')
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.special_parent {
  color: red;
}</code>```

1

2

3

4

5

6

7

8

9

10

11

```

Body:
I have the following markup:

What I need to do is extract 2 sub collections of div.special (for the 2 groups of adjacent siblings), then wrap each group with another parent, ending up with:

I could begin with iterating through the sibling elements and doing some heavy lifting, but I feel convinced there should be a more elegant approach.

Body:
Using each() and nextUntil()

$('.special').each(function() {
  if ($(this).parent().hasClass('special_parent')) return
  $(this)
    .nextUntil(':not(.special)')
    .add(this)
    .wrapAll('<div class="special_parent">')
})

.special_parent {
  color: red;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="parent">
  <div class="special child">1</div>
  <div class="child">2</div>
  <div class="child">3</div>
  <div class="child">4</div>
  <div class="special child">5</div>
  <div class="special child">6</div>
  <div class="special child">7</div>
  <div class="child">8</div>
  <div class="child">9</div>
  <div class="special child">10</div>
  <div class="special child">11</div>
</div>


问:
PIL.Image to cv2: Expected Ptr<cv::UMat> for argument 'src'
I am using the pyautogui library to take a screenshot, which gets stored as PIL.Image.Image.
When I try to use cv2's cvtColor() function to convert it, I get a TypeError:

```<code>TypeError: Expected Ptr<cv::UMat> for argument 'src'
</code>```

Here is my code:

```<code>img = pyautogui.screenshot(0, 0, 500, 500)
print(type(img))    #<class 'PIL.Image.Image'>
img_rgb = numpy.array(img)
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
</code>```

What is my mistake here, and how could I convert the image as desired?

答:
Never used the library, but from the error it gave out

try

```<code>img_gray = cv2.cvtColor(np.float32(img_rgb), cv2.COLOR_BGR2GRAY)
</code>```

EDIT :

This is my test code which works fine

```<code>import pyautogui
import numpy as np
import cv2

img = pyautogui.screenshot(region=(0,0, 500, 500))
    #tested on impossible resolution as well, but the library still handles it.
print(type(img))  #<class 'PIL.Image.Image'>
img_rgb = np.array(img) #<class 'numpy.ndarray'>
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
cv2.imshow("img",img_gray)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

Body:
I am using the pyautogui library to take a screenshot, which gets stored as PIL.Image.Image.
When I try to use cv2's cvtColor() function to convert it, I get a TypeError:

TypeError: Expected Ptr<cv::UMat> for argument 'src'

Here is my code:

img = pyautogui.screenshot(0, 0, 500, 500)
print(type(img))    #<class 'PIL.Image.Image'>
img_rgb = numpy.array(img)
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)

What is my mistake here, and how could I convert the image as desired?

Body:
Never used the library, but from the error it gave out

try

img_gray = cv2.cvtColor(np.float32(img_rgb), cv2.COLOR_BGR2GRAY)

EDIT :

This is my test code which works fine

import pyautogui
import numpy as np
import cv2

img = pyautogui.screenshot(region=(0,0, 500, 500))
    #tested on impossible resolution as well, but the library still handles it.
print(type(img))  #<class 'PIL.Image.Image'>
img_rgb = np.array(img) #<class 'numpy.ndarray'>
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
cv2.imshow("img",img_gray)
cv2.waitKey(0)
cv2.destroyAllWindows()


问:
How to return the zoom when pinch to zoom to 100% in iOS
When the user do a pinch to zoom out in iOS, we would like to return it to the normal view( 100% )

Because of our project, we can't use touchstart or touchmove

We have this code below but doesnt work.

document.addEventListener('touchend', function(event) {
  if (window.visualViewport.scale != 1) {
    document.body.style.transform = 'scale(1)';
  }
}, {passive: false});```
</div>
</div>
</p>

<p>We also tried, </p>

```document.body.style.zoom = 1;
```

<p>Is there anyway we can force to return to zoom 100% when pinch to zoom? Any help would be appreciated.</p>

<p><strong>Full HTML code:</strong></p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">

  <script>
    document.addEventListener('touchend', function(event) {
      if (window.visualViewport.scale != 1) {
        document.body.style.transform = 'scale(1)';

        //document.body.style.zoom = 1;
        //window.visualViewport.scale = 1;
      }
    }, {
      passive: false
    });
  </script>

  <style>
    html,
    body {
      width: 100%;
      height: 100%;
      background-color: green;
      overflow: hidden;
    }
  </style>
</head>

<body>

</body>

</html></code>```

答:
If you don't want users to be able to zoom at all (rather than resetting the zoom every time they try to) you only need to have user-scalable=no" in your viewport meta tag.

Try:

```<code><meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
</code>```

Or:

```<code><meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0">
</code>```

Or:

```<code>document.documentElement.addEventListener('touchmove', function (event) {
    event.preventDefault();
}, false);
</code>```

Body:
When the user do a pinch to zoom out in iOS, we would like to return it to the normal view( 100% )

Because of our project, we can't use touchstart or touchmove

We have this code below but doesnt work.

document.addEventListener('touchend', function(event) {
  if (window.visualViewport.scale != 1) {
    document.body.style.transform = 'scale(1)';
  }
}, {passive: false});

We also tried,

document.body.style.zoom = 1;

Is there anyway we can force to return to zoom 100% when pinch to zoom? Any help would be appreciated.

Full HTML code:

<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">

Body:
If you don't want users to be able to zoom at all (rather than resetting the zoom every time they try to) you only need to have user-scalable=no" in your viewport meta tag.

Try:

<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">

Or:

<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0">

Or:

document.documentElement.addEventListener('touchmove', function (event) {
    event.preventDefault();
}, false);


问:
Do we need to sign .apk file everytime we update it on playstore?
I have already signed my app the first time with this command

```<code>keytool -genkey -v -keystore android/app/key.jks -keyalg RSA -keysize 2048 -validity 10000 -alias key
</code>```

So I was wondering if I have to do it again every time I update my app because whenever I try to repeat this command I'm getting error saying the key already exist

Edit : what's the difference between theses two commands

```<code>keytool -genkey -v -keystore debug.keystore -storepass android -alias androiddebugkey -keypass android -keyalg RSA -keysize 2048 -validity 10000
</code>```

答: Generating key is one time process, After that you have to sign your apk every time with same generated key. You can do this in android studio easily. Refer the apk signing process at developer site APK signing</p>

Body:
I have already signed my app the first time with this command

keytool -genkey -v -keystore android/app/key.jks -keyalg RSA -keysize 2048 -validity 10000 -alias key

So I was wondering if I have to do it again every time I update my app because whenever I try to repeat this command I'm getting error saying the key already exist

Edit : what's the difference between theses two commands

keytool -genkey -v -keystore debug.keystore -storepass android -alias androiddebugkey -keypass android -keyalg RSA -keysize 2048 -validity 10000


问:
r dplyr::case_when Error: must be a character vector, not a double vector
I am trying to use dplyr::case_when within dplyr::mutate to replace some values:

```<code>data<-data%>%
  mutate(floor = case_when(
    floor_id == 2 ~ "ground_floor",
    floor_id == 3 ~ "mezzanine",
    floor_id == 1 ~ "basement",
    floor_id == 30 ~ "over_10",
    floor==1 ~ 1,
    floor==2 ~ 2,
    floor==3 ~ 3,
    floor==4 ~ 4,
    floor==5 ~ 5,
    floor==6 ~ 6,
    floor==7 ~ 7,
    floor==8 ~ 8,
    floor==9 ~ 9,
    floor==10 ~ 10,
    TRUE ~ as.character(floor)))
</code>```

I have an error

```<code>Error: must be a character vector, not a double vector
</code>```

I have 2 questions:
1) Does anyone know how to change the code to fix this error?
2) If no cases match, NA is returned that is why I add all these lines like floor==10 ~ 10. Is there any way to make the code less redundant?

答:
case_when is type-strict meaning you need to return values of same type. For first few cases you are returning values like "ground-floor", "mezzanine" etc whereas later you are returning 1, 2 which are numeric hence you get that error. If you change all your return values to character values like "1", "2" etc then it will work.

Since, you are just returning the floor values you can reduce the code by:

```<code>library(dplyr)
data<- data%>%
        mutate(floor = case_when(
               floor_id == 2 ~ "ground_floor",
               floor_id == 3 ~ "mezzanine",
               floor_id == 1 ~ "basement",
               floor_id == 30 ~ "over_10",
               TRUE ~ as.character(floor)))
</code>```

Body:
I am trying to use dplyr::case_when within dplyr::mutate to replace some values:

data<-data%>%
  mutate(floor = case_when(
    floor_id == 2 ~ "ground_floor",
    floor_id == 3 ~ "mezzanine",
    floor_id == 1 ~ "basement",
    floor_id == 30 ~ "over_10",
    floor==1 ~ 1,
    floor==2 ~ 2,
    floor==3 ~ 3,
    floor==4 ~ 4,
    floor==5 ~ 5,
    floor==6 ~ 6,
    floor==7 ~ 7,
    floor==8 ~ 8,
    floor==9 ~ 9,
    floor==10 ~ 10,
    TRUE ~ as.character(floor)))

I have an error

Error: must be a character vector, not a double vector

I have 2 questions:
1) Does anyone know how to change the code to fix this error?
2) If no cases match, NA is returned that is why I add all these lines like floor==10 ~ 10. Is there any way to make the code less redundant?

Body:
case_when is type-strict meaning you need to return values of same type. For first few cases you are returning values like "ground-floor", "mezzanine" etc whereas later you are returning 1, 2 which are numeric hence you get that error. If you change all your return values to character values like "1", "2" etc then it will work.

Since, you are just returning the floor values you can reduce the code by:

library(dplyr)
data<- data%>%
        mutate(floor = case_when(
               floor_id == 2 ~ "ground_floor",
               floor_id == 3 ~ "mezzanine",
               floor_id == 1 ~ "basement",
               floor_id == 30 ~ "over_10",
               TRUE ~ as.character(floor)))


问:
DLL load failed with PyQGIS
I've already asked this question in the "gis.stackexchange" forum, but it seems to be more appropriate for this one.

I am having problems with Python Shell importing the module "qgis.core".
When I type "import qgis.core" the Shell ("idle.pyw") gives me this error:

```<code>Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    import qgis.core
ImportError: DLL load failed: Impossibile trovare il modulo specificato (Trad "Impossible to find the specified module").
</code>```

I have already set the environment to point the right folders following "PyQGIS cookbook" instructions.
In my case, the paths are:

PYTHOPATH=C:\"QGIS_path"\apps\qgis\python;
Path=C:\"QGIS_path"\apps\qgis\bin.

Am I missing something? What are supposed to be the right libraries the Shell is unable to find?
I am working with windows 7 64 bit, QGIS Lisboa (version 1.8), Python 2.7.2 (the one that is included in the QGIS package).

答:
Check this link import-qgis-core-in-pycharm-no-module-named-pyqt5-qtcore
also ignore the pycharm setup if you want.

It works for me,

setup-qgispy.bat

    @ECHO off
    set OSGEO4W_ROOT=C:\QGIS
    call "%OSGEO4W_ROOT%\bin\o4w_env.bat"
    call "%OSGEO4W_ROOT%\bin\qt5_env.bat"
    call "%OSGEO4W_ROOT%\bin\py3_env.bat"
    path %OSGEO4W_ROOT%\apps\qgis\bin;%PATH%
    set QGIS_PREFIX_PATH=%OSGEO4W_ROOT%\apps\qgis
    set GDAL_FILENAME_IS_UTF8=YES
    set VSI_CACHE=TRUE
    set VSI_CACHE_SIZE=1000000
    set QT_PLUGIN_PATH=%OSGEO4W_ROOT%\apps\qgis\qtplugins;%OSGEO4W_ROOT%\apps\qt5\plugins
    set PYTHONPATH=%OSGEO4W_ROOT%\apps\qgis\python
    set PYTHONHOME=%OSGEO4W_ROOT%\apps\Python37
    set PYTHONPATH=%OSGEO4W_ROOT%\apps\Python37\lib\site-packages;%PYTHONPATH%
    set QT_QPA_PLATFORM_PLUGIN_PATH=%OSGEO4W_ROOT%\apps\Qt5\plugins\platforms
    set QGIS_PREFIX_PATH=%OSGEO4W_ROOT%\apps\qgis

and then,

C:\> setup-qgispy.bat

C:\> python file.py

Title: DLL load failed with PyQGIS

Body:
I've already asked this question in the "gis.stackexchange" forum, but it seems to be more appropriate for this one.

I am having problems with Python Shell importing the module "qgis.core".
When I type "import qgis.core" the Shell ("idle.pyw") gives me this error:

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    import qgis.core
ImportError: DLL load failed: Impossibile trovare il modulo specificato (Trad "Impossible to find the specified module").

I have already set the environment to point the right folders following "PyQGIS cookbook" instructions.
In my case, the paths are:

PYTHOPATH=C:\"QGIS_path"\apps\qgis\python;
Path=C:\"QGIS_path"\apps\qgis\bin.

Am I missing something? What are supposed to be the right libraries the Shell is unable to find?
I am working with windows 7 64 bit, QGIS Lisboa (version 1.8), Python 2.7.2 (the one that is included in the QGIS package).


问:
How to pass arguments to seeder from controller method in Laravel?
I'd like to create a dynamic model.

In fact, I have this seeder :

```<code>class TestSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table('tests')->insert([
            'name_test' => $name_test
        ]);
    }
}
</code>```

And I need to send arguments from my controller :

```<code>public function addTest(Request $request)
{
    $request->validate([
            'name_test' => 'required|max:255'
        ], [
            'name_test.required' => 'Es necesario rellenar el campo de nombre',
            'name_test.max' => 'El nombre del test debe ser máxim de 255 catacteres',
        ]);

    $input = $request->all();

    //$test = Test::create($input);

    return back()->with('success', 'El test se ha creado correctamente.');
}
</code>```

However, I have no idea how I can do it.

Any ideas ?

答:
You can just call the TestSeeder class directly:

$test = new TestSeeder;
$test->run($request->name_test);
```

<pre class="lang-php prettyprint-override"><code>public function run($name_test)
{
    DB::table('tests')->insert([
        'name_test' => $name_test
    ]);
}
</code>```

However, the seeder classes in Laravel are meant for initial data set up, when running tests or when you want to regularly refresh the database in your local environment, for example. You're better off to just run the insert right in the controller - nothing wrong with that when you're testing!

Body:
I'd like to create a dynamic model.

In fact, I have this seeder :

class TestSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table('tests')->insert([
            'name_test' => $name_test
        ]);
    }
}

And I need to send arguments from my controller :

public function addTest(Request $request)
{
    $request->validate([
            'name_test' => 'required|max:255'
        ], [
            'name_test.required' => 'Es necesario rellenar el campo de nombre',
            'name_test.max' => 'El nombre del test debe ser máxim de 255 catacteres',
        ]);

    $input = $request->all();

    //$test = Test::create($input);

    return back()->with('success', 'El test se ha creado correctamente.');
}

However, I have no idea how I can do it.

Any ideas ?

Body:
You can just call the TestSeeder class directly:

$test = new TestSeeder;
$test->run($request->name_test);

public function run($name_test)
{
    DB::table('tests')->insert([
        'name_test' => $name_test
    ]);
}

However, the seeder classes in Laravel are meant for initial data set up, when running tests or when you want to regularly refresh the database in your local environment, for example. You're better off to just run the insert right in the controller - nothing wrong with that when you're testing!


问:
Format Spring CommandObject variable on the front end
How do I format a value that is fetched from a command object on front end.

Its an SSN value which comes from the DB without any "-" (Hyphens). How do I convert this?

example: Convert 123456789 into 123-45-6789. Also the in the backing bean this field is an Int.

答: How about using fmt:substring

Body: How about using fmt:substring


问:
Set cookie for change template with JavaScript
how to Set cookie and get cookie in my code ?
i want change template But with refresh, everything goes back to the default state.
Is it possible to place cookies for all changes?

Code part 1

```<code>!(function (s, a, i) {
"use strict";
var t = {
        "theme-primary": "rgba(90, 141, 238, 0.2)",
        "theme-success": "rgba(57, 218, 138, 0.2)",
        "theme-danger": "rgba(255, 91, 92, 0.2)",
        "theme-info": "rgba(0, 207, 221, 0.2)",
        "theme-warning": "rgba(253, 172, 65, 0.2)",
        "theme-dark": "rgba(57, 76, 98, 0.2)",
    },
    d = { "theme-default": "#FFFFFF", "theme-primary": "#5A8DEE", "theme-success": "#39DA8A", "theme-danger": "#FF5B5C", "theme-info": "#00CFDD", "theme-warning": "#FDAC41", "theme-dark": "#394C62" },
    l = { "theme-primary": "-65px -54px", "theme-success": "-120px -10px", "theme-danger": "-10px -10px", "theme-info": "-10px -54px", "theme-warning": "-120px -54px", "theme-dark": "-65px -10px" },
    n = i("body"),
    c = (i(".app-content"), i(".main-menu")),
    v = i(".menu-content"),
    e = i(".footer"),
    o = i(".header-navbar"),
    r = i(".main-header-navbar"),
    b = (i(".navbar-light"), i(".header-navbar-shadow")),
    m = i(".toggle-icon"),
    g = i("#collapse-sidebar-switch"),
    u = i("#icon-animation-switch"),
    C = i(".customizer"),
    h = i(".brand-logo");
if (
    (i(".customizer-toggle").on("click", function (a) {
        a.preventDefault(), i(C).toggleClass("open");
    }),
    i(".customizer-close").on("click", function () {
        i(C).removeClass("open");
    }),
    0 < i(".customizer-content").length)
)
    new PerfectScrollbar(".customizer-content", { wheelPropagation: !1 });
i(a).on("click", "#customizer-theme-colors .color-box", function () {
    var a = i(this);
    a.siblings().removeClass("selected"), a.addClass("selected");
    var e = i(this).data("color"),
        s = t[e],
        n = d[e],
        o = l[e];
    function r(a) {
        a.updateLiviconEvo({ strokeColor: n, solidColor: n, fillColor: n, strokeColorAlt: n });
    }
</code>```

答:
Code part 2

```<code>        v.find("li.active").length
        ? (v.find("li.active a").css({ color: n }),
          v.find("li.active a > i").css({ color: n }),
          v.find("li.active a span.menu-item").css({ color: n }),
          v.find("li.active").css({ background: s, "border-color": n }),
          i("li.sidebar-group-active .menu-livicon").length && r(i("li.sidebar-group-active .menu-livicon")))
        : (c.find(".nav-item.active a").css({ background: s, color: n }), c.find(".nav-item.active a .menu-title").css({ color: n }), i(".nav-item.active .menu-livicon").length && r(i(".nav-item.active .menu-livicon"))),
        i(".brand-text").css("color", n),
        m.removeClass("primary").css("color", n),
        h.css("background-position", o);
}),
    i(".layout-name").on("click", function () {
        var a = i(this).data("layout");
        n.removeClass("dark-layout semi-dark-layout").addClass(a),
            "" === a && (c.removeClass("menu-dark").addClass("menu-light"), o.removeClass("navbar-dark").addClass("navbar-light"), r.css({ "background-color": "inherit" })),
            n.hasClass("dark-layout") && (c.removeClass("menu-light").addClass("menu-dark"), o.removeClass("navbar-light").addClass("navbar-dark"), r.css({ "background-color": "inherit" })),
            n.hasClass("semi-dark-layout") && (c.removeClass("menu-light").addClass("menu-dark"), o.removeClass("navbar-dark").addClass("navbar-light"), r.css({ "background-color": "inherit" }));
    });
var f = n.data("layout");
if (
    (i(".layout-name[data-layout='" + f + "']").prop("checked", !0),
    u.on("click", function () {
        i(this).is(":checked") ? i("#main-menu-navigation .menu-livicon").updateLiviconEvo({ animated: !0 }) : i("#main-menu-navigation .menu-livicon").updateLiviconEvo({ animated: !1 });
    }),
    g.on("click", function () {
        i(n).hasClass("menu-expanded")
            ? (n.removeClass("menu-expanded").addClass("menu-collapsed"),
              c.removeClass("expanded"),
              c.find(".sidebar-group-active").removeClass("open").addClass("menu-collapsed-open"),
              m.removeClass("bx bx-disc").addClass("bx bx-circle"))
            : (n.removeClass("menu-collapsed").addClass("menu-expanded"), c.find(".sidebar-group-active").addClass("open"), m.removeClass("bx bx-circle").addClass("bx bx-disc"));
    }),
    m.on("click", function () {
        g.prop("checked", !g.prop("checked"));
    }),
    n.hasClass("menu-collapsed") ? g.prop("checked", !0) : g.prop("checked", !1),
    i(n).hasClass("horizontal-layout") &&
        (i("#customizer-navbar-colors .color-box.bg-white").removeClass("selected").hide(),
        i("#customizer-navbar-colors .color-box.bg-primary").addClass("selected"),
        i("#customizer-theme-colors").hide(),
        i(".navbar-type .hidden-ele").hide()),
    i(n).hasClass("navbar-static") && i("#navbar-static").attr("checked", "true"),
    i(n).hasClass("boxicon-layout") && i("#menu-icon-animation").hide(),
    i("#customizer-navbar-colors .color-box").on("click", function () {
        var a = i(this);
        a.siblings().removeClass("selected"), a.addClass("selected");
        var e = a.data("navbar-color");
        i(n).hasClass("vertical-layout")
            ? 20 < i(s).scrollTop() &&
              (e
                  ? i(".vertical-layout")
                        .find(o)
                        .removeClass("bg-primary bg-success bg-danger bg-info bg-warning bg-dark navbar-light")
                        .addClass(e + " navbar-dark")
                  : i(".vertical-layout.navbar-sticky").find(o).addClass("navbar-light").removeClass("navbar-dark").removeClass("bg-primary bg-success bg-danger bg-info bg-warning bg-white bg-dark navbar-dark"),
              n.hasClass("dark-layout") && o.addClass("navbar-dark"))
            : e && i(".horizontal-layout").find(".navbar-with-menu").removeClass("bg-primary bg-success bg-danger bg-info bg-warning bg-dark").addClass(e);
    }),
    i(s).scroll(function () {
        var a = i("#customizer-navbar-colors .color-box.selected").data("navbar-color");
        i(this).scrollTop() < 20
            ? i(".vertical-layout.navbar-sticky").find(r).removeClass("bg-primary bg-success bg-danger bg-info bg-warning bg-white bg-dark navbar-dark")
            : a &&
              i(".vertical-layout.navbar-sticky")
                  .find(r)
                  .removeClass("bg-primary bg-success bg-danger bg-info bg-warning bg-white bg-dark navbar-dark")
                  .addClass(a + " navbar-dark");
    }),
</code>```

})(window, document, jQuery);

Body:
how to Set cookie and get cookie in my code ?
i want change template But with refresh, everything goes back to the default state.
Is it possible to place cookies for all changes?

Code part 1

!(function (s, a, i) {
"use strict";
var t = {
        "theme-primary": "rgba(90, 141, 238, 0.2)",
        "theme-success": "rgba(57, 218, 138, 0.2)",
        "theme-danger": "rgba(255, 91, 92, 0.2)",
        "theme-info": "rgba(0, 207, 221, 0.2)",
        "theme-warning": "rgba(253, 172, 65, 0.2)",
        "theme-dark": "rgba(57, 76, 98, 0.2)",
    },
    d = { "theme-default": "#FFFFFF", "theme-primary": "#5A8DEE", "theme-success": "#39DA8A", "theme-danger": "#FF5B5C", "theme-info": "#00CFDD", "theme-warning": "#FDAC41", "theme-dark": "#394C62" },
    l = { "theme-primary": "-65px -54px", "theme-success": "-120px -10px", "theme-danger": "-10px -10px", "theme-info": "-10px -54px", "theme-warning": "-120px -54px", "theme-dark": "-65px -10px" },
    n = i("body"),
    c = (i(".app-content"), i(".main-menu")),
    v = i(".menu-content"),
    e = i(".footer"),
    o = i(".header-navbar"),
    r = i(".main-header-navbar"),
    b = (i(".navbar-light"), i(".header-navbar-shadow")),
    m = i(".toggle-icon"),
    g = i("#collapse-sidebar-switch"),
    u = i("#icon-animation-switch"),
    C = i(".customizer"),
    h = i(".brand-logo");
if (
    (i(".customizer-toggle").on("click", function (a) {
        a.preventDefault(), i(C).toggleClass("open");
    }),
    i(".customizer-close").on("click", function () {
        i(C).removeClass("open");
    }),
    0 < i(".customizer-content").length)
)
    new PerfectScrollbar(".customizer-content", { wheelPropagation: !1 });
i(a).on("click", "#customizer-theme-colors .color-box", function () {
    var a = i(this);
    a.siblings().removeClass("selected"), a.addClass("selected");
    var e = i(this).data("color"),
        s = t[e],
        n = d[e],
        o = l[e];
    function r(a) {
        a.updateLiviconEvo({ strokeColor: n, solidColor: n, fillColor: n, strokeColorAlt: n });
    }

Body:
Code part 2

        v.find("li.active").length
        ? (v.find("li.active a").css({ color: n }),
          v.find("li.active a > i").css({ color: n }),
          v.find("li.active a span.menu-item").css({ color: n }),
          v.find("li.active").css({ background: s, "border-color": n }),
          i("li.sidebar-group-active .menu-livicon").length && r(i("li.sidebar-group-active .menu-livicon")))
        : (c.find(".nav-item.active a").css({ background: s, color: n }), c.find(".nav-item.active a .menu-title").css({ color: n }), i(".nav-item.active .menu-livicon").length && r(i(".nav-item.active .menu-livicon"))),
        i(".brand-text").css("color", n),
        m.removeClass("primary").css("color", n),
        h.css("background-position", o);
}),
    i(".layout-name").on("click", function () {
        var a = i(this).data("layout");
        n.removeClass("dark-layout semi-dark-layout").addClass(a),
            "" === a && (c.removeClass("menu-dark").addClass("menu-light"), o.removeClass("navbar-dark").addClass("navbar-light"), r.css({ "background-color": "inherit" })),
            n.hasClass("dark-layout") && (c.removeClass("menu-light").addClass("menu-dark"), o.removeClass("navbar-light").addClass("navbar-dark"), r.css({ "background-color": "inherit" })),
            n.hasClass("semi-dark-layout") && (c.removeClass("menu-light").addClass("menu-dark"), o.removeClass("navbar-dark").addClass("navbar-light"), r.css({ "background-color": "inherit" }));
    });
var f = n.data("layout");
if (
    (i(".layout-name[data-layout='" + f + "']").prop("checked", !0),
    u.on("click", function () {
        i(this).is(":checked") ? i("#main-menu-navigation .menu-livicon").updateLiviconEvo({ animated: !0 }) : i("#main-menu-navigation .menu-livicon").updateLiviconEvo({ animated: !1 });
    }),
    g.on("click", function () {
        i(n).hasClass("menu-expanded")
            ? (n.removeClass("menu-expanded").addClass("menu-collapsed"),
              c.removeClass("expanded"),
              c.find(".sidebar-group-active").removeClass("open").addClass("menu-collapsed-open"),
              m.removeClass("bx bx-disc").addClass("bx bx-circle"))
            : (n.removeClass("menu-collapsed").addClass("menu-expanded"), c.find(".sidebar-group-active").addClass("open"), m.removeClass("bx bx-circle").addClass("bx bx-disc"));
    }),
    m.on("click", function () {
        g.prop("checked", !g.prop("checked"));
    }),
    n.hasClass("menu-collapsed") ? g.prop("checked", !0) : g.prop("checked", !1),
    i(n).hasClass("horizontal-layout") &&
        (i("#customizer-navbar-colors .color-box.bg-white").removeClass("selected").hide(),
        i("#customizer-navbar-colors .color-box.bg-primary").addClass("selected"),
        i("#customizer-theme-colors").hide(),
        i(".navbar-type .hidden-ele").hide()),
    i(n).hasClass("navbar-static") && i("#navbar-static").attr("checked", "true"),
    i(n).hasClass("boxicon-layout") && i("#menu-icon-animation").hide(),
    i("#customizer-navbar-colors .color-box").on("click", function () {
        var a = i(this);
        a.siblings().removeClass("selected"), a.addClass("selected");
        var e = a.data("navbar-color");
        i(n).hasClass("vertical-layout")
            ? 20 < i(s).scrollTop() &&
              (e
                  ? i(".vertical-layout")
                        .find(o)
                        .removeClass("bg-primary bg-success bg-danger bg-info bg-warning bg-dark navbar-light")
                        .addClass(e + " navbar-dark")
                  : i(".vertical-layout.navbar-sticky").find(o).addClass("navbar-light").removeClass("navbar-dark").removeClass("bg-primary bg-success bg-danger bg-info bg-warning bg-white bg-dark navbar-dark"),
              n.hasClass("dark-layout") && o.addClass("navbar-dark"))
            : e && i(".horizontal-layout").find(".navbar-with-menu").removeClass("bg-primary bg-success bg-danger bg-info bg-warning bg-dark").addClass(e);
    }),
    i(s).scroll(function () {
        var a = i("#customizer-navbar-colors .color-box.selected").data("navbar-color");
        i(this).scrollTop() < 20
            ? i(".vertical-layout.navbar-sticky").find(r).removeClass("bg-primary bg-success bg-danger bg-info bg-warning bg-white bg-dark navbar-dark")
            : a &&
              i(".vertical-layout.navbar-sticky")
                  .find(r)
                  .removeClass("bg-primary bg-success bg-danger bg-info bg-warning bg-white bg-dark navbar-dark")
                  .addClass(a + " navbar-dark");
    }),

})(window, document, jQuery);


问:
Is there a way to count and calculate mean for text columns using groupby?
I have been using pandas.groupby to pivot data and create descriptive charts and tables for my data. While doing groupby for three variables, I keep running into a DataError: No numeric types to aggregate error while working with the cancelled column.

To describe my data, Year and Month contain yearly and monthly data for multiple columns (multiple years, all months), Type contains the type of order item (Clothes, Appliances, etc.), and cancelled contains yes or no string values to determine whether a order was cancelled or not.

I am hoping to plot a graph and show a table to show what the cancellation rate (and success rate) is by order item. The following is what I'm using so far

```<code>df.groupby(['Year', 'Month', 'Type'])['cancelled'].mean()
</code>```

But this doesn't seem to be working.

Sample

```<code>Year    Month        Type          cancelled
2012      1        electronics       yes
2012      10         fiber           yes
2012      9         clothes          no
2013      4        vegetables        yes
2013      5        appliances        no
2016      3        fiber             no
2017      1        clothes           yes
</code>```

答:
It's possible I have misunderstood what you want your output to look like, but to find the cancellation rate for each item type, you could do something like this:

```<code># change 'cancelled' to numeric values
df.loc[df['cancelled'] == 'yes', 'cancelled'] = 1
df.loc[df['cancelled'] == 'no', 'cancelled'] = 0

# get the mean of 'cancelled' for each item type
res = {}
for t in df['Type'].unique():
    res[t] = df.loc[df['Type'] == t, 'cancelled'].mean()

# if desired, put it into a dataframe
results = pd.DataFrame([res], index=['Rate']).T
</code>```

Output:

```<code>              Rate
electronics   1.0
fiber         0.5
clothes       0.5
vegetables    1.0
appliances    0.0
</code>```

Note: If you want to specify specific years or months, you can do that with loc as well, but given that your example data did not have any repeats within a given year or month, this would return your original dataframe for your given example.

Body:
I have been using pandas.groupby to pivot data and create descriptive charts and tables for my data. While doing groupby for three variables, I keep running into a DataError: No numeric types to aggregate error while working with the cancelled column.

To describe my data, Year and Month contain yearly and monthly data for multiple columns (multiple years, all months), Type contains the type of order item (Clothes, Appliances, etc.), and cancelled contains yes or no string values to determine whether a order was cancelled or not.

I am hoping to plot a graph and show a table to show what the cancellation rate (and success rate) is by order item. The following is what I'm using so far

df.groupby(['Year', 'Month', 'Type'])['cancelled'].mean()

But this doesn't seem to be working.

Sample

Year    Month        Type          cancelled
2012      1        electronics       yes
2012      10         fiber           yes
2012      9         clothes          no
2013      4        vegetables        yes
2013      5        appliances        no
2016      3        fiber             no
2017      1        clothes           yes

Body:
It's possible I have misunderstood what you want your output to look like, but to find the cancellation rate for each item type, you could do something like this:

# change 'cancelled' to numeric values
df.loc[df['cancelled'] == 'yes', 'cancelled'] = 1
df.loc[df['cancelled'] == 'no', 'cancelled'] = 0

# get the mean of 'cancelled' for each item type
res = {}
for t in df['Type'].unique():
    res[t] = df.loc[df['Type'] == t, 'cancelled'].mean()

# if desired, put it into a dataframe
results = pd.DataFrame([res], index=['Rate']).T

Output:

              Rate
electronics   1.0
fiber         0.5
clothes       0.5
vegetables    1.0
appliances    0.0

Note: If you want to specify specific years or months, you can do that with loc as well, but given that your example data did not have any repeats within a given year or month, this would return your original dataframe for your given example.


问:
How to delete an SMS from the inbox in Android programmatically?
On Android phones SMS messages registered to applications also get sent to the device's inbox.  However to prevent clutter, it'd be nice to be able to remove application specific SMS messages from the inbox to reduce the potential overflow of those messages.

Questions on other Google groups on getting a definitive answer on a programmatic way to delete SMS messages from the Android inbox don't seem to be pressing.

So the scenario:

Android App startup.

register SMS message types X,Y and Z

messages P,Q,X,Y,Z stream in over the course of time, all deposited in inbox

Android application detects receipt of X,Y,Z (presumably as part of the program interrupt event)

process X,Y,Z

Desirement!!! X,Y,Z are deleted from the Android inbox

Has it been done?  Can it be done?

答:
"As of Android 1.6, incoming SMS message broadcasts (android.provider.Telephony.SMS_RECEIVED) are delivered as an "ordered broadcast" — meaning that you can tell the system which components should receive the broadcast first."

This means that you can intercept incoming message and abort broadcasting of it further on.

In your AndroidManifest.xml file, make sure to have priority set to highest:

```<code><receiver android:name=".receiver.SMSReceiver" android:enabled="true">
    <intent-filter android:priority="1000">
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>
</code>```

In your BroadcastReceiver, in onReceive() method, before performing anything with your message, simply call abortBroadcast();

EDIT: As of KitKat, this doesn't work anymore apparently.

EDIT2: More info on how to do it on KitKat here:

Delete SMS from android on 4.4.4 (Affected rows = 0(Zero), after deleted)

OwnerDisplayName: dmyung

ContentLicense: CC BY-SA 2.5

Body:
"As of Android 1.6, incoming SMS message broadcasts (android.provider.Telephony.SMS_RECEIVED) are delivered as an "ordered broadcast" — meaning that you can tell the system which components should receive the broadcast first."

This means that you can intercept incoming message and abort broadcasting of it further on.

In your AndroidManifest.xml file, make sure to have priority set to highest:

<receiver android:name=".receiver.SMSReceiver" android:enabled="true">
    <intent-filter android:priority="1000">
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

In your BroadcastReceiver, in onReceive() method, before performing anything with your message, simply call abortBroadcast();

EDIT: As of KitKat, this doesn't work anymore apparently.

EDIT2: More info on how to do it on KitKat here:

Delete SMS from android on 4.4.4 (Affected rows = 0(Zero), after deleted)


问:
Flutter - Loops for ListTile
I am not sure how to generate multiple ListTiles by means of loops, such as for().

I do not know how Flutter works for rendering widgets, since in Angular 2 just insert the *ngFor directives in the layout (html).

I could not find such a subject in the Flutter documentation.

main.dart

```<code>import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: "Myapp",
      home: new HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {

  @override
  Widget build(BuildContext context) => new Scaffold(
    appBar: new AppBar(
      backgroundColor: new Color(0xFF26C6DA),
    ),
    body: new ListView (
      children: <Widget>[
        new Card(
          child: new Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              const ListTile(
                leading: const Icon(Icons.album),
                title: const Text('The Enchanted Nightingale'),
                subtitle: const Text('Music by Julie Gable. Lyrics by Sidney Stein.'),
              ),
            ],
          ),
        ),
      ],
    )
  );
}
</code>```

答:
Here is the example with List.generate:-

```<code>import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      debugShowCheckedModeBanner: false,
      title: "Myapp",
      home: new HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: Text('List.generate demo'),
      ),
      body: new ListView(
        padding: const EdgeInsets.all(8),
        children: new List.generate(
          10,
          (index) => new ListTile(
            title: Text('Item $index'),
          ),
        ),
      ),
    );
  }
}
</code>```

Title: Flutter - Loops for ListTile

Body:
I am not sure how to generate multiple ListTiles by means of loops, such as for().

I do not know how Flutter works for rendering widgets, since in Angular 2 just insert the *ngFor directives in the layout (html).

I could not find such a subject in the Flutter documentation.

main.dart

import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: "Myapp",
      home: new HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {

  @override
  Widget build(BuildContext context) => new Scaffold(
    appBar: new AppBar(
      backgroundColor: new Color(0xFF26C6DA),
    ),
    body: new ListView (
      children: <Widget>[
        new Card(
          child: new Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              const ListTile(
                leading: const Icon(Icons.album),
                title: const Text('The Enchanted Nightingale'),
                subtitle: const Text('Music by Julie Gable. Lyrics by Sidney Stein.'),
              ),
            ],
          ),
        ),
      ],
    )
  );
}

Body:
Here is the example with List.generate:-

import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      debugShowCheckedModeBanner: false,
      title: "Myapp",
      home: new HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: Text('List.generate demo'),
      ),
      body: new ListView(
        padding: const EdgeInsets.all(8),
        children: new List.generate(
          10,
          (index) => new ListTile(
            title: Text('Item $index'),
          ),
        ),
      ),
    );
  }
}


问:
VBScript, Text to Clipboard to Paste in Any Field
I have put together a script that will copy my desired text into my clipboard so I can paste content in any text field.

```<code>Dim string
String = "This Is A script that allows me to copy text contained withing these quotes directly into my clipboard. Which yes is plenty fast as it is when compared to finding file, opening file, selecting desired content, copy content, and select location to paste content."
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "cmd.exe /c echo " & String & " | clip", 0, TRUE
</code>```

Current steps required is

run script

navigate to desired location

paste content.

I am trying to make it so that I can use a hotkey at desired location
1. Ctrl + Alt + F1 (Or any combo) to get Text to Clipboard to Paste

答:
To get text from clipboard:

```<code>' Use the HTML parser to get clipboard text
Dim x : x = CreateObject("htmlfile").ParentWindow.ClipboardData.GetData("text")

WScript.Echo x
</code>```

To write contents to file:

```<code>Dim fileObj : Set fileObj = CreateObject("Scripting.FileSystemObject").CreateTextFile("clipboard.txt")
fileObj.Write(x)
fileObj.Close
</code>```

Body:
I have put together a script that will copy my desired text into my clipboard so I can paste content in any text field.

Dim string
String = "This Is A script that allows me to copy text contained withing these quotes directly into my clipboard. Which yes is plenty fast as it is when compared to finding file, opening file, selecting desired content, copy content, and select location to paste content."
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "cmd.exe /c echo " & String & " | clip", 0, TRUE

Current steps required is

run script

navigate to desired location

paste content.

I am trying to make it so that I can use a hotkey at desired location
1. Ctrl + Alt + F1 (Or any combo) to get Text to Clipboard to Paste

Body:
To get text from clipboard:

' Use the HTML parser to get clipboard text
Dim x : x = CreateObject("htmlfile").ParentWindow.ClipboardData.GetData("text")

WScript.Echo x

To write contents to file:

Dim fileObj : Set fileObj = CreateObject("Scripting.FileSystemObject").CreateTextFile("clipboard.txt")
fileObj.Write(x)
fileObj.Close


问:
Get Error 530 5.7.0 Authentication Required when sending email using Django Python
I am trying to send emails with G-Suite account using python in Django. As Google stoped the less secure App option for the new applications, I have to use Oauth2.
But when I start to send emails via smtplib, the ERROR:

```<code>smtplib.SMTPSenderRefused: (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0  https://support.google.com/mail/?p=WantAuthError q4sm8418287pfl.175 - gsmtp'
</code>```

And after looking up the reference, it means "530, "5.7.0", Must issue a STARTTLS command first."
However, I have added "server.starttls()". Could someone help me? Many thanks.

```<code>server = smtplib.SMTP('smtp.gmail.com', port=587)
server.ehlo('test')
server.starttls()
server.docmd('AUTH', 'XOAUTH2 ' + base64.b64encode(auth_string.encode()).decode("utf-8"))
server.sendmail(from_addr, to_addr, msg.as_string())
server.quit()
</code>```

答:
```<code>EMAIL_BACKEND="django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST_USER ='youremail@gmail.com'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_PASSWORD = 'yourpassword'
EMAIL_USE_TLS = True
</code>```

Add this on your settings. After that :

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

You will enter to Python shell. Then:

```<code>from django.core.mail import send_mail
</code>```

Write this command on shell and after that:

```<code>send_mail(
    "django test mail",
    "this is django test mail",
    "your.email@gmail.com",
    "recipient.email@example.com",
    fail_silently=False
)
</code>```

If output is equal to:

1

, then you send email through your Gmail.

Body:
I am trying to send emails with G-Suite account using python in Django. As Google stoped the less secure App option for the new applications, I have to use Oauth2.
But when I start to send emails via smtplib, the ERROR:

smtplib.SMTPSenderRefused: (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0  https://support.google.com/mail/?p=WantAuthError q4sm8418287pfl.175 - gsmtp'

And after looking up the reference, it means "530, "5.7.0", Must issue a STARTTLS command first."
However, I have added "server.starttls()". Could someone help me? Many thanks.

server = smtplib.SMTP('smtp.gmail.com', port=587)
server.ehlo('test')
server.starttls()
server.docmd('AUTH', 'XOAUTH2 ' + base64.b64encode(auth_string.encode()).decode("utf-8"))
server.sendmail(from_addr, to_addr, msg.as_string())
server.quit()

Body:
EMAIL_BACKEND="django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST_USER ='youremail@gmail.com'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_PASSWORD = 'yourpassword'
EMAIL_USE_TLS = True

Add this on your settings. After that :

python manage.py shell

You will enter to Python shell. Then:

from django.core.mail import send_mail

Write this command on shell and after that:

send_mail(
    "django test mail",
    "this is django test mail",
    "your.email@gmail.com",
    "recipient.email@example.com",
    fail_silently=False
)

If output is equal to:

1

, then you send email through your Gmail.