问:
How to make the mark_rule in Altair change based on user input?
I would like to make the mark_rule (significance level) to be adjustable. I have tried to do it using user input code and change the value in the rule from 0.05 to 'user input' but the chart turned out weird.

There are two things that I would like to ask for help with:

Make the mark_rule change through user input (top priority)

Make the color of the bars (factors) below the mark_rule change (optional)

I have tried many codes in this, by far, I can only make the mark_rule move using mouseover but it is not exactly what I want to do.

Any help would be very much appreciated.

```<code>import pandas as pd
import altair as alt

Sheet2 = 'P-value'
df = pd.read_excel('Life Expectancy Data- Clean.xlsx', sheet_name=Sheet2)

highlight = alt.selection(type='single', on='mouseover',
                          fields=['Factor'], nearest=True, empty="none")

bar = alt.Chart(df).mark_bar(strokeWidth=5, stroke="steelblue", strokeOpacity=0.1).encode(
        x = alt.X('Factor:O', sort='y'),
        y = alt.Y('P-value:Q'),
        tooltip = [alt.Tooltip('Factor:O'),alt.Tooltip('P-value:Q',format='.4f')],
        color= alt.condition(
            highlight,
            alt.value("orange"),
            alt.value("steelblue"))
    ).add_selection(
        highlight
    )

rule = alt.Chart(pd.DataFrame({'y': [0.05]})).mark_rule(color='red').encode(y='y')

alt.layer(
    bar, rule
).properties(
    title='Factors that Contribute to Life Expectancy in Malaysia',
    width=500, height=300
)
</code>```

Current graph

答:
Building upon the example in the Altair docs, you could do something like this, which gives you a slider that controls the position of the rule and highlights the bars in different colors depending on if they are above or below the slider value:

```<code>import altair as alt
import pandas as pd
import numpy as np

rand = np.random.RandomState(42)

df = pd.DataFrame({
    'xval': range(10),
    'yval': rand.randn(10).cumsum()
})

slider = alt.binding_range(min=0, max=5, step=0.5, name='cutoff:')
selector = alt.selection_single(name="SelectorName", bind=slider, init={'cutoff': 2.5})

rule = alt.Chart().mark_rule().transform_calculate(
    rule='SelectorName.cutoff'
).encode(
    # Take the mean to avoid creating multiple lines on top of eachother
    y='mean(rule):Q',
)

bars = alt.Chart(df).mark_bar().encode(
    x='xval:O',
    y='yval',
    color=alt.condition(
        alt.datum.yval < selector.cutoff,
        alt.value('coral'), alt.value('steelblue')
    )
).add_selection(
    selector
)

bars + rule
</code>```

Body:
I would like to make the mark_rule (significance level) to be adjustable. I have tried to do it using user input code and change the value in the rule from 0.05 to 'user input' but the chart turned out weird.

There are two things that I would like to ask for help with:

Make the mark_rule change through user input (top priority)

Make the color of the bars (factors) below the mark_rule change (optional)

I have tried many codes in this, by far, I can only make the mark_rule move using mouseover but it is not exactly what I want to do.

Any help would be very much appreciated.

import pandas as pd
import altair as alt

Sheet2 = 'P-value'
df = pd.read_excel('Life Expectancy Data- Clean.xlsx', sheet_name=Sheet2)

highlight = alt.selection(type='single', on='mouseover',
                          fields=['Factor'], nearest=True, empty="none")

bar = alt.Chart(df).mark_bar(strokeWidth=5, stroke="steelblue", strokeOpacity=0.1).encode(
        x = alt.X('Factor:O', sort='y'),
        y = alt.Y('P-value:Q'),
        tooltip = [alt.Tooltip('Factor:O'),alt.Tooltip('P-value:Q',format='.4f')],
        color= alt.condition(
            highlight,
            alt.value("orange"),
            alt.value("steelblue"))
    ).add_selection(
        highlight
    )

rule = alt.Chart(pd.DataFrame({'y': [0.05]})).mark_rule(color='red').encode(y='y')

alt.layer(
    bar, rule
).properties(
    title='Factors that Contribute to Life Expectancy in Malaysia',
    width=500, height=300
)

Current graph

Body:
Building upon the example in the Altair docs, you could do something like this, which gives you a slider that controls the position of the rule and highlights the bars in different colors depending on if they are above or below the slider value:

import altair as alt
import pandas as pd
import numpy as np

rand = np.random.RandomState(42)

df = pd.DataFrame({
    'xval': range(10),
    'yval': rand.randn(10).cumsum()
})

slider = alt.binding_range(min=0, max=5, step=0.5, name='cutoff:')
selector = alt.selection_single(name="SelectorName", bind=slider, init={'cutoff': 2.5})

rule = alt.Chart().mark_rule().transform_calculate(
    rule='SelectorName.cutoff'
).encode(
    # Take the mean to avoid creating multiple lines on top of eachother
    y='mean(rule):Q',
)

bars = alt.Chart(df).mark_bar().encode(
    x='xval:O',
    y='yval',
    color=alt.condition(
        alt.datum.yval < selector.cutoff,
        alt.value('coral'), alt.value('steelblue')
    )
).add_selection(
    selector
)

bars + rule


来源: stackexchange

问:
Xcode 12: Failed to start remote service "com.apple.debugserver" on iOS device
I updated my Xcode to Version 12.4 (12D4e) and after that I am unable to run my app on my device
iPhone X iOS 14.4.2.

Its alway show this Error

When I check my device connected status, Its show as connected

Action I applied

Clear DerivedData folder.

Unpair device and connected again.

Drank 20+ coffees.

答: I reset the iPhone network settings and it works!</p>

ContentLicense: CC BY-SA 4.0


问:
Failed to Execute Build Analyzer Maven Plugin in Local SDK
```<code>[INFO] --- aemanalyser-maven-plugin:0.9.2:analyse (default-analyse) @ aem-guides-myproject.analyse ---
[INFO] Starting analyzing feature 'com.adobe.aem.guides.myproject:aem-guides-myproject.analyse:slingosgifeature:aggregated-author.prod:0.0.1-SNAPSHOT'...
[INFO] - Executing Api Regions analyser task that checks that listed packages are actually exported [api-regions]...
[INFO] - Executing Api Regions check order analyser task [api-regions-check-order]...
[INFO] - Executing Bundle Import/Export Check [api-regions-exportsimports]...
[INFO] - Executing Api Regions cross-feature duplicate export task [api-regions-crossfeature-dups]...
[INFO] - Executing Configuration API analyser task [configuration-api]...
[INFO] - Executing Bundle Natice Code Check [bundle-nativecode]...
[INFO] - Executing Bundle Initial Content Check [bundle-content]...
[INFO] - Executing Bundle Resources Check [bundle-resources]...
[INFO] - Executing Requirements Capabilities check [requirements-capabilities]...
[INFO] Analyzing feature 'com.adobe.aem.guides.myproject:aem-guides-myproject.analyse:slingosgifeature:aggregated-author.prod:0.0.1-SNAPSHOT' finished : 0 warnings, 3 errors.
[ERROR] Configuration org.apache.sling.commons.log.LogManager.factory.config~asyncjssightly.org.apache.sling.commons.log.level : Value error does not match provided options
[ERROR] Configuration org.apache.sling.commons.log.LogManager.factory.config~myproject.org.apache.sling.commons.log.level : Value error does not match provided options
[ERROR] Configuration org.apache.sling.commons.log.LogManager.factory.config~myproject.org.apache.sling.commons.log.pattern : Property is not allowed
[ERROR] Analyser detected errors on feature 'com.adobe.aem.guides.myproject:aem-guides-myproject.analyse:slingosgifeature:aggregated-author.prod:0.0.1-SNAPSHOT'. See log output for error messages.
[INFO] Starting analyzing feature 'com.adobe.aem.guides.myproject:aem-guides-myproject.analyse:slingosgifeature:aggregated-publish.prod:0.0.1-SNAPSHOT'...
[INFO] - Executing Api Regions analyser task that checks that listed packages are actually exported [api-regions]...
[INFO] - Executing Api Regions check order analyser task [api-regions-check-order]...
[INFO] - Executing Bundle Import/Export Check [api-regions-exportsimports]...
[INFO] - Executing Api Regions cross-feature duplicate export task [api-regions-crossfeature-dups]...
[INFO] - Executing Configuration API analyser task [configuration-api]...
[INFO] - Executing Bundle Natice Code Check [bundle-nativecode]...
[INFO] - Executing Bundle Initial Content Check [bundle-content]...
[INFO] - Executing Bundle Resources Check [bundle-resources]...
[INFO] - Executing Requirements Capabilities check [requirements-capabilities]...
[INFO] Analyzing feature 'com.adobe.aem.guides.myproject:aem-guides-myproject.analyse:slingosgifeature:aggregated-publish.prod:0.0.1-SNAPSHOT' finished : 0 warnings, 3 errors.
[ERROR] Configuration org.apache.sling.commons.log.LogManager.factory.config~asyncjssightly.org.apache.sling.commons.log.level : Value error does not match provided options
[ERROR] Configuration org.apache.sling.commons.log.LogManager.factory.config~myproject.org.apache.sling.commons.log.level : Value error does not match provided options
[ERROR] Configuration org.apache.sling.commons.log.LogManager.factory.config~myproject.org.apache.sling.commons.log.pattern : Property is not allowed
[ERROR] Analyser detected errors on feature 'com.adobe.aem.guides.myproject:aem-guides-myproject.analyse:slingosgifeature:aggregated-publish.prod:0.0.1-SNAPSHOT'. See log output for error messages.
[INFO] Starting analyzing feature 'com.adobe.aem.guides.myproject:aem-guides-myproject.analyse:slingosgifeature:aggregated-publish.stage:0.0.1-SNAPSHOT'...
[INFO] - Executing Api Regions analyser task that checks that listed packages are actually exported [api-regions]...
[INFO] - Executing Api Regions check order analyser task [api-regions-check-order]...
[INFO] - Executing Bundle Import/Export Check [api-regions-exportsimports]...
[INFO] - Executing Api Regions cross-feature duplicate export task [api-regions-crossfeature-dups]...
[INFO] - Executing Configuration API analyser task [configuration-api]...
[INFO] - Executing Bundle Natice Code Check [bundle-nativecode]...
[INFO] - Executing Bundle Initial Content Check [bundle-content]...
[INFO] - Executing Bundle Resources Check [bundle-resources]...
[INFO] - Executing Requirements Capabilities check [requirements-capabilities]...
[INFO] Analyzing feature 'com.adobe.aem.guides.myproject:aem-guides-myproject.analyse:slingosgifeature:aggregated-publish.stage:0.0.1-SNAPSHOT' finished : 0 warnings, 2 errors.
[ERROR] Configuration org.apache.sling.commons.log.LogManager.factory.config~asyncjssightly.org.apache.sling.commons.log.level : Value error does not match provided options
[ERROR] Configuration org.apache.sling.commons.log.LogManager.factory.config~myproject.org.apache.sling.commons.log.pattern : Property is not allowed
[ERROR] Analyser detected errors on feature 'com.adobe.aem.guides.myproject:aem-guides-myproject.analyse:slingosgifeature:aggregated-publish.stage:0.0.1-SNAPSHOT'. See log output for error messages.
[INFO] Starting analyzing feature 'com.adobe.aem.guides.myproject:aem-guides-myproject.analyse:slingosgifeature:aggregated-publish:0.0.1-SNAPSHOT'...
[INFO] - Executing Api Regions analyser task that checks that listed packages are actually exported [api-regions]...
[INFO] - Executing Api Regions check order analyser task [api-regions-check-order]...
[INFO] - Executing Bundle Import/Export Check [api-regions-exportsimports]...
[INFO] - Executing Api Regions cross-feature duplicate export task [api-regions-crossfeature-dups]...
[INFO] - Executing Configuration API analyser task [configuration-api]...
[INFO] - Executing Bundle Natice Code Check [bundle-nativecode]...
[INFO] - Executing Bundle Initial Content Check [bundle-content]...
[INFO] - Executing Bundle Resources Check [bundle-resources]...
[INFO] - Executing Requirements Capabilities check [requirements-capabilities]...
[INFO] Analyzing feature 'com.adobe.aem.guides.myproject:aem-guides-myproject.analyse:slingosgifeature:aggregated-publish:0.0.1-SNAPSHOT' finished : 0 warnings, 2 errors.
[ERROR] Configuration org.apache.sling.commons.log.LogManager.factory.config~asyncjssightly.org.apache.sling.commons.log.level : Value error does not match provided options
[ERROR] Configuration org.apache.sling.commons.log.LogManager.factory.config~myproject.org.apache.sling.commons.log.pattern : Property is not allowed
[ERROR] Analyser detected errors on feature 'com.adobe.aem.guides.myproject:aem-guides-myproject.analyse:slingosgifeature:aggregated-publish:0.0.1-SNAPSHOT'. See log output for error messages.
[INFO] Starting analyzing feature 'com.adobe.aem.guides.myproject:aem-guides-myproject.analyse:slingosgifeature:aggregated-author:0.0.1-SNAPSHOT'...
[INFO] - Executing Api Regions analyser task that checks that listed packages are actually exported [api-regions]...
[INFO] - Executing Api Regions check order analyser task [api-regions-check-order]...
[INFO] - Executing Bundle Import/Export Check [api-regions-exportsimports]...
[INFO] - Executing Api Regions cross-feature duplicate export task [api-regions-crossfeature-dups]...
[INFO] - Executing Configuration API analyser task [configuration-api]...
[INFO] - Executing Bundle Natice Code Check [bundle-nativecode]...
[INFO] - Executing Bundle Initial Content Check [bundle-content]...
[INFO] - Executing Bundle Resources Check [bundle-resources]...
[INFO] - Executing Requirements Capabilities check [requirements-capabilities]...
[INFO] Analyzing feature 'com.adobe.aem.guides.myproject:aem-guides-myproject.analyse:slingosgifeature:aggregated-author:0.0.1-SNAPSHOT' finished : 0 warnings, 2 errors.
[ERROR] Configuration org.apache.sling.commons.log.LogManager.factory.config~asyncjssightly.org.apache.sling.commons.log.level : Value error does not match provided options
[ERROR] Configuration org.apache.sling.commons.log.LogManager.factory.config~myproject.org.apache.sling.commons.log.pattern : Property is not allowed
[ERROR] Analyser detected errors on feature 'com.adobe.aem.guides.myproject:aem-guides-myproject.analyse:slingosgifeature:aggregated-author:0.0.1-SNAPSHOT'. See log output for error messages.
[INFO] Starting analyzing feature 'com.adobe.aem.guides.myproject:aem-guides-myproject.analyse:slingosgifeature:aggregated-author.stage:0.0.1-SNAPSHOT'...
[INFO] - Executing Api Regions analyser task that checks that listed packages are actually exported [api-regions]...
[INFO] - Executing Api Regions check order analyser task [api-regions-check-order]...
[INFO] - Executing Bundle Import/Export Check [api-regions-exportsimports]...
[INFO] - Executing Api Regions cross-feature duplicate export task [api-regions-crossfeature-dups]...
[INFO] - Executing Configuration API analyser task [configuration-api]...
[INFO] - Executing Bundle Natice Code Check [bundle-nativecode]...
[INFO] - Executing Bundle Initial Content Check [bundle-content]...
[INFO] - Executing Bundle Resources Check [bundle-resources]...
[INFO] - Executing Requirements Capabilities check [requirements-capabilities]...
[INFO] Analyzing feature 'com.adobe.aem.guides.myproject:aem-guides-myproject.analyse:slingosgifeature:aggregated-author.stage:0.0.1-SNAPSHOT' finished : 0 warnings, 2 errors.
[ERROR] Configuration org.apache.sling.commons.log.LogManager.factory.config~asyncjssightly.org.apache.sling.commons.log.level : Value error does not match provided options
[ERROR] Configuration org.apache.sling.commons.log.LogManager.factory.config~myproject.org.apache.sling.commons.log.pattern : Property is not allowed
[ERROR] Analyser detected errors on feature 'com.adobe.aem.guides.myproject:aem-guides-myproject.analyse:slingosgifeature:aggregated-author.stage:0.0.1-SNAPSHOT'. See log output for error messages.
</code>```

ERROR is :

Failed to execute goal com.adobe.aem:aemanalyser-maven-plugin:0.9.2:analyse (default-analyse) on project aem-guides-myproject.analyse: One or more feature analyser(s) detected feature error(s), please read the plugin log for more details -> [Help 1]

I am using following command to create AEM project

```<code>mvn archetype:generate -B -DarchetypeGroupId=com.adobe.aem -DarchetypeArtifactId=aem-project-archetype -DarchetypeVersion=26 -DappTitle="My Citi Sites Project" -DappId="myproject" -DgroupId="com.adobe.aem.guides.myproject" -DartifactId="aem-guides-myproject" -Dversion="0.0.1-SNAPSHOT" -DaemVersion="cloud"
</code>```

Project is created sucessfully but the problem is while building project using  mvn clean install -PautoInstallSinglePackage getting above error.

答:
Here is the answer.

If you used the AEM Project Archetype to setup your project, make sure to adjust the property in the root Maven pom.xml like below.

I have changed property in root pom.xml, I have updated version of AEM Analyser to latest version.

Old version: [pom.xml]

```<code><properties>
    <aemanalyser.version>0.9.2</aemanalyser.version>
</properties>

 <build>
        <plugins> </plugins>
           <pluginManagement>
                <!-- AEM Analyser Plugin -->
                <plugin>
                    <groupId>com.adobe.aem</groupId>
                    <artifactId>aemanalyser-maven-plugin</artifactId>
                    <version>${aemanalyser.version}</version>
                    <extensions>true</extensions>
                </plugin>
        </pluginManagement>
    </build>
</code>```

Latest Version: [pom.xml]

```<code><properties>
    <aemanalyser.version>1.3.0</aemanalyser.version> <!-- Make sure to use the latest release -->
</properties>

 <build>
        <plugins> </plugins>
           <pluginManagement>
                <!-- AEM Analyser Plugin -->
                <plugin>
                    <groupId>com.adobe.aem</groupId>
                    <artifactId>aemanalyser-maven-plugin</artifactId>
                    <version>${aemanalyser.version}</version>
                    <extensions>true</extensions>
                </plugin>
        </pluginManagement>
    </build>
</code>```

Check latest version of AEM Analyser Maven Plugin https://mvnrepository.com/artifact/com.adobe.aem/aemanalyser-maven-plugin

Body:
[INFO] --- aemanalyser-maven-plugin:0.9.2:analyse (default-analyse) @ aem-guides-myproject.analyse ---
[INFO] Starting analyzing feature 'com.adobe.aem.guides.myproject:aem-guides-myproject.analyse:slingosgifeature:aggregated-author.prod:0.0.1-SNAPSHOT'...
[INFO] - Executing Api Regions analyser task that checks that listed packages are actually exported [api-regions]...
[INFO] - Executing Api Regions check order analyser task [api-regions-check-order]...
[INFO] - Executing Bundle Import/Export Check [api-regions-exportsimports]...
[INFO] - Executing Api Regions cross-feature duplicate export task [api-regions-crossfeature-dups]...
[INFO] - Executing Configuration API analyser task [configuration-api]...
[INFO] - Executing Bundle Natice Code Check [bundle-nativecode]...
[INFO] - Executing Bundle Initial Content Check [bundle-content]...
[INFO] - Executing Bundle Resources Check [bundle-resources]...
[INFO] - Executing Requirements Capabilities check [requirements-capabilities]...
[INFO] Analyzing feature 'com.adobe.aem.guides.myproject:aem-guides-myproject.analyse:slingosgifeature:aggregated-author.prod:0.0.1-SNAPSHOT' finished : 0 warnings, 3 errors.
[ERROR] Configuration org.apache.sling.commons.log.LogManager.factory.config~asyncjssightly.org.apache.sling.commons.log.level : Value error does not match provided options
[ERROR] Configuration org.apache.sling.commons.log.LogManager.factory.config~myproject.org.apache.sling.commons.log.level : Value error does not match provided options
[ERROR] Configuration org.apache.sling.commons.log.LogManager.factory.config~myproject.org.apache.sling.commons.log.pattern : Property is not allowed
[ERROR] Analyser detected errors on feature 'com.adobe.aem.guides.myproject:aem-guides-myproject.analyse:slingosgifeature:aggregated-author.prod:0.0.1-SNAPSHOT'. See log output for error messages.
[INFO] Starting analyzing feature 'com.adobe.aem.guides.myproject:aem-guides-myproject.analyse:slingosgifeature:aggregated-publish.prod:0.0.1-SNAPSHOT'...
[INFO] - Executing Api Regions analyser task that checks that listed packages are actually exported [api-regions]...
[INFO] - Executing Api Regions check order analyser task [api-regions-check-order]...
[INFO] - Executing Bundle Import/Export Check [api-regions-exportsimports]...
[INFO] - Executing Api Regions cross-feature duplicate export task [api-regions-crossfeature-dups]...
[INFO] - Executing Configuration API analyser task [configuration-api]...
[INFO] - Executing Bundle Natice Code Check [bundle-nativecode]...
[INFO] - Executing Bundle Initial Content Check [bundle-content]...
[INFO] - Executing Bundle Resources Check [bundle-resources]...
[INFO] - Executing Requirements Capabilities check [requirements-capabilities]...
[INFO] Analyzing feature 'com.adobe.aem.guides.myproject:aem-guides-myproject.analyse:slingosgifeature:aggregated-publish.prod:0.0.1-SNAPSHOT' finished : 0 warnings, 3 errors.
[ERROR] Configuration org.apache.sling.commons.log.LogManager.factory.config~asyncjssightly.org.apache.sling.commons.log.level : Value error does not match provided options
[ERROR] Configuration org.apache.sling.commons.log.LogManager.factory.config~myproject.org.apache.sling.commons.log.level : Value error does not match provided options
[ERROR] Configuration org.apache.sling.commons.log.LogManager.factory.config~myproject.org.apache.sling.commons.log.pattern : Property is not allowed
[ERROR] Analyser detected errors on feature 'com.adobe.aem.guides.myproject:aem-guides-myproject.analyse:slingosgifeature:aggregated-publish.prod:0.0.1-SNAPSHOT'. See log output for error messages.
[INFO] Starting analyzing feature 'com.adobe.aem.guides.myproject:aem-guides-myproject.analyse:slingosgifeature:aggregated-publish.stage:0.0.1-SNAPSHOT'...
[INFO] - Executing Api Regions analyser task that checks that listed packages are actually exported [api-regions]...
[INFO] - Executing Api Regions check order analyser task [api-regions-check-order]...
[INFO] - Executing Bundle Import/Export Check [api-regions-exportsimports]...
[INFO] - Executing Api Regions cross-feature duplicate export task [api-regions-crossfeature-dups]...
[INFO] - Executing Configuration API analyser task [configuration-api]...
[INFO] - Executing Bundle Natice Code Check [bundle-nativecode]...
[INFO] - Executing Bundle Initial Content Check [bundle-content]...
[INFO] - Executing Bundle Resources Check [bundle-resources]...
[INFO] - Executing Requirements Capabilities check [requirements-capabilities]...
[INFO] Analyzing feature 'com.adobe.aem.guides.myproject:aem-guides-myproject.analyse:slingosgifeature:aggregated-publish.stage:0.0.1-SNAPSHOT' finished : 0 warnings, 2 errors.
[ERROR] Configuration org.apache.sling.commons.log.LogManager.factory.config~asyncjssightly.org.apache.sling.commons.log.level : Value error does not match provided options
[ERROR] Configuration org.apache.sling.commons.log.LogManager.factory.config~myproject.org.apache.sling.commons.log.pattern : Property is not allowed
[ERROR] Analyser detected errors on feature 'com.adobe.aem.guides.myproject:aem-guides-myproject.analyse:slingosgifeature:aggregated-publish.stage:0.0.1-SNAPSHOT'. See log output for error messages.
[INFO] Starting analyzing feature 'com.adobe.aem.guides.myproject:aem-guides-myproject.analyse:slingosgifeature:aggregated-publish:0.0.1-SNAPSHOT'...
[INFO] - Executing Api Regions analyser task that checks that listed packages are actually exported [api-regions]...
[INFO] - Executing Api Regions check order analyser task [api-regions-check-order]...
[INFO] - Executing Bundle Import/Export Check [api-regions-exportsimports]...
[INFO] - Executing Api Regions cross-feature duplicate export task [api-regions-crossfeature-dups]...
[INFO] - Executing Configuration API analyser task [configuration-api]...
[INFO] - Executing Bundle Natice Code Check [bundle-nativecode]...
[INFO] - Executing Bundle Initial Content Check [bundle-content]...
[INFO] - Executing Bundle Resources Check [bundle-resources]...
[INFO] - Executing Requirements Capabilities check [requirements-capabilities]...
[INFO] Analyzing feature 'com.adobe.aem.guides.myproject:aem-guides-myproject.analyse:slingosgifeature:aggregated-publish:0.0.1-SNAPSHOT' finished : 0 warnings, 2 errors.
[ERROR] Configuration org.apache.sling.commons.log.LogManager.factory.config~asyncjssightly.org.apache.sling.commons.log.level : Value error does not match provided options
[ERROR] Configuration org.apache.sling.commons.log.LogManager.factory.config~myproject.org.apache.sling.commons.log.pattern : Property is not allowed
[ERROR] Analyser detected errors on feature 'com.adobe.aem.guides.myproject:aem-guides-myproject.analyse:slingosgifeature:aggregated-publish:0.0.1-SNAPSHOT'. See log output for error messages.
[INFO] Starting analyzing feature 'com.adobe.aem.guides.myproject:aem-guides-myproject.analyse:slingosgifeature:aggregated-author:0.0.1-SNAPSHOT'...
[INFO] - Executing Api Regions analyser task that checks that listed packages are actually exported [api-regions]...
[INFO] - Executing Api Regions check order analyser task [api-regions-check-order]...
[INFO] - Executing Bundle Import/Export Check [api-regions-exportsimports]...
[INFO] - Executing Api Regions cross-feature duplicate export task [api-regions-crossfeature-dups]...
[INFO] - Executing Configuration API analyser task [configuration-api]...
[INFO] - Executing Bundle Natice Code Check [bundle-nativecode]...
[INFO] - Executing Bundle Initial Content Check [bundle-content]...
[INFO] - Executing Bundle Resources Check [bundle-resources]...
[INFO] - Executing Requirements Capabilities check [requirements-capabilities]...
[INFO] Analyzing feature 'com.adobe.aem.guides.myproject:aem-guides-myproject.analyse:slingosgifeature:aggregated-author:0.0.1-SNAPSHOT' finished : 0 warnings, 2 errors.
[ERROR] Configuration org.apache.sling.commons.log.LogManager.factory.config~asyncjssightly.org.apache.sling.commons.log.level : Value error does not match provided options
[ERROR] Configuration org.apache.sling.commons.log.LogManager.factory.config~myproject.org.apache.sling.commons.log.pattern : Property is not allowed
[ERROR] Analyser detected errors on feature 'com.adobe.aem.guides.myproject:aem-guides-myproject.analyse:slingosgifeature:aggregated-author:0.0.1-SNAPSHOT'. See log output for error messages.
[INFO] Starting analyzing feature 'com.adobe.aem.guides.myproject:aem-guides-myproject.analyse:slingosgifeature:aggregated-author.stage:0.0.1-SNAPSHOT'...
[INFO] - Executing Api Regions analyser task that checks that listed packages are actually exported [api-regions]...
[INFO] - Executing Api Regions check order analyser task [api-regions-check-order]...
[INFO] - Executing Bundle Import/Export Check [api-regions-exportsimports]...
[INFO] - Executing Api Regions cross-feature duplicate export task [api-regions-crossfeature-dups]...
[INFO] - Executing Configuration API analyser task [configuration-api]...
[INFO] - Executing Bundle Natice Code Check [bundle-nativecode]...
[INFO] - Executing Bundle Initial Content Check [bundle-content]...
[INFO] - Executing Bundle Resources Check [bundle-resources]...
[INFO] - Executing Requirements Capabilities check [requirements-capabilities]...
[INFO] Analyzing feature 'com.adobe.aem.guides.myproject:aem-guides-myproject.analyse:slingosgifeature:aggregated-author.stage:0.0.1-SNAPSHOT' finished : 0 warnings, 2 errors.
[ERROR] Configuration org.apache.sling.commons.log.LogManager.factory.config~asyncjssightly.org.apache.sling.commons.log.level : Value error does not match provided options
[ERROR] Configuration org.apache.sling.commons.log.LogManager.factory.config~myproject.org.apache.sling.commons.log.pattern : Property is not allowed
[ERROR] Analyser detected errors on feature 'com.adobe.aem.guides.myproject:aem-guides-myproject.analyse:slingosgifeature:aggregated-author.stage:0.0.1-SNAPSHOT'. See log output for error messages.

ERROR is :

Failed to execute goal com.adobe.aem:aemanalyser-maven-plugin:0.9.2:analyse (default-analyse) on project aem-guides-myproject.analyse: One or more feature analyser(s) detected feature error(s), please read the plugin log for more details -> [Help 1]

I am using following command to create AEM project

mvn archetype:generate -B -DarchetypeGroupId=com.adobe.aem -DarchetypeArtifactId=aem-project-archetype -DarchetypeVersion=26 -DappTitle="My Citi Sites Project" -DappId="myproject" -DgroupId="com.adobe.aem.guides.myproject" -DartifactId="aem-guides-myproject" -Dversion="0.0.1-SNAPSHOT" -DaemVersion="cloud"

Project is created sucessfully but the problem is while building project using  mvn clean install -PautoInstallSinglePackage getting above error.

Body:
Here is the answer.

If you used the AEM Project Archetype to setup your project, make sure to adjust the property in the root Maven pom.xml like below.

I have changed property in root pom.xml, I have updated version of AEM Analyser to latest version.

Old version: [pom.xml]

<properties>
    <aemanalyser.version>0.9.2</aemanalyser.version>
</properties>

 <build>
        <plugins> </plugins>
           <pluginManagement>
                <!-- AEM Analyser Plugin -->
                <plugin>
                    <groupId>com.adobe.aem</groupId>
                    <artifactId>aemanalyser-maven-plugin</artifactId>
                    <version>${aemanalyser.version}</version>
                    <extensions>true</extensions>
                </plugin>
        </pluginManagement>
    </build>

Latest Version: [pom.xml]

<properties>
    <aemanalyser.version>1.3.0</aemanalyser.version> <!-- Make sure to use the latest release -->
</properties>

 <build>
        <plugins> </plugins>
           <pluginManagement>
                <!-- AEM Analyser Plugin -->
                <plugin>
                    <groupId>com.adobe.aem</groupId>
                    <artifactId>aemanalyser-maven-plugin</artifactId>
                    <version>${aemanalyser.version}</version>
                    <extensions>true</extensions>
                </plugin>
        </pluginManagement>
    </build>

Check latest version of AEM Analyser Maven Plugin https://mvnrepository.com/artifact/com.adobe.aem/aemanalyser-maven-plugin


问:
Python - How to access elements in a list of lists to get empty values
I'm reading in a csv file and need to parse it. I want to have a validation check that makes sure no cell/value in the file has any empty values. My problem is that I don't know how to check each element in a list in a list of lists

In essence, I have a sample file with headers STATE, COST, and ID

```<code>VA,2000,1
CA,1
NY,3784,1
</code>```

When parsing, I want a check that would throw an error on the second line since it's missing a value for the COST field.

Here is my code on how i'm approaching it:

```<code>with open('<hidden path url>', 'r') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    all_values = [line for line in csv_reader]
    headers = all_values[0]
    allocations = all_values[1:]

# Check for empty values
    if any(line == (None or '') for line in all_values):
        print("No column value can be empty")
    else:
        print("Success!")
</code>```

This is the result of print(all_values), aka the list of lists from which i'm trying to check each element for

```<code>[['state', 'cost', 'id'], ['VA', '2000' , '1'], ['CA', '', '1'], ['NY', '3784' , '1']]
</code>```

Going through the check should print "No column values can be empty" since there is an empty value in the row ['CA', '', '1']. I also don't want to define any extra function for the check.

Any help would be greatly appreciated!

答:
I believe your problem stems from syntax

line == (None or '')

Try

line == None or line == ''

Body:
I'm reading in a csv file and need to parse it. I want to have a validation check that makes sure no cell/value in the file has any empty values. My problem is that I don't know how to check each element in a list in a list of lists

In essence, I have a sample file with headers STATE, COST, and ID

VA,2000,1
CA,1
NY,3784,1

When parsing, I want a check that would throw an error on the second line since it's missing a value for the COST field.

Here is my code on how i'm approaching it:

with open('<hidden path url>', 'r') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    all_values = [line for line in csv_reader]
    headers = all_values[0]
    allocations = all_values[1:]

# Check for empty values
    if any(line == (None or '') for line in all_values):
        print("No column value can be empty")
    else:
        print("Success!")

This is the result of print(all_values), aka the list of lists from which i'm trying to check each element for

[['state', 'cost', 'id'], ['VA', '2000' , '1'], ['CA', '', '1'], ['NY', '3784' , '1']]

Going through the check should print "No column values can be empty" since there is an empty value in the row ['CA', '', '1']. I also don't want to define any extra function for the check.

Any help would be greatly appreciated!


问:
How to streamline concurrent saves in Yii2?
My application is exposing an API to sync-up data from an external system. The corresponding controller uses QueryParamAuth for authentication, and after some preliminary checks, populates an ActiveRecord model product with the posted data, and attempts to save it using $product->save()

The id field for this model was auto-generated via migrate/create as:

```<code>'id' => $this->primaryKey(),
</code>```

Now, in the initial sync, all the products data needs to be synced up from the external system on to the new application. Thus, external system is making multiple asynchronous calls to a URL exposed by the above controller. However, I'm repeatedly getting one of the following two SQL Errors during $product->save(), resulting in only ~250 records getting saved out of a test batch of ~375.

The first, and most common error that I'm getting is:

```<code>SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '7' for key 'PRIMARY'
The SQL being executed was: INSERT INTO `product` (`sku`, `name`, `quantity`, `created_at`, `updated_at`, `created_by`, `updated_by`, `id`) VALUES (NULL, 'Copies', 0, NOW(), NOW(), 3, 3, 7)
</code>```

Another error, that I'm getting towards the end of the batch is:

```<code>SQLSTATE[22003]: Numeric value out of range: 1264 Out of range value for column 'id' at row 1
The SQL being executed was: INSERT INTO `product` (`sku`, `name`, `quantity`, `created_at`, `updated_at`, `created_by`, `updated_by`, `id`) VALUES (NULL, 'Brochures', 0, NOW(), NOW(), 3, 3, 9223372036854775807)
</code>```

Please note that the table was initially empty, and the first record got created with id 1. The erratic jump in AUTO_INCREMENT id seems to happen randomly. The last saved record carries the id 1816263484.

What can I do to avoid these SQL errors?

答:
After raising the issue on Yii2 repository and much diagnostic discussion there, it turns out the following code in the model was responsible for it:

```<code>public function behaviors()
{
    return [
        ...
        'uuid' => [
            'class' => UUIDBehavior::className(),
            'column' => 'id',
        ],
    ];
}
</code>```

After removing the uuid behavior rule, the problem vanished.

Michal Hynčica was right is assuming that I'm setting the value of id, though I didn't know it was happening here.

Special thanks to lubosdz for attempting to help here as well as on GitHub.

Body:
My application is exposing an API to sync-up data from an external system. The corresponding controller uses QueryParamAuth for authentication, and after some preliminary checks, populates an ActiveRecord model product with the posted data, and attempts to save it using $product->save()

The id field for this model was auto-generated via migrate/create as:

'id' => $this->primaryKey(),

Now, in the initial sync, all the products data needs to be synced up from the external system on to the new application. Thus, external system is making multiple asynchronous calls to a URL exposed by the above controller. However, I'm repeatedly getting one of the following two SQL Errors during $product->save(), resulting in only ~250 records getting saved out of a test batch of ~375.

The first, and most common error that I'm getting is:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '7' for key 'PRIMARY'
The SQL being executed was: INSERT INTO `product` (`sku`, `name`, `quantity`, `created_at`, `updated_at`, `created_by`, `updated_by`, `id`) VALUES (NULL, 'Copies', 0, NOW(), NOW(), 3, 3, 7)

Another error, that I'm getting towards the end of the batch is:

SQLSTATE[22003]: Numeric value out of range: 1264 Out of range value for column 'id' at row 1
The SQL being executed was: INSERT INTO `product` (`sku`, `name`, `quantity`, `created_at`, `updated_at`, `created_by`, `updated_by`, `id`) VALUES (NULL, 'Brochures', 0, NOW(), NOW(), 3, 3, 9223372036854775807)

Please note that the table was initially empty, and the first record got created with id 1. The erratic jump in AUTO_INCREMENT id seems to happen randomly. The last saved record carries the id 1816263484.

What can I do to avoid these SQL errors?

Body:
After raising the issue on Yii2 repository and much diagnostic discussion there, it turns out the following code in the model was responsible for it:

public function behaviors()
{
    return [
        ...
        'uuid' => [
            'class' => UUIDBehavior::className(),
            'column' => 'id',
        ],
    ];
}

After removing the uuid behavior rule, the problem vanished.

Michal Hynčica was right is assuming that I'm setting the value of id, though I didn't know it was happening here.

Special thanks to lubosdz for attempting to help here as well as on GitHub.


问:
for loop to clean multiple dataframes
Here's my code:

```<code>library(PNADcIBGE)
#DOWNLOAD DATABASES#
data2018q1 <- get_pnadc(year = 2018, quarter = 1, vars = c("UF", "Capital", "V1022", "V2007", "V2009", "V2010", "V3009A", "VD3004", "VD4001", "VD4004", "V4001", "V4003", "V4005", "V4010", "V4002", "V4012", "V403322","VD4019", "VD4020"), labels = FALSE, deflator = TRUE, design = FALSE, defyear = 2018, defperiod = 1)
data2018q2 <- get_pnadc(year = 2018, quarter = 2, vars = c("UF", "Capital", "V1022", "V2007", "V2009", "V2010", "V3009A", "VD3004", "VD4001", "VD4004", "V4001", "V4003", "V4005", "V4010", "V4002", "V4012", "V403322","VD4019", "VD4020"), labels = FALSE, deflator = TRUE, design = FALSE, defyear = 2018, defperiod = 2)
data2018q3 <- get_pnadc(year = 2018, quarter = 3, vars = c("UF", "Capital", "V1022", "V2007", "V2009", "V2010", "V3009A", "VD3004", "VD4001", "VD4004", "V4001", "V4003", "V4005", "V4010", "V4002", "V4012", "V403322","VD4019", "VD4020"), labels = FALSE, deflator = TRUE, design = FALSE, defyear = 2018, defperiod = 3)
data2018q4 <- get_pnadc(year = 2018, quarter = 4, vars = c("UF", "Capital", "V1022", "V2007", "V2009", "V2010", "V3009A", "VD3004", "VD4001", "VD4004", "V4001", "V4003", "V4005", "V4010", "V4002", "V4012", "V403322","VD4019", "VD4020"), labels = FALSE, deflator = TRUE, design = FALSE, defyear = 2018, defperiod = 4)

#CLEAN DATABASES#

data_list <- list(data_2018q1,data_2018q2,data_2018q3,data_2018q4,data_2019q1,data_2019q2,data_2019q3,data_2019q4,data_2020q1,data_2020q2,data_2020q3,data_2020q4,data_2021q1,data_2021q2,data_2021q3)
</code>```

I'm trying to use a log10 for the variable VD4020 for all dataframes within data_lis. After log10, I want to do other things, such as renaming columns, adding columns and other cleaning stuff. I tried using lapply with no success, and couldnt do a For loop either. The way I was doing it was by manually going into each dataframe and doing a sub data frame, such as

```<code>data_2018q1 <- subset.data.frame(data_2018q2, VD4020!="NA")
data_2018q2 <- subset.data.frame(data_2018q2, VD4020!="NA")
data_2018q3 <- subset.data.frame(data_2018q2, VD4020!="NA")

data_2018q1$VD4020 <- log(data_2018q1$VD4020)
data_2018q2$VD4020 <- log(data_2018q2$VD4020)
data_2018q3$VD4020 <- log(data_2018q3$VD4020)
</code>```

And so on with each and every command. This is really time consuming as I need to do it with 15 dataframes.

答:
Two thoughts.

You didn't ask, but it may be easier to load the data this way:

datalist <- lapply(setNames(1:4, paste0("data_2018q", 1:4)), function(qtr) {
  get_pnadc(year = 2018, quarter = qtr, vars = c("UF", "Capital", "V1022", "V2007", "V2009", "V2010", "V3009A", "VD3004", "VD4001", "VD4004", "V4001", "V4003", "V4005", "V4010", "V4002", "V4012", "V403322","VD4019", "VD4020"), labels = FALSE, deflator = TRUE, design = FALSE, defyear = 2018, defperiod = 1)
})

```
</li>
<li><p>Log-10 on one column.  FYI, <code>!= "NA"</code> is doing string comparisons, you may want <code>!is.na(.)</code>.</p>
<pre class="lang-r prettyprint-override"><code>datalist2 <- lapply(datalist, function(dat) {
  dat$VD4020[!is.na(dat$VD4020)] <- log10(dat$VD4020[!is.na(dat$VD4020)])
  dat
})
</code>```

or write back to datalist <- lapply(...), but for learning/debugging I often like to break it apart until I am confident about the process.

Edit: for multi-years, you can auto-list it with:

eg <- expand.grid(q = 1:4, y = 2018:2021)[,2:1] # so that the 'q' column goes more quickly
eg
#       y q
# 1  2018 1
# 2  2018 2
# 3  2018 3
# 4  2018 4
# 5  2019 1
# 6  2019 2
# 7  2019 3
# 8  2019 4
# 9  2020 1
# 10 2020 2
# 11 2020 3
# 12 2020 4
# 13 2021 1
# 14 2021 2
# 15 2021 3
# 16 2021 4
```
<p>You said you only need through 2021q3, so we can drop row 16:</p>
<pre class="lang-r prettyprint-override"><code>nms <- with(eg[-16,], sprintf("data_%sq%s", y, q))
nms
#  [1] "data_2018q1" "data_2018q2" "data_2018q3" "data_2018q4" "data_2019q1" "data_2019q2" "data_2019q3" "data_2019q4" "data_2020q1"
# [10] "data_2020q2" "data_2020q3" "data_2020q4" "data_2021q1" "data_2021q2" "data_2021q3"
datalist <- setNames(Map(function(yr, qtr) {
  get_pnadc(year = yr, quarter = qtr, vars = c("UF", "Capital", "V1022", "V2007", "V2009", "V2010", "V3009A", "VD3004", "VD4001", "VD4004", "V4001", "V4003", "V4005", "V4010", "V4002", "V4012", "V403322","VD4019", "VD4020"), labels = FALSE, deflator = TRUE, design = FALSE, defyear = yr, defperiod = 1)
}, eg$y, eg$q), nms)
</code>```

Title: for loop to clean multiple dataframes

Body:
Here's my code:

library(PNADcIBGE)
#DOWNLOAD DATABASES#
data2018q1 <- get_pnadc(year = 2018, quarter = 1, vars = c("UF", "Capital", "V1022", "V2007", "V2009", "V2010", "V3009A", "VD3004", "VD4001", "VD4004", "V4001", "V4003", "V4005", "V4010", "V4002", "V4012", "V403322","VD4019", "VD4020"), labels = FALSE, deflator = TRUE, design = FALSE, defyear = 2018, defperiod = 1)
data2018q2 <- get_pnadc(year = 2018, quarter = 2, vars = c("UF", "Capital", "V1022", "V2007", "V2009", "V2010", "V3009A", "VD3004", "VD4001", "VD4004", "V4001", "V4003", "V4005", "V4010", "V4002", "V4012", "V403322","VD4019", "VD4020"), labels = FALSE, deflator = TRUE, design = FALSE, defyear = 2018, defperiod = 2)
data2018q3 <- get_pnadc(year = 2018, quarter = 3, vars = c("UF", "Capital", "V1022", "V2007", "V2009", "V2010", "V3009A", "VD3004", "VD4001", "VD4004", "V4001", "V4003", "V4005", "V4010", "V4002", "V4012", "V403322","VD4019", "VD4020"), labels = FALSE, deflator = TRUE, design = FALSE, defyear = 2018, defperiod = 3)
data2018q4 <- get_pnadc(year = 2018, quarter = 4, vars = c("UF", "Capital", "V1022", "V2007", "V2009", "V2010", "V3009A", "VD3004", "VD4001", "VD4004", "V4001", "V4003", "V4005", "V4010", "V4002", "V4012", "V403322","VD4019", "VD4020"), labels = FALSE, deflator = TRUE, design = FALSE, defyear = 2018, defperiod = 4)

#CLEAN DATABASES#

data_list <- list(data_2018q1,data_2018q2,data_2018q3,data_2018q4,data_2019q1,data_2019q2,data_2019q3,data_2019q4,data_2020q1,data_2020q2,data_2020q3,data_2020q4,data_2021q1,data_2021q2,data_2021q3)

I'm trying to use a log10 for the variable VD4020 for all dataframes within data_lis. After log10, I want to do other things, such as renaming columns, adding columns and other cleaning stuff. I tried using lapply with no success, and couldnt do a For loop either. The way I was doing it was by manually going into each dataframe and doing a sub data frame, such as

data_2018q1 <- subset.data.frame(data_2018q2, VD4020!="NA")
data_2018q2 <- subset.data.frame(data_2018q2, VD4020!="NA")
data_2018q3 <- subset.data.frame(data_2018q2, VD4020!="NA")

data_2018q1$VD4020 <- log(data_2018q1$VD4020)
data_2018q2$VD4020 <- log(data_2018q2$VD4020)
data_2018q3$VD4020 <- log(data_2018q3$VD4020)

And so on with each and every command. This is really time consuming as I need to do it with 15 dataframes.

Body:
Two thoughts.

You didn't ask, but it may be easier to load the data this way:

datalist <- lapply(setNames(1:4, paste0("data_2018q", 1:4)), function(qtr) {
  get_pnadc(year = 2018, quarter = qtr, vars = c("UF", "Capital", "V1022", "V2007", "V2009", "V2010", "V3009A", "VD3004", "VD4001", "VD4004", "V4001", "V4003", "V4005", "V4010", "V4002", "V4012", "V403322","VD4019", "VD4020"), labels = FALSE, deflator = TRUE, design = FALSE, defyear = 2018, defperiod = 1)
})

Log-10 on one column.  FYI, != "NA" is doing string comparisons, you may want !is.na(.).

datalist2 <- lapply(datalist, function(dat) {
  dat$VD4020[!is.na(dat$VD4020)] <- log10(dat$VD4020[!is.na(dat$VD4020)])
  dat
})

or write back to datalist <- lapply(...), but for learning/debugging I often like to break it apart until I am confident about the process.

Edit: for multi-years, you can auto-list it with:

eg <- expand.grid(q = 1:4, y = 2018:2021)[,2:1] # so that the 'q' column goes more quickly
eg
#       y q
# 1  2018 1
# 2  2018 2
# 3  2018 3
# 4  2018 4
# 5  2019 1
# 6  2019 2
# 7  2019 3
# 8  2019 4
# 9  2020 1
# 10 2020 2
# 11 2020 3
# 12 2020 4
# 13 2021 1
# 14 2021 2
# 15 2021 3
# 16 2021 4

You said you only need through 2021q3, so we can drop row 16:

nms <- with(eg[-16,], sprintf("data_%sq%s", y, q))
nms
#  [1] "data_2018q1" "data_2018q2" "data_2018q3" "data_2018q4" "data_2019q1" "data_2019q2" "data_2019q3" "data_2019q4" "data_2020q1"
# [10] "data_2020q2" "data_2020q3" "data_2020q4" "data_2021q1" "data_2021q2" "data_2021q3"
datalist <- setNames(Map(function(yr, qtr) {
  get_pnadc(year = yr, quarter = qtr, vars = c("UF", "Capital", "V1022", "V2007", "V2009", "V2010", "V3009A", "VD3004", "VD4001", "VD4004", "V4001", "V4003", "V4005", "V4010", "V4002", "V4012", "V403322","VD4019", "VD4020"), labels = FALSE, deflator = TRUE, design = FALSE, defyear = yr, defperiod = 1)
}, eg$y, eg$q), nms)


问:
Eclipse, regular expression search and replace
In eclipse, is it possible to use the matched search string as part of the replace string when performing a regular expression search and replace?

Basically, I want to replace all occurrences of

```<code>variableName.someMethod()
</code>```

with:

```<code>((TypeName)variableName.someMethod())
</code>```

Where variableName can be any variable name at all.

In sed I could use something like:

```<code>s/[a-zA-Z]+\.someMethod\(\)/((TypeName)&)/g
</code>```

That is, & represents the matched search string. Is there something similar in Eclipse?

Thanks!

答:
At least at STS (SpringSource Tool Suite) groups are numbered starting form 0, so replace string will be</p>

```<code>replace: ((TypeName)$0)
</code>```

Body:
In eclipse, is it possible to use the matched search string as part of the replace string when performing a regular expression search and replace?

Basically, I want to replace all occurrences of

variableName.someMethod()

with:

((TypeName)variableName.someMethod())

Where variableName can be any variable name at all.

In sed I could use something like:

s/[a-zA-Z]+\.someMethod\(\)/((TypeName)&)/g

That is, & represents the matched search string. Is there something similar in Eclipse?

Thanks!

Body:
At least at STS (SpringSource Tool Suite) groups are numbered starting form 0, so replace string will be

replace: ((TypeName)$0)

ContentLicense: CC BY-SA 3.0


问:
How to add manufacturer specific data in advertise packets for nordic nrf82532
I have a need to code in manufacture specific data in NRF ble advertisement packets> I need to do so to make an additional ble test kit for testing my main device(which is probably filtering blue tooth packets based on company id and specific data ).

I have tried to modify the sample from the SDK BLE-Peripheral_UART (deemed to be easiest to fit my need). However I bumped into problem of adding company specific data.

Below is how i added my data

```<code>uint8_t COMPANY_ID[] = { 0x99, 0x99};
uint8_t COMPANY_DATA[] = {0x76, 0x61, 0x6e, 0x74, 0x72, 0x6f, 0x6e, 0x00};

static const struct bt_data ad[] = {
    BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)),
    BT_DATA(BT_DATA_MANUFACTURER_DATA, COMPANY_ID, 2),
    BT_DATA(BT_DATA_MANUFACTURER_DATA,COMPANY_DATA,8),
    BT_DATA(BT_DATA_NAME_COMPLETE, DEVICE_NAME, DEVICE_NAME_LEN),
};
</code>```

The result however shown something like this
[![enter image description here][1]][1]
But I need it to be like this

[![enter image description here][2]][2]

I believe somehow I have used the wrong function... but there is no simple api (the documentation was mind-boggling) for me to read. Need some help for pointing me in the direction where i can get the information from or any help

Thanks
[1]: https://i.stack.imgur.com/n3Vv3.png
[2]: https://i.stack.imgur.com/qKPHD.png

EDIT

Btw in response to fabik111 queries, I am using

Nordic UART Bridge Service (NUS) sample from SDK v1.7.0

I am passing the ad (advertisement) and scan response (sd) data by err = bt_le_adv_start(BT_LE_ADV_CONN, ad, ARRAY_SIZE(ad), sd, ARRAY_SIZE(sd));

答:
I believe I might have got it working ...</p>
```<code>uint8_t COMPANY_ID[] = { 0x99, 0x99, 0x76, 0x61, 0x6e, 0x74, 0x72, 0x6f, 0x6e, 0x00};

static const struct bt_data ad[] = {
    BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)),
    BT_DATA(BT_DATA_MANUFACTURER_DATA, COMPANY_ID, 10),
    BT_DATA(BT_DATA_NAME_COMPLETE, DEVICE_NAME, DEVICE_NAME_LEN),
};
</code>```

Body:
I have a need to code in manufacture specific data in NRF ble advertisement packets> I need to do so to make an additional ble test kit for testing my main device(which is probably filtering blue tooth packets based on company id and specific data ).

I have tried to modify the sample from the SDK BLE-Peripheral_UART (deemed to be easiest to fit my need). However I bumped into problem of adding company specific data.

Below is how i added my data

uint8_t COMPANY_ID[] = { 0x99, 0x99};
uint8_t COMPANY_DATA[] = {0x76, 0x61, 0x6e, 0x74, 0x72, 0x6f, 0x6e, 0x00};

static const struct bt_data ad[] = {
    BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)),
    BT_DATA(BT_DATA_MANUFACTURER_DATA, COMPANY_ID, 2),
    BT_DATA(BT_DATA_MANUFACTURER_DATA,COMPANY_DATA,8),
    BT_DATA(BT_DATA_NAME_COMPLETE, DEVICE_NAME, DEVICE_NAME_LEN),
};

The result however shown something like this
[![enter image description here][1]][1]
But I need it to be like this

[![enter image description here][2]][2]

I believe somehow I have used the wrong function... but there is no simple api (the documentation was mind-boggling) for me to read. Need some help for pointing me in the direction where i can get the information from or any help

Thanks
[1]: https://i.stack.imgur.com/n3Vv3.png
[2]: https://i.stack.imgur.com/qKPHD.png

EDIT

Btw in response to fabik111 queries, I am using

Nordic UART Bridge Service (NUS) sample from SDK v1.7.0

I am passing the ad (advertisement) and scan response (sd) data by err = bt_le_adv_start(BT_LE_ADV_CONN, ad, ARRAY_SIZE(ad), sd, ARRAY_SIZE(sd));

Body:
I believe I might have got it working ...

uint8_t COMPANY_ID[] = { 0x99, 0x99, 0x76, 0x61, 0x6e, 0x74, 0x72, 0x6f, 0x6e, 0x00};

static const struct bt_data ad[] = {
    BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)),
    BT_DATA(BT_DATA_MANUFACTURER_DATA, COMPANY_ID, 10),
    BT_DATA(BT_DATA_NAME_COMPLETE, DEVICE_NAME, DEVICE_NAME_LEN),
};


问:
Looped Regression Model Returning Single Result, Instead of Multiple Outputs
I am running a ridge regression model over some bootstrapped resampled data, for the sake of this question, let's say two bootstrapped samples
in a list of dataframes. However, when I iterate over the list of dataframes, I get only one output, instead of two outputs corresponding
to each dataframe in the list. Not sure what else I am missing in my code.

Below are the sample datasets

```<code>import pandas as pd
import numpy as np

# the resampled datasets
d1 = {'v1': [2.5, 4.5, 3.3, 4.0, 3.8, 2.5, 4.5, 3.3, 4.0, 3.8, 2.5, 4.5, 3.3, 4.0, 3.8, 2.5, 4.5, 3.3, 4.0, 3.8],
      'v2': [3.5, 3.8, 2.5, 4.0, 4.0, 3.5, 3.8, 2.5, 4.0, 4.0, 3.5, 3.8, 2.5, 4.0, 4.0, 3.8, 3.89, 2.75, 4.5, 4.25],
      'v3': [4.5, 3.8, 3.5, 4.2, 4.3, 1.5, 2.98, 3.5, 3.5, 4.5, 3.8, 3.89, 2.75, 4.5, 4.25, 3.55, 3.85, 2.98, 4.05, 4.50]}
df1 = pd.DataFrame(d1)

d2 = {'v1': [2.6, 4.0, 3.3, 4.0, 3.0, 2.5, 4.5, 3.3, 4.0, 3.8, 4.5, 3.8, 3.5, 4.2, 4.3, 4.25, 3.55, 3.85, 2.98, 4.05],
      'v2': [3.8, 3.89, 2.75, 4.5, 4.25, 3.55, 3.85, 2.98, 4.05, 4.50, 3.5, 2.98, 3.5, 3.25, 4.25, 4.0, 4.0, 3.5, 3.8, 2.5],
      'v3': [4.0, 3.85, 3.75, 4.0, 4.73, 3.5, 2.98, 3.5, 3.25, 4.25, 3.3, 4.0, 3.8, 2.5, 4.5, 3.3, 4.0, 3.8, 2.5, 4.5]}
df2 = pd.DataFrame(d2)

dflst = [df1, df2]
</code>```

and the codes I am running on them.

```<code>from sklearn.linear_model import Ridge

# function to run ridge regression
def ridgereg(data, ynum=1):

    y = np.asarray(data.iloc[:, 0:ynum])
    X = np.asarray(data.iloc[:, ynum:])

    model = Ridge(alpha=1.0).fit(X,y)
    return model.coef_

# iterate over list of dfs
for x in range(1, len(dflst)):
    resampled_model = {}
    resampled_model[x] = ridgereg(dflst[x], ynum=1)

print(resampled_model)
</code>```

答:
In the for loop, you are creating a new dict at each iteration, throwing the previously made dict away.

Try (using enumerate):

resampled_model = {} # note that it is outside the loop
for i, df in enumerate(dflst, start=1):
    resampled_model[i] = ridgereg(df, ynum=1)

print(resampled_model)
# {1: array([[0.35603345, 0.1373456 ]]), 2: array([[ 0.08019198, -0.10895105]])}
```
<p>Instead of the <code>for</code> loop, you can use dict comprehension:</p>
<pre class="lang-py prettyprint-override"><code>resampled_model = {i: ridgereg(df, ynum=1) for i, df in enumerate(dflst, start=1)}
</code>```

Body:
I am running a ridge regression model over some bootstrapped resampled data, for the sake of this question, let's say two bootstrapped samples
in a list of dataframes. However, when I iterate over the list of dataframes, I get only one output, instead of two outputs corresponding
to each dataframe in the list. Not sure what else I am missing in my code.

Below are the sample datasets

import pandas as pd
import numpy as np

# the resampled datasets
d1 = {'v1': [2.5, 4.5, 3.3, 4.0, 3.8, 2.5, 4.5, 3.3, 4.0, 3.8, 2.5, 4.5, 3.3, 4.0, 3.8, 2.5, 4.5, 3.3, 4.0, 3.8],
      'v2': [3.5, 3.8, 2.5, 4.0, 4.0, 3.5, 3.8, 2.5, 4.0, 4.0, 3.5, 3.8, 2.5, 4.0, 4.0, 3.8, 3.89, 2.75, 4.5, 4.25],
      'v3': [4.5, 3.8, 3.5, 4.2, 4.3, 1.5, 2.98, 3.5, 3.5, 4.5, 3.8, 3.89, 2.75, 4.5, 4.25, 3.55, 3.85, 2.98, 4.05, 4.50]}
df1 = pd.DataFrame(d1)

d2 = {'v1': [2.6, 4.0, 3.3, 4.0, 3.0, 2.5, 4.5, 3.3, 4.0, 3.8, 4.5, 3.8, 3.5, 4.2, 4.3, 4.25, 3.55, 3.85, 2.98, 4.05],
      'v2': [3.8, 3.89, 2.75, 4.5, 4.25, 3.55, 3.85, 2.98, 4.05, 4.50, 3.5, 2.98, 3.5, 3.25, 4.25, 4.0, 4.0, 3.5, 3.8, 2.5],
      'v3': [4.0, 3.85, 3.75, 4.0, 4.73, 3.5, 2.98, 3.5, 3.25, 4.25, 3.3, 4.0, 3.8, 2.5, 4.5, 3.3, 4.0, 3.8, 2.5, 4.5]}
df2 = pd.DataFrame(d2)

dflst = [df1, df2]

and the codes I am running on them.

from sklearn.linear_model import Ridge

# function to run ridge regression
def ridgereg(data, ynum=1):

    y = np.asarray(data.iloc[:, 0:ynum])
    X = np.asarray(data.iloc[:, ynum:])

    model = Ridge(alpha=1.0).fit(X,y)
    return model.coef_

# iterate over list of dfs
for x in range(1, len(dflst)):
    resampled_model = {}
    resampled_model[x] = ridgereg(dflst[x], ynum=1)

print(resampled_model)

Body:
In the for loop, you are creating a new dict at each iteration, throwing the previously made dict away.

Try (using enumerate):

resampled_model = {} # note that it is outside the loop
for i, df in enumerate(dflst, start=1):
    resampled_model[i] = ridgereg(df, ynum=1)

print(resampled_model)
# {1: array([[0.35603345, 0.1373456 ]]), 2: array([[ 0.08019198, -0.10895105]])}

Instead of the for loop, you can use dict comprehension:

resampled_model = {i: ridgereg(df, ynum=1) for i, df in enumerate(dflst, start=1)}


问:
Readline filtering answers
I want to filter answers in the built-in module in nodejs called "readline" which allows you to prompt a user and ask some question, yk things like that, I've made a js file for my users to easily understand what to do on my discord bot. Installing dependencies, git pull, ye it explains it. But I want it to only accept certain answers. Here is the code for you to understand it

const readline = require("readline")
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });

console.log("Hello! Welcome to the startup file of my bot dio! You can use this file to easily install,uninstall and update files!")
console.log('Type npm install if you want to install the needed packages. ')
console.log('Type git pull to update the whole folder but it needs a token and username so ye just enter it.')
console.log('Type node index.js of you want to start the bot')

rl.question('Now, what do you want to do? ', (answer) => {
    const { execSync } = require('child_process')
    const start = () => {
        execSync(`${answer}`, { stdio: "inherit" });
      }
start();

rl.close();
  });
```

I want this code to only accept the given answers I provided (npm install, git pull, node index.js)

答:
I finally got it! I just used if arrays lol . I completely forgot about it.
Here's the code

const readline = require("readline")
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });
const answers = ['npm install', 'git pull', 'node index.js']

console.log("Hello! Welcome to the startup file of my bot dio! You can use this file to easily install,uninstall and update files!")
console.log('Type npm install if you want to install the needed packages. ')
console.log('Type git pull to update the whole folder but it needs a token and username so ye just enter it.')
console.log('Type node index.js of you want to start the bot')

rl.question('What do you want to do? ', (answer) => {
  const { execSync } = require('child_process');
    if(answer === answers[0]){
        console.log('Installing packages...')
        execSync('npm install', {stdio: 'inherit'})
        console.log('Installed!')
    }
    else if(answer === answers[1]){
        console.log('Updating...')
        execSync('git pull', {stdio: 'inherit'})
        console.log('Updated!')
    }
    else if(answer === answers[2]){
        console.log('Starting...')
        execSync('node index.js', {stdio: 'inherit'})
        console.log('Started!')
    }
    else{
        rl.setPrompt('Wrong input! Try again!')
        rl.prompt()
    }
    rl.close();
});
```

Title: Readline filtering answers

Body:
I want to filter answers in the built-in module in nodejs called "readline" which allows you to prompt a user and ask some question, yk things like that, I've made a js file for my users to easily understand what to do on my discord bot. Installing dependencies, git pull, ye it explains it. But I want it to only accept certain answers. Here is the code for you to understand it

const readline = require("readline")
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });

console.log("Hello! Welcome to the startup file of my bot dio! You can use this file to easily install,uninstall and update files!")
console.log('Type npm install if you want to install the needed packages. ')
console.log('Type git pull to update the whole folder but it needs a token and username so ye just enter it.')
console.log('Type node index.js of you want to start the bot')

rl.question('Now, what do you want to do? ', (answer) => {
    const { execSync } = require('child_process')
    const start = () => {
        execSync(`${answer}`, { stdio: "inherit" });
      }
start();

rl.close();
  });

I want this code to only accept the given answers I provided (npm install, git pull, node index.js)


问:
A href pointed to nowhere added # to url
I have a href which pointed to #

```<code><a href="#" id="bla" >Bla<a>
</code>```

I have onclick function which displaying popup on click on that a href.

```<code>function doingClick()
{
   //display popup
   return false;
}
</code>```

But after click symbol # every time added to the url in browser.

So for example if url was like that before I click on my link http://mywebsite.com

But after click on a href the url looking like that: http://mywebsite.com#

Is there any way to avoid such behavior?

答:
The url is not pointed to nowhere. The URL is a relative URL to # in other words the URL resolves to <current_url># which in this case is http://mywebsite.com#.

To avoid this behaviour, you have to change the URL.

If you have a onclick-handler that returns false, then that should prevent the link being active :

```<code><a href="#" onclick="return doingClick();">link</a>
</code>```

You can also use javascript:void(0) as the link href.

In either case, be mindful of the decreased accessibility of your site when you use javascript to access some parts of it. Those users that have javascript disabled, doesn't have javascript enabled browsers or use a screenreader or other accessibilty tools may not be able to use the site.

Body:
I have a href which pointed to #

Bla

I have onclick function which displaying popup on click on that a href.

function doingClick()
{
   //display popup
   return false;
}

But after click symbol # every time added to the url in browser.

So for example if url was like that before I click on my link http://mywebsite.com

But after click on a href the url looking like that: http://mywebsite.com#

Is there any way to avoid such behavior?

Body:
The url is not pointed to nowhere. The URL is a relative URL to # in other words the URL resolves to <current_url># which in this case is http://mywebsite.com#.

To avoid this behaviour, you have to change the URL.

If you have a onclick-handler that returns false, then that should prevent the link being active :

<a href="#" onclick="return doingClick();">link</a>

You can also use javascript:void(0) as the link href.

In either case, be mindful of the decreased accessibility of your site when you use javascript to access some parts of it. Those users that have javascript disabled, doesn't have javascript enabled browsers or use a screenreader or other accessibilty tools may not be able to use the site.


问:
How to permanently save Picked Time in TimePicker Flutter
I've tried to save picked time permanently by using shared preferences inside future asynchronous with set string and get string inside load_reftime(). Also in Shared Preferences I add selected Time in a set string with .tostring() and I add TimeOfDay.from DateTime(DateTime.parse(prefs.getString(_time))); with DateTime.parse to make sure the picked time is saved and loaded permanently by the time I restart my emulator app.
But the result is the same.

I need advice and a solution to save the selected time to SharedPreferences and change it only when I decide to change Thank you.

For the code:
https://drive.google.com/file/d/1BYftWqgBGc7K-ggo1iwrcCwbohAotuS3/view?usp=sharing

答:
While saving into Sharedpreferences,
save it like this:

```<code>preferences.setString('time', DateTime(
  DateTime.now().year,
  DateTime.now().month,
  DateTime.now().day,
  endTime!.hour, // TimeOfDay
  endTime!.minute, //TimeOfDay
).toString());
</code>```

And for getting,

```<code> time = TimeOfDay.fromDateTime(
      DateTime.parse(preferences.getString('time')!));
</code>```

This should fix it!

Body:
While saving into Sharedpreferences,
save it like this:

preferences.setString('time', DateTime(
  DateTime.now().year,
  DateTime.now().month,
  DateTime.now().day,
  endTime!.hour, // TimeOfDay
  endTime!.minute, //TimeOfDay
).toString());

And for getting,

 time = TimeOfDay.fromDateTime(
      DateTime.parse(preferences.getString('time')!));

This should fix it!


问:
error NG6002: Appears in the NgModule.imports of AppModule, but itself has errors
I am having angular 12 in my local and building project which runs fine without any error.

My local setup:

```<code>Angular CLI: 12.0.5
Node: 12.16.3
Package Manager: npm 6.14.4
OS: win32 x64
Angular: 12.0.5
</code>```

But while building my project on the linux server it is giving this error with nothing much to work with.

Server setup:

```<code>Angular CLI: 12.0.5
Node: 14.18.1
Package Manager: npm 6.14.15
OS: linux x64
Angular: 12.0.5
</code>```
```<code>Error: src/app/app-routing.module.ts:34:14 - error NG6002: Appears in the NgModule.imports of AppModule, but itself has errors
34 export class AppRoutingModule { }
</code>```

app.module.ts

```<code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { HeaderComponent } from './header/header.component';
import { FooterComponent } from './footer/footer.component';
import { NotifyFormComponent } from './notify-form/notify-form.component';
import { LoginComponent } from './login/login.component';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    HeaderComponent,
    FooterComponent,
    NotifyFormComponent,
    LoginComponent
  ],
  imports: [
    AppRoutingModule,
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

app-routing.module.ts

```<code>import { LoginComponent } from './login/login.component';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { NotifyFormComponent } from './notify-form/notify-form.component';
import { HomeComponent } from './home/home.component';

const routes: Routes = [
  {path:'',redirectTo:'/',pathMatch: 'full'},
  {
    path:'',
    component: HomeComponent,
    children:[

    ]
  },
  {
    path:'notify',
    component: NotifyFormComponent
  },
  {
    path:'login',
    component: LoginComponent
  }
  // {
  //   path:'**',
  //   component: HomeComponent
  // }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

</code>```

tsconfig.json

```<code>{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2017",
    "module": "es2020",
    "lib": [
      "es2018",
      "dom"
    ]
  },
  "angularCompilerOptions": {
    "enableI18nLegacyMessageIdFormat": false,
    "strictInjectionParameters": true,
    "strictInputAccessModifiers": true,
    "strictTemplates": true
  }
}
</code>```

Please help me if I am doing anything horribly wrong here. It is just a simple project to test with. Thanks a lot in advance.

答: Try npm version should be > 8.1.0 and node version should be > v16.13.0</p>

Body:
I am having angular 12 in my local and building project which runs fine without any error.

My local setup:

Angular CLI: 12.0.5
Node: 12.16.3
Package Manager: npm 6.14.4
OS: win32 x64
Angular: 12.0.5

But while building my project on the linux server it is giving this error with nothing much to work with.

Server setup:

Angular CLI: 12.0.5
Node: 14.18.1
Package Manager: npm 6.14.15
OS: linux x64
Angular: 12.0.5

Error: src/app/app-routing.module.ts:34:14 - error NG6002: Appears in the NgModule.imports of AppModule, but itself has errors
34 export class AppRoutingModule { }

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { HeaderComponent } from './header/header.component';
import { FooterComponent } from './footer/footer.component';
import { NotifyFormComponent } from './notify-form/notify-form.component';
import { LoginComponent } from './login/login.component';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    HeaderComponent,
    FooterComponent,
    NotifyFormComponent,
    LoginComponent
  ],
  imports: [
    AppRoutingModule,
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app-routing.module.ts

import { LoginComponent } from './login/login.component';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { NotifyFormComponent } from './notify-form/notify-form.component';
import { HomeComponent } from './home/home.component';

const routes: Routes = [
  {path:'',redirectTo:'/',pathMatch: 'full'},
  {
    path:'',
    component: HomeComponent,
    children:[

    ]
  },
  {
    path:'notify',
    component: NotifyFormComponent
  },
  {
    path:'login',
    component: LoginComponent
  }
  // {
  //   path:'**',
  //   component: HomeComponent
  // }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

tsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2017",
    "module": "es2020",
    "lib": [
      "es2018",
      "dom"
    ]
  },
  "angularCompilerOptions": {
    "enableI18nLegacyMessageIdFormat": false,
    "strictInjectionParameters": true,
    "strictInputAccessModifiers": true,
    "strictTemplates": true
  }
}

Please help me if I am doing anything horribly wrong here. It is just a simple project to test with. Thanks a lot in advance.


问:
TicTacToe game stuck in a while loop
I have the following code for a basic TicTacToe game. When playing the code does not break out of the while loop even when the winner is True and the length of used numbers is less than 9. I tried debugging it with breakpoints and the debugger indicates the breakpoint is hit, but the while loop persists.</p>
```<code>
def TicTacToe():
    #options available
    nums = [0,1,2,3,4,5,6,7,8,9]
    used = []

    #winner winner chicken dinner combinations

    #board
    def board():
        print(f" {nums[0]}  |  {nums[1]}  |  {nums[2]}  ")
        print("----|-----|----")
        print(f" {nums[3]}  |  {nums[4]}  |  {nums[5]}  ")
        print("----|-----|----")
        print(f" {nums[6]}  |  {nums[7]}  |  {nums[8]}  ")

    # def progress():

        # return wwcd

    def round(player = "X"):
        print(used)
        winner = False

        while len(used) < 9 and winner == False:
            print(len(used))

            if player == "X":

                board()
                selected = int(input("Select number on the board to place X: "))
                if selected in nums and selected not in used:
                    used.append(selected)
                    nums[selected] = "X"

                    if (nums[0] == "X" and nums[1] == "X" and nums[2] == "X") or (nums[3] == "X" and nums[4] =="X" and nums[5] =="X") or (nums[6] == "X" and nums[7] =="X" and nums[8] =="X") or (nums[0] == "X" and nums[4] =="X" and nums[8] =="X") or (nums[6] == "X" and nums[4] =="X" and nums[2] =="X") or (nums[0] == "X" and nums[3] =="X" and nums[6] =="X") or (nums[1] == "X" and nums[4] =="X" and nums[7] =="X") or (nums[2] == "X" and nums[5] =="X" and nums[8] =="X"):
                            board()
                            print("Congradulations X, you win!")
                            winner = True
                            break

                    else:
                        print('O turn now')
                        round("O")
            elif player == "O":
                board()
                selected = int(input("Select number on the board to place O: "))
                if selected in nums and selected not in used:
                    used.append(selected)
                    nums[selected] = "O"

                    if (nums[0] == "O" and nums[1] == "O" and nums[2] == "O") or (nums[3] == "O" and nums[4] =="O" and nums[5] =="O") or (nums[6] == "O" and nums[7] =="O" and nums[8] =="O") or (nums[0] == "O" and nums[4] =="O" and nums[8] =="O") or (nums[6] == "O" and nums[4] =="O" and nums[2] =="O") or (nums[0] == "O" and nums[3] =="O" and nums[6] =="O") or (nums[1] == "O" and nums[4] =="O" and nums[7] =="O") or (nums[2] == "O" and nums[5] =="O" and nums[8] =="O"):
                            board()
                            print("Congradulations O, you win!")
                            winner = True
                            print('Hit, Winner found')

                    else:
                        round()

    round()

TicTacToe()
</code>```

答:
There is a logical problem.

The break is working well after assigning True to winner variable. The problem is that you call the round() function again, so the winner became False again. To avoid this unwanted calling round() function at the end, you need some re-structure your code.

You declared variables such as nums and used at the beginning of TicTacToc function, but declared winner inside the function round(). It would be better to declare winner outside of the function round() so that winner keep assigned value.

However, if you declare winner outside of the function round(), it will throw an error because, unlike nums and used (list type), winner is not a list so it cannot be refer in round function. (To understand why, you may want to google call by reference and call by value). To resolve this issue, you can use global keyword inside round function, indicating that we will use the winner variable in the round function. Then, your code will work.

However, I highly recommend re-construct your code to avoid using global keyword because it sometime makes code confusing. It would be nice not using nested function.

Other minor problems are...

Use different name of function for round, because it is pre-defined built-in keyword in Python.

Use winner is False instead of winner == False. (PEP 8: E712 comparison to False should be 'if cond is False:' or 'if not cond:')

Follwing is a code I fixed using global, so that it works. However, make sure that you need to re-construct the code without global and unnecessary nested functions.

def TicTacToe():
    # options available
    nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    used = []
    winner = False

    # winner winner chicken dinner combinations

    # board
    def board():
        print(f" {nums[0]}  |  {nums[1]}  |  {nums[2]}  ")
        print("----|-----|----")
        print(f" {nums[3]}  |  {nums[4]}  |  {nums[5]}  ")
        print("----|-----|----")
        print(f" {nums[6]}  |  {nums[7]}  |  {nums[8]}  ")

    # def progress():

    # return wwcd
    def round(player="X"):
        print(used)
        global winner # meaning that you will use the winner declared outside.
        winner = False
        while (len(used) < 9) and (winner is False):
            print(len(used), winner)

            if player == "X":
                board()
                selected = int(input("Select number on the board to place X: "))
                if selected in nums and selected not in used:
                    used.append(selected)
                    nums[selected] = "X"

                    if (nums[0] == "X" and nums[1] == "X" and nums[2] == "X") or (
                            nums[3] == "X" and nums[4] == "X" and nums[5] == "X") or (
                            nums[6] == "X" and nums[7] == "X" and nums[8] == "X") or (
                            nums[0] == "X" and nums[4] == "X" and nums[8] == "X") or (
                            nums[6] == "X" and nums[4] == "X" and nums[2] == "X") or (
                            nums[0] == "X" and nums[3] == "X" and nums[6] == "X") or (
                            nums[1] == "X" and nums[4] == "X" and nums[7] == "X") or (
                            nums[2] == "X" and nums[5] == "X" and nums[8] == "X"):
                        board()
                        print("Congradulations X, you win!")
                        winner = True
                        break
                    else:
                        print('O turn now')
                        round("O")
            elif player == "O":
                board()
                selected = int(input("Select number on the board to place O: "))
                if selected in nums and selected not in used:
                    used.append(selected)
                    nums[selected] = "O"

                    if (nums[0] == "O" and nums[1] == "O" and nums[2] == "O") or (
                            nums[3] == "O" and nums[4] == "O" and nums[5] == "O") or (
                            nums[6] == "O" and nums[7] == "O" and nums[8] == "O") or (
                            nums[0] == "O" and nums[4] == "O" and nums[8] == "O") or (
                            nums[6] == "O" and nums[4] == "O" and nums[2] == "O") or (
                            nums[0] == "O" and nums[3] == "O" and nums[6] == "O") or (
                            nums[1] == "O" and nums[4] == "O" and nums[7] == "O") or (
                            nums[2] == "O" and nums[5] == "O" and nums[8] == "O"):
                        board()
                        print("Congradulations O, you win!")
                        winner = True
                    else:
                        round()

    round()  # This call the round function althouth winner is already True.

TicTacToe()

```

Title: TicTacToe game stuck in a while loop

Body:
I have the following code for a basic TicTacToe game. When playing the code does not break out of the while loop even when the winner is True and the length of used numbers is less than 9. I tried debugging it with breakpoints and the debugger indicates the breakpoint is hit, but the while loop persists.

def TicTacToe():
    #options available
    nums = [0,1,2,3,4,5,6,7,8,9]
    used = []

    #winner winner chicken dinner combinations

    #board
    def board():
        print(f" {nums[0]}  |  {nums[1]}  |  {nums[2]}  ")
        print("----|-----|----")
        print(f" {nums[3]}  |  {nums[4]}  |  {nums[5]}  ")
        print("----|-----|----")
        print(f" {nums[6]}  |  {nums[7]}  |  {nums[8]}  ")

    # def progress():

        # return wwcd

    def round(player = "X"):
        print(used)
        winner = False

        while len(used) < 9 and winner == False:
            print(len(used))

            if player == "X":

                board()
                selected = int(input("Select number on the board to place X: "))
                if selected in nums and selected not in used:
                    used.append(selected)
                    nums[selected] = "X"

                    if (nums[0] == "X" and nums[1] == "X" and nums[2] == "X") or (nums[3] == "X" and nums[4] =="X" and nums[5] =="X") or (nums[6] == "X" and nums[7] =="X" and nums[8] =="X") or (nums[0] == "X" and nums[4] =="X" and nums[8] =="X") or (nums[6] == "X" and nums[4] =="X" and nums[2] =="X") or (nums[0] == "X" and nums[3] =="X" and nums[6] =="X") or (nums[1] == "X" and nums[4] =="X" and nums[7] =="X") or (nums[2] == "X" and nums[5] =="X" and nums[8] =="X"):
                            board()
                            print("Congradulations X, you win!")
                            winner = True
                            break

                    else:
                        print('O turn now')
                        round("O")
            elif player == "O":
                board()
                selected = int(input("Select number on the board to place O: "))
                if selected in nums and selected not in used:
                    used.append(selected)
                    nums[selected] = "O"

                    if (nums[0] == "O" and nums[1] == "O" and nums[2] == "O") or (nums[3] == "O" and nums[4] =="O" and nums[5] =="O") or (nums[6] == "O" and nums[7] =="O" and nums[8] =="O") or (nums[0] == "O" and nums[4] =="O" and nums[8] =="O") or (nums[6] == "O" and nums[4] =="O" and nums[2] =="O") or (nums[0] == "O" and nums[3] =="O" and nums[6] =="O") or (nums[1] == "O" and nums[4] =="O" and nums[7] =="O") or (nums[2] == "O" and nums[5] =="O" and nums[8] =="O"):
                            board()
                            print("Congradulations O, you win!")
                            winner = True
                            print('Hit, Winner found')

                    else:
                        round()

    round()

TicTacToe()


问:
Check if a binary tree is a mirror image or symmetric
What is the basic algorithm for testing if a tree is symmetrical?  Because it is a binary tree, I would assume that it would be a recursive definition of sorts

The formal question is below:

A binary tree is a mirror image of itself if its left and right subtrees are identical mirror images i.e., the binary tree is symmetrical.
This is best explained with a few examples.

```<code>  1
 / \
2   2
</code>```

TRUE

```<code>   1
  / \
 2   2
  \
   3
</code>```

FALSE

```<code>     1
   /   \
  2     2
 / \   / \
4   3 3   4
</code>```

TRUE

```<code>       1
     /   \
    2     2
   / \   / \
  3   4 3   4
</code>```

FALSE

```<code>       1
     /   \
    2     2
   /       \
  3         3
</code>```

TRUE

In a programming language of choice, define a BTree class/C struct and an associated method to check if the tree is a mirror image. For statically typed languages, you can assume that node values are all integers.

```<code>Class/structure definition
BTree {
  BTree left;
  BTree right;
  int value;
}
</code>```

Assume that the root of the tree is tracked by caller and function isMirror() is invoked on it.

Also, if defining a class, make sure to provide a no-argument constructor and getter/setter methods if data elements are not publicly accessible.

答:
```<code>class Solution:
    def isSymmetric(self, root: Optional[TreeNode]) -> bool:
        def is_mirror(t1,t2):
            # this is when I hit the leaf nodes
            if t1 is None and t2 is None:
                return True
            # if node has only one child
            if t1 is None or t2 is None:
                return False
            return t1.val==t2.val and is_mirror(t1.left,t2.right) and is_mirror(t1.right,t2.left)
        return is_mirror(root.left,root.right)
</code>```

Body:
What is the basic algorithm for testing if a tree is symmetrical?  Because it is a binary tree, I would assume that it would be a recursive definition of sorts

The formal question is below:

A binary tree is a mirror image of itself if its left and right subtrees are identical mirror images i.e., the binary tree is symmetrical.
This is best explained with a few examples.

  1
 / \
2   2

TRUE

   1
  / \
 2   2
  \
   3

FALSE

     1
   /   \
  2     2
 / \   / \
4   3 3   4

TRUE

       1
     /   \
    2     2
   / \   / \
  3   4 3   4

FALSE

       1
     /   \
    2     2
   /       \
  3         3

TRUE

In a programming language of choice, define a BTree class/C struct and an associated method to check if the tree is a mirror image. For statically typed languages, you can assume that node values are all integers.

Class/structure definition
BTree {
  BTree left;
  BTree right;
  int value;
}

Assume that the root of the tree is tracked by caller and function isMirror() is invoked on it.

Also, if defining a class, make sure to provide a no-argument constructor and getter/setter methods if data elements are not publicly accessible.


问:
How to get specific city from detail address in Google Map
This url has a demo: http://gmaps4rails.heroku.com/locations

When we give a detail address such as "9 Rue du Muret, Marseille", in the Google Map it will show a point.

Now I want to get the specific city "Marseille" through the address. This doesn't contain the street, only the city name.

Is there some way to implement this?

答:
It's as simple as doing:

```<code>  acts_as_gmappable :callback => :save_country

  def save_country(data)
    #what you need  to do here
  end
</code>```

data will contain the full hash from google. in your example it looks like:

address_components:

long_name: "9"   types:

street_number   short_name: "9"

long_name: Rue du Muret   types:

route   short_name: Rue du Muret

long_name: Les Amavaux   types:

neighborhood

political   short_name: Les Amavaux

long_name: 14e Arrondissement   types:

sublocality

political   short_name: 14e Arrondissement

long_name: Marseille   types:

locality

political   short_name: Marseille

long_name: Bouches-du-Rhone   types:

administrative_area_level_2

political   short_name: "13"

long_name: "Provence-Alpes-C\xC3\xB4te d'Azur"   types:

administrative_area_level_1

political   short_name: PACA

long_name: France   types:

country

political   short_name: FR

long_name: "13014"   types:

postal_code   short_name: "13014" types:

street_address geometry:    location:
  lng: 5.3805084
  lat: 43.3315919   bounds:
  northeast:
    lng: 5.3805246
    lat: 43.3315919
  southwest:
    lng: 5.3805084
    lat: 43.331585   location_type: RANGE_INTERPOLATED   viewport:
  northeast:
    lng: 5.3818654802915
    lat: 43.3329374302915
  southwest:
    lng: 5.3791675197085
    lat: 43.3302394697085 formatted_address: 9 Rue du Muret, 13014
  Marseilles, France

Body:
It's as simple as doing:

  acts_as_gmappable :callback => :save_country

  def save_country(data)
    #what you need  to do here
  end

data will contain the full hash from google. in your example it looks like:

address_components:

long_name: "9"   types:

street_number   short_name: "9"

long_name: Rue du Muret   types:

route   short_name: Rue du Muret

long_name: Les Amavaux   types:

neighborhood

political   short_name: Les Amavaux

long_name: 14e Arrondissement   types:

sublocality

political   short_name: 14e Arrondissement

long_name: Marseille   types:

locality

political   short_name: Marseille

long_name: Bouches-du-Rhone   types:

administrative_area_level_2

political   short_name: "13"

long_name: "Provence-Alpes-C\xC3\xB4te d'Azur"   types:

administrative_area_level_1

political   short_name: PACA

long_name: France   types:

country

political   short_name: FR

long_name: "13014"   types:

postal_code   short_name: "13014" types:

street_address geometry:    location:
  lng: 5.3805084
  lat: 43.3315919   bounds:
  northeast:
    lng: 5.3805246
    lat: 43.3315919
  southwest:
    lng: 5.3805084
    lat: 43.331585   location_type: RANGE_INTERPOLATED   viewport:
  northeast:
    lng: 5.3818654802915
    lat: 43.3329374302915
  southwest:
    lng: 5.3791675197085
    lat: 43.3302394697085 formatted_address: 9 Rue du Muret, 13014
  Marseilles, France


问:
Caused by: java.lang.ClassNotFoundException: com.sun.tools.javac.code.TypeTags when using lombok
I have following dependency in pom.xml:

```<code><dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.16.8</version>
</dependency>
</code>```

When I run mvn clean install, I have following error:

```<code>Caused by: java.lang.ClassNotFoundException: com.sun.tools.javac.code.TypeTags
    at java.lang.ClassLoader.findClass (ClassLoader.java:711)
    at java.lang.ClassLoader.loadClass (ClassLoader.java:566)
    at lombok.launch.ShadowClassLoader.loadClass (ShadowClassLoader.java:418)
</code>```

I tried to use java 1.8, 1.9, 1.10. And I tried lombok 1.6.10, 1.6.12, 1.6.20. All of them have the same problem.

答:
I tried the following lombok dependency on java-1.8 and java-11, and it build successfully.</p>
```<code><dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.4</version>
    <scope>provided</scope>
</dependency>
</code>```

Body:
I have following dependency in pom.xml:

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.16.8</version>
</dependency>

When I run mvn clean install, I have following error:

Caused by: java.lang.ClassNotFoundException: com.sun.tools.javac.code.TypeTags
    at java.lang.ClassLoader.findClass (ClassLoader.java:711)
    at java.lang.ClassLoader.loadClass (ClassLoader.java:566)
    at lombok.launch.ShadowClassLoader.loadClass (ShadowClassLoader.java:418)

I tried to use java 1.8, 1.9, 1.10. And I tried lombok 1.6.10, 1.6.12, 1.6.20. All of them have the same problem.

Body:
I tried the following lombok dependency on java-1.8 and java-11, and it build successfully.

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.4</version>
    <scope>provided</scope>
</dependency>


问:
Handling the "IndexError: string index out of range" error
I have the following string my_string:

```<code>my_string = 'A15B27C32D72A7B14C9D31'
</code>```

I split this string into chunks by the character A:

```<code>chunks = ['A' + elem for elem in my_string.split('A') if elem != '']

chunks
['A15B27C32D72', 'A7B14C9D31']
</code>```

I'd like to be able to check whether there is a number associated with the "D" character of each chunk.  To do this, I use:

```<code>for elem in chunks:
    if elem[elem.find('D') + 1].isdigit() is False:
        print('no number associated with D')
    else:
        print('the number associated with D is', elem[elem.find('D') +1])
</code>```

(Technically, this isn't correct since it won't catch cases whereby the number isn't a single digit.)

Now, let's change my_string to:

```<code>my_string = 'A15B27C32DA7B14C9D31'

chunks = ['A' + elem for elem in my_string.split('A') if elem != '']
chunks
['A15B27C32D', 'A7B14C9D31']
</code>```

(notice that D in the first chunk doesn't have an associated number)

If I run the following:

```<code>for elem in chunks:
    if elem[elem.find('D') + 1].isdigit() is False:
        print('no number associated with D')
    else:
        print('the number associated with D is', elem[elem.find('D') +1])
</code>```

I get:

```<code>IndexError                                Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_8844/1838165888.py in <module>
      1 for elem in chunks:
----> 2     if elem[elem.find('D') + 1].isdigit() is False:
      3         print('no number associated with D')
      4     else:
      5         print('the number associated with D is', elem[elem.find('D') +1])

IndexError: string index out of range
</code>```

To fix this, I can use try/except.

I can also use the following:

```<code>for elem in chunks:
    if elem[-1].isdigit() is False:
        print('no number associated with D')
    else:
        print('the number associated with D is', elem[elem.find('D') +1])

no number associated with D
the number associated with D is 3
</code>```

But, both of these approaches feel somewhat hacky.

Is there a more elegant and idiomatic way to handle the string index out of range error?

Thanks!

答:
I would suggest regex for this, but logic-wise, sometimes edge cases just have to be handled by you

```<code>for elem in chunks:
    first_d = elem.find('D')
    if first_d < len(elem) and elem[first_d + 1].isdigit() is False:
        print('no number associated with D')
    else:
        print('the number associated with D is', elem[first_d +1])
</code>```

Or, you can tweak the logic a bit

```<code>for elem in chunks:
    # should only looks for 'D' from start to second-to-last characters
    # because if last character is 'D' it is still not valid
    first_d = elem[:-1].find('D')
    if elem[first_d + 1].isdigit() is False:
        print('no number associated with D')
    else:
        print('the number associated with D is', elem[first_d + 1])
</code>```

Body:
I have the following string my_string:

my_string = 'A15B27C32D72A7B14C9D31'

I split this string into chunks by the character A:

chunks = ['A' + elem for elem in my_string.split('A') if elem != '']

chunks
['A15B27C32D72', 'A7B14C9D31']

I'd like to be able to check whether there is a number associated with the "D" character of each chunk.  To do this, I use:

for elem in chunks:
    if elem[elem.find('D') + 1].isdigit() is False:
        print('no number associated with D')
    else:
        print('the number associated with D is', elem[elem.find('D') +1])

(Technically, this isn't correct since it won't catch cases whereby the number isn't a single digit.)

Now, let's change my_string to:

my_string = 'A15B27C32DA7B14C9D31'

chunks = ['A' + elem for elem in my_string.split('A') if elem != '']
chunks
['A15B27C32D', 'A7B14C9D31']

(notice that D in the first chunk doesn't have an associated number)

If I run the following:

for elem in chunks:
    if elem[elem.find('D') + 1].isdigit() is False:
        print('no number associated with D')
    else:
        print('the number associated with D is', elem[elem.find('D') +1])

I get:

IndexError                                Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_8844/1838165888.py in <module>
      1 for elem in chunks:
----> 2     if elem[elem.find('D') + 1].isdigit() is False:
      3         print('no number associated with D')
      4     else:
      5         print('the number associated with D is', elem[elem.find('D') +1])

IndexError: string index out of range

To fix this, I can use try/except.

I can also use the following:

for elem in chunks:
    if elem[-1].isdigit() is False:
        print('no number associated with D')
    else:
        print('the number associated with D is', elem[elem.find('D') +1])

no number associated with D
the number associated with D is 3

But, both of these approaches feel somewhat hacky.

Is there a more elegant and idiomatic way to handle the string index out of range error?

Thanks!

Body:
I would suggest regex for this, but logic-wise, sometimes edge cases just have to be handled by you

for elem in chunks:
    first_d = elem.find('D')
    if first_d < len(elem) and elem[first_d + 1].isdigit() is False:
        print('no number associated with D')
    else:
        print('the number associated with D is', elem[first_d +1])

Or, you can tweak the logic a bit

for elem in chunks:
    # should only looks for 'D' from start to second-to-last characters
    # because if last character is 'D' it is still not valid
    first_d = elem[:-1].find('D')
    if elem[first_d + 1].isdigit() is False:
        print('no number associated with D')
    else:
        print('the number associated with D is', elem[first_d + 1])