问:
Can somebody please point out what is wrong with my Dockerfile? Also, please advise how can I convert this file to Alpine Linux?
```<code>> [ERROR] Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:2.5:clean (default-clean) on project myproject: Failed to clean project: Failed to delete /home/automation/myproject/target/generated-test-sources/test-annotations -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:2.5:clean (default-clean) on project myproject: Failed to clean project: Failed to delete /home/automation/myproject/target/generated-test-sources/test-annotations
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:215)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:956)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:192)
    at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:498)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356)
Caused by: org.apache.maven.plugin.MojoExecutionException: Failed to clean project: Failed to delete /home/automation/thanos/target/generated-test-sources/test-annotations
    at org.apache.maven.plugin.clean.CleanMojo.execute (CleanMojo.java:215)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:956)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:192)
    at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:498)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356)
Caused by: java.io.IOException: Failed to delete /home/automation/myproject/target/generated-test-sources/test-annotations
    at org.apache.maven.plugin.clean.Cleaner.delete (Cleaner.java:249)
    at org.apache.maven.plugin.clean.Cleaner.delete (Cleaner.java:191)
    at org.apache.maven.plugin.clean.Cleaner.delete (Cleaner.java:158)
    at org.apache.maven.plugin.clean.Cleaner.delete (Cleaner.java:158)
    at org.apache.maven.plugin.clean.Cleaner.delete (Cleaner.java:117)
    at org.apache.maven.plugin.clean.CleanMojo.execute (CleanMojo.java:193)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:956)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:192)
    at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:498)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356)
[ERROR]
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
The command '/bin/sh -c cd /home/automation/myproject/ && mvn clean test-compile -e' returned a non-zero code: 1
</code>```

I need to execute my Selenium tests in Docker containers. I know Selenium provides hub and nodes containers but I have to write my own Dockerfile that will build a container which will execute tests with no grid configuration. Basically, I cannot use grid for some reason. I have written a Dockerfile. It fails at build stage and says unable to clean project.

I have tried opening firefox and chrome without adding any user i.e. tried to execute via root user but it didn't work. Then I added a user and still it does not work. Looks like permission is granted. Please point me where permission is needed and which one that is? Below is my Dockerfile.

```<code>FROM ubuntu:latest
LABEL name="Project short intro" \
            author="TAFSEER HAIDER" \
            version="1.0" \
            description="my project description"

# Install Java JDK8, Maven, and Wget
RUN apt-get update \
    && apt-get install firefox  -y \
    && apt-get -y install openjdk-8-jdk \
    && apt-get install -y maven \
    && apt-get install -y wget \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/ /tmp/* /var/tmp/*

# Install Chrome
RUN wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
RUN dpkg -i google-chrome-stable_current_amd64.deb; apt-get -fy install

# Add a user for running applications.
RUN apt-get update && apt-get install sudo -y \
    && adduser --disabled-password --gecos '' automation \
    && adduser automation sudo \
    && echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/ /tmp/* /var/tmp/*

USER automation

# Copy myproject project to the specified directory in containerized Ubuntu Linux
COPY . /home/automation/myproject/

# Set working directory
WORKDIR /home/automation/myproject/

# Clean & compile myproject
RUN cd /home/automation/myproject/ && mvn clean test-compile -e

# Execute tests on microservices and fronted GUI by specifying the required test suite file
CMD ["mvn", "failsafe:integration-test", "-DtestSuite=frontend.xml"]
</code>```

It should execute my tests in headless mode.

答:
It looks like your automation user doesn't have Linux write permission hence he cannot remove target folder during Maven clean phase

Change this line:

```<code>COPY . /home/automation/myproject/
</code>```

to this one:

```<code>COPY --chown=automation . /home/automation/myproject/
</code>```

I also fail to see any real or virtual display configuration in your Dockerfile, hopefully you pass headless arguments to the browsers initialization, otherwise your test will not work.

Also make sure to follow Parallel Tests - Best Practices, in particular:

Use ThreadLocal to hold your WebDriver instances and the variables which are not meant to be global and shared across threads

Avoid using static methods and fields

Make sure that your tests are independent, repeatable and stable

Body:
> [ERROR] Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:2.5:clean (default-clean) on project myproject: Failed to clean project: Failed to delete /home/automation/myproject/target/generated-test-sources/test-annotations -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:2.5:clean (default-clean) on project myproject: Failed to clean project: Failed to delete /home/automation/myproject/target/generated-test-sources/test-annotations
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:215)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:956)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:192)
    at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:498)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356)
Caused by: org.apache.maven.plugin.MojoExecutionException: Failed to clean project: Failed to delete /home/automation/thanos/target/generated-test-sources/test-annotations
    at org.apache.maven.plugin.clean.CleanMojo.execute (CleanMojo.java:215)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:956)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:192)
    at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:498)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356)
Caused by: java.io.IOException: Failed to delete /home/automation/myproject/target/generated-test-sources/test-annotations
    at org.apache.maven.plugin.clean.Cleaner.delete (Cleaner.java:249)
    at org.apache.maven.plugin.clean.Cleaner.delete (Cleaner.java:191)
    at org.apache.maven.plugin.clean.Cleaner.delete (Cleaner.java:158)
    at org.apache.maven.plugin.clean.Cleaner.delete (Cleaner.java:158)
    at org.apache.maven.plugin.clean.Cleaner.delete (Cleaner.java:117)
    at org.apache.maven.plugin.clean.CleanMojo.execute (CleanMojo.java:193)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:956)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:192)
    at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:498)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356)
[ERROR]
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
The command '/bin/sh -c cd /home/automation/myproject/ && mvn clean test-compile -e' returned a non-zero code: 1

I need to execute my Selenium tests in Docker containers. I know Selenium provides hub and nodes containers but I have to write my own Dockerfile that will build a container which will execute tests with no grid configuration. Basically, I cannot use grid for some reason. I have written a Dockerfile. It fails at build stage and says unable to clean project.

I have tried opening firefox and chrome without adding any user i.e. tried to execute via root user but it didn't work. Then I added a user and still it does not work. Looks like permission is granted. Please point me where permission is needed and which one that is? Below is my Dockerfile.

FROM ubuntu:latest
LABEL name="Project short intro" \
            author="TAFSEER HAIDER" \
            version="1.0" \
            description="my project description"

# Install Java JDK8, Maven, and Wget
RUN apt-get update \
    && apt-get install firefox  -y \
    && apt-get -y install openjdk-8-jdk \
    && apt-get install -y maven \
    && apt-get install -y wget \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/ /tmp/* /var/tmp/*

# Install Chrome
RUN wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
RUN dpkg -i google-chrome-stable_current_amd64.deb; apt-get -fy install

# Add a user for running applications.
RUN apt-get update && apt-get install sudo -y \
    && adduser --disabled-password --gecos '' automation \
    && adduser automation sudo \
    && echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/ /tmp/* /var/tmp/*

USER automation

# Copy myproject project to the specified directory in containerized Ubuntu Linux
COPY . /home/automation/myproject/

# Set working directory
WORKDIR /home/automation/myproject/

# Clean & compile myproject
RUN cd /home/automation/myproject/ && mvn clean test-compile -e

# Execute tests on microservices and fronted GUI by specifying the required test suite file
CMD ["mvn", "failsafe:integration-test", "-DtestSuite=frontend.xml"]

It should execute my tests in headless mode.

Body:
It looks like your automation user doesn't have Linux write permission hence he cannot remove target folder during Maven clean phase

Change this line:

COPY . /home/automation/myproject/

to this one:

COPY --chown=automation . /home/automation/myproject/

I also fail to see any real or virtual display configuration in your Dockerfile, hopefully you pass headless arguments to the browsers initialization, otherwise your test will not work.

Also make sure to follow Parallel Tests - Best Practices, in particular:

Use ThreadLocal to hold your WebDriver instances and the variables which are not meant to be global and shared across threads

Avoid using static methods and fields

Make sure that your tests are independent, repeatable and stable


来源: stackexchange

问:
Extent report not marking my tests FAIL, if test failed due to NoSuchElementException or any other exception
I have used extent report for generating HTML reports, I am using a testing framework. I have only class and have mentioned all of my tests under @Test method of testing. Now if any of my tests are throwing NoSuchElementException then it should be marked as FAIL in extent report and also in testing build status, failed test count should come for this failed test.

I am using try catch for each of my tests and I tried using below in catch
test.fail(e);
extent.flush();

I was expecting that extent report should show failed test as FAIL and also testing build status should show failed test count.

but it didn't happen like this

答:
```<code>I found the answer and thus posting it.
Use below code in all tests...you must include all test in try catch

catch (AssertionError e)
{
            test.fail(e);
            Assert.fail();
            extent.flush();
}

after this any kind of exception that comes in between steps of tests will be caught in catch and then this test.fail will tell extent report to mark that test as FAIL and this Assert.fail() will test TestNG to mark that test as FAIL.

Do include AssertionError in catch block as that is the key which worked for me
</code>```

ContentLicense: CC BY-SA 4.0


问:
How to calculate difference between two dates in months in MySQL
I have two columns in a MySQL table:

DateOfService (datetime)

BirthDate (date)

I want to run a MySQL query that will provide date difference between these two fields in months.

How can I do this in a MySQL select query?

Thanks.

答:
Try this:

SELECT DATEDIFF(DateOfService, BirthDate) / 30 as months FROM ...

ContentLicense: CC BY-SA 3.0


问:
How to Insert New Rows (with a condition) in Excel using Python / Pandas
I am trying to insert new rows into an excel using pandas data-frame when a particular columns has a specific condition

For ex:

```<code>Input

    A   B   C   D   E
0   AA  111 2   2
1   CC  222 8   12
2   DD  333 3   3

Output
    A   B   C   D   E (Output Column)
0   AA  111 2   2   111-2
1   CC  222 8   8   222-8
2   CC  222 9   9   222-9
3   CC  222 10  10  222-10
4   CC  222 11  11  222-11
5   CC  222 12  12  222-12
6   DD  333 3   3   333-3
</code>```

If you see here the Column C and D has a range of 8-12 for Row # 1. So I need to split the row accordingly. If C and D are same, no appending of new rows.

答:
My example uses to get data from lines with different values for C and D columns and create new data for them. Next add this new data to data with no differences.

```<code>import pandas as pd

# setup data
data_raw = [['AA', 111, 2, 2], ['CC', 222, 8, 12], ['DD', 333, 3, 3]]
data = pd.DataFrame(data_raw, columns=['A', 'B', 'C','D'])

# get items with no difference
rest_of_data = data.loc[data['C'] == data['D']]

# create value for E column
rest_of_data = rest_of_data.copy()
rest_of_data['E'] = str(str(rest_of_data['B'].values[0]) + '-' + str(rest_of_data['C'].values[0]))

# find items with difference
difference_data = data.loc[data['C'] != data['D']]

# get numbers of elements to create
start = int(difference_data['C'])
stop = int(difference_data['D'])

# create new data
create_data = []
for i in range(start,stop+1,1):
    new = [difference_data['A'].values[0], difference_data['B'].values[0], i, i, str(difference_data['B'].values[0])+'-'+str(i)]
    create_data.append(new)

new_data = pd.DataFrame(create_data, columns=['A', 'B', 'C','D', 'E'])

# concatenate frames
frames = [rest_of_data, new_data]
result = pd.concat(frames, ignore_index=True)
</code>```

Result:

```<code>    A    B   C   D       E
0  AA  111   2   2   111-2
1  DD  333   3   3   111-2
2  CC  222   8   8   222-8
3  CC  222   9   9   222-9
4  CC  222  10  10  222-10
5  CC  222  11  11  222-11
6  CC  222  12  12  222-12
</code>```

Body:
I am trying to insert new rows into an excel using pandas data-frame when a particular columns has a specific condition

For ex:

Input

    A   B   C   D   E
0   AA  111 2   2
1   CC  222 8   12
2   DD  333 3   3

Output
    A   B   C   D   E (Output Column)
0   AA  111 2   2   111-2
1   CC  222 8   8   222-8
2   CC  222 9   9   222-9
3   CC  222 10  10  222-10
4   CC  222 11  11  222-11
5   CC  222 12  12  222-12
6   DD  333 3   3   333-3

If you see here the Column C and D has a range of 8-12 for Row # 1. So I need to split the row accordingly. If C and D are same, no appending of new rows.

Body:
My example uses to get data from lines with different values for C and D columns and create new data for them. Next add this new data to data with no differences.

import pandas as pd

# setup data
data_raw = [['AA', 111, 2, 2], ['CC', 222, 8, 12], ['DD', 333, 3, 3]]
data = pd.DataFrame(data_raw, columns=['A', 'B', 'C','D'])

# get items with no difference
rest_of_data = data.loc[data['C'] == data['D']]

# create value for E column
rest_of_data = rest_of_data.copy()
rest_of_data['E'] = str(str(rest_of_data['B'].values[0]) + '-' + str(rest_of_data['C'].values[0]))

# find items with difference
difference_data = data.loc[data['C'] != data['D']]

# get numbers of elements to create
start = int(difference_data['C'])
stop = int(difference_data['D'])

# create new data
create_data = []
for i in range(start,stop+1,1):
    new = [difference_data['A'].values[0], difference_data['B'].values[0], i, i, str(difference_data['B'].values[0])+'-'+str(i)]
    create_data.append(new)

new_data = pd.DataFrame(create_data, columns=['A', 'B', 'C','D', 'E'])

# concatenate frames
frames = [rest_of_data, new_data]
result = pd.concat(frames, ignore_index=True)

Result:

    A    B   C   D       E
0  AA  111   2   2   111-2
1  DD  333   3   3   111-2
2  CC  222   8   8   222-8
3  CC  222   9   9   222-9
4  CC  222  10  10  222-10
5  CC  222  11  11  222-11
6  CC  222  12  12  222-12


Title: Fill missing time slots for multiple users

Body:
I'm trying to fill the missing slots in the CSV file which has date and time as a string.

My input is:

time_slot              User       Location
2017-10-26 00:00:00      1           156
2017-10-26 10:00:00      1           55
2017-10-26 12:00:00      1           848
2017-10-27 02:00:00      1           79
2017-10-27 16:00:00      1           846
2017-10-27 23:00:00      1           648
2017-10-26 00:00:00      2           75
2017-10-26 02:00:00      2           32
2017-10-26 10:00:00      2           18
2017-10-27 01:00:00      2           874
2017-10-27 04:00:00      2           46
2017-10-27 18:00:00      2           96
2017-10-26 07:00:00      3           25
2017-10-26 09:00:00      3           463
2017-10-26 14:00:00      3           85
2017-10-27 06:00:00      3           95
2017-10-27 23:00:00      3           12

Output should be

time_slot              User       Location
2017-10-26 00:00:00      1           156
.
.
.
.
2017-10-26 09:00:00      1           156
2017-10-26 10:00:00      1           55
2017-10-26 11:00:00      1           55
2017-10-26 12:00:00      1           848
.
.          848 for all slots in between
.
2017-10-26 24:00:00      1           848
.
.           848

2017-10-27 02:00:00      1           79
.
.          79
.

2017-10-27 16:00:00      1           846

             846
Same as above

2017-10-27 23:00:00      1           648
2017-10-26 00:00:00      2           75
2017-10-26 02:00:00      2           32
2017-10-26 10:00:00      2           18
2017-10-27 01:00:00      2           874
2017-10-27 04:00:00      2           46
2017-10-27 18:00:00      2           96
2017-10-26 07:00:00      3           25
2017-10-26 09:00:00      3           463
2017-10-26 14:00:00      3           85
2017-10-27 06:00:00      3           95
2017-10-27 23:00:00      3           12

the datetime frequency is 1hour. Instead of filling 0 in the missing slots we fill the location point of the previous timeslots

Body:
Use  DataFrame.asfreq in DataFrame.groupby:

df1 = (df.groupby('User')['Location']
        .apply(lambda x: x.asfreq(freq='H',method='ffill'))
        .reset_index())
print (df1.head(10))
   User           time_slot  Location
0     1 2017-10-26 00:00:00       156
1     1 2017-10-26 01:00:00       156
2     1 2017-10-26 02:00:00       156
3     1 2017-10-26 03:00:00       156
4     1 2017-10-26 04:00:00       156
5     1 2017-10-26 05:00:00       156
6     1 2017-10-26 06:00:00       156
7     1 2017-10-26 07:00:00       156
8     1 2017-10-26 08:00:00       156
9     1 2017-10-26 09:00:00       156

Detail:

print (df.index)
DatetimeIndex(['2017-10-26 00:00:00', '2017-10-26 10:00:00',
               '2017-10-26 12:00:00', '2017-10-27 02:00:00',
               '2017-10-27 16:00:00', '2017-10-27 23:00:00',
               '2017-10-26 00:00:00', '2017-10-26 02:00:00',
               '2017-10-26 10:00:00', '2017-10-27 01:00:00',
               '2017-10-27 04:00:00', '2017-10-27 18:00:00',
               '2017-10-26 07:00:00', '2017-10-26 09:00:00',
               '2017-10-26 14:00:00', '2017-10-27 06:00:00',
               '2017-10-27 23:00:00'],
              dtype='datetime64[ns]', name='time_slot', freq=None)


问:
How to integrate Flash Professional and Flash Builder?
I'm an AS3 developer used to working with Flash Builder. I'm working with a designer who's using Flash Professional to design sprites and backgrounds for a game. I'm looking to create an integrated workflow for us, so they can layout levels in Flash Pro and I can add events in Flash Builder.

As well as triggering events when the player collides with items, triggering animations etc., I'm also looking to switch between scenes when the player changes level and the game changes state (start menu, in-play, game over etc.). To do this I'd like to load everything into Flash Builder and manipulate it programatically - showing and hiding scenes, scrolling, checking for collisions etc.

I've found guides to exporting a swc from Flash Pro and accessing the library in Flash Builder, but this only gives me the classes, not the positioned instances of objects. Is it possible to access everything on the stage as I'm looking to do?

This seems like an obvious workflow but I'm not finding it clear how it's done. Is my approach correct, or is there a better way to do this? Any advice on how to setup this workflow generally, what to do or avoid? More specifically, how can I access the entities on the stage and switch between scenes?

答:
You can compile your project in Flash CS into swf and then use Loader or SWFLoader in Flash Builder to add it to your displaylist.
Also you can wrap all your objects on the stage into one MovieClip and compile it into swc and then use as library.


问:
How to Add ResultSet Data To JTable with out changing Default Colomn names of jTable
I have the following class:

```<code>public class customer_master extends javax.swing.JInternalFrame {

    Connection con = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    JFrame parent;
    public customer_master(JFrame parent) {

        this.parent=parent;
        initComponents();

        try {
            String qry="select customer_code, customer_name, customer_address, customer_created_time from customer";
            database.JavaConnect jc= new JavaConnect();
            con = jc.ConnectDB();
            ps = con.prepareStatement(qry);
            rs = ps.executeQuery();
            jTable1.setModel(DbUtils.resultSetToTableModel(rs));
            con.close();
        }
        catch(SQLException e)
        {
            JOptionPane.showMessageDialog(null, e);
        }
    }
}
</code>```

It also change the name of columns but I want to add rs without changing columns name please if any one can help.  Thanks in advance.

答:
Just change your query

String qry="select customer_code, customer_name, customer_address,
               customer_created_time from customer";

to

String qry="select customer_code AS Customer Code, customer_name AS Customer Name, customer_address AS Customer Address,
               customer_created_time AS DOJ from customer";

and you'll be good to go.

Body:
I have the following class:

public class customer_master extends javax.swing.JInternalFrame {

    Connection con = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    JFrame parent;
    public customer_master(JFrame parent) {

        this.parent=parent;
        initComponents();

        try {
            String qry="select customer_code, customer_name, customer_address, customer_created_time from customer";
            database.JavaConnect jc= new JavaConnect();
            con = jc.ConnectDB();
            ps = con.prepareStatement(qry);
            rs = ps.executeQuery();
            jTable1.setModel(DbUtils.resultSetToTableModel(rs));
            con.close();
        }
        catch(SQLException e)
        {
            JOptionPane.showMessageDialog(null, e);
        }
    }
}

It also change the name of columns but I want to add rs without changing columns name please if any one can help.  Thanks in advance.


问:
Pointer to member function using C++ lambda
I'm trying to find a way to provide pointers to a member functions between different class instances. For the moment I'm able to provide pointers to member function that takes no arguments but cannot manage to do so when the function to point to has an argument.

A sample code to illustrate my problem :

```<code>#include <iostream>

class Event
{
public:
    std::string type;
    Event(std::string type):type(type){}
};

class EventDispatcherBase
{
public:

    void addEventListener(std::function<void(Event &event)> listener)
    {
        Event myEvent("Type of the myEvent object");
        listener(myEvent);
    }
};

class EventDispatcherClass:public EventDispatcherBase
{
public:
    EventDispatcherClass()
    {
        addEventListener([](Event &event){std::cout << event.type << std::endl;});
        //addEventListener([this]{listener(Event event);});
    };

    void listener(Event &event)
    {
        std::cout << event.type << std::endl;
    }
};

int main()
{
    EventDispatcherClass eventDispatcherClass;

    return 0;
}
</code>```

This code works with an anonymous lambda expression and output "Type of the myEvent object" in the console. But if I uncomment the line

```<code>addEventListener([this]{listener(Event event);});
</code>```

in the constructor of the EventDispatcherClass in order to transmit a pointer to the void listener(Event &event) member function, the compiler throw the following error :

no viable conversion from '(lambda at .../main.cpp:27:26)' to
  'std::function'

I don't understand why.

答:
just change it to addEventListener(listener);

and make the function itself static as static void listener(Event &event)

Body:
I'm trying to find a way to provide pointers to a member functions between different class instances. For the moment I'm able to provide pointers to member function that takes no arguments but cannot manage to do so when the function to point to has an argument.

A sample code to illustrate my problem :

#include <iostream>

class Event
{
public:
    std::string type;
    Event(std::string type):type(type){}
};

class EventDispatcherBase
{
public:

    void addEventListener(std::function<void(Event &event)> listener)
    {
        Event myEvent("Type of the myEvent object");
        listener(myEvent);
    }
};

class EventDispatcherClass:public EventDispatcherBase
{
public:
    EventDispatcherClass()
    {
        addEventListener([](Event &event){std::cout << event.type << std::endl;});
        //addEventListener([this]{listener(Event event);});
    };

    void listener(Event &event)
    {
        std::cout << event.type << std::endl;
    }
};

int main()
{
    EventDispatcherClass eventDispatcherClass;

    return 0;
}

This code works with an anonymous lambda expression and output "Type of the myEvent object" in the console. But if I uncomment the line

addEventListener([this]{listener(Event event);});

in the constructor of the EventDispatcherClass in order to transmit a pointer to the void listener(Event &event) member function, the compiler throw the following error :

no viable conversion from '(lambda at .../main.cpp:27:26)' to
  'std::function'

I don't understand why.


问:
Swift - how to split an amount of money equally between a group of people?
I'm building a clone banking app at the moment, and one of the things I'm trying to do is add 'Split Transaction' (which can then be shared with a set of friends paying a given amount each).

Initially, the transaction is split equally amongst friends (unless it doesn't split equally, in which case the remainder gets added on to one unlucky friend). The user can then manually adjust the amount each pays, which then updates the others. If the user has manually adjust an amount for a friend, this friends 'split' doesn't get updated automatically if the user then adjust another friend's amount (i.e. if the user says friend1 pays £12, it will always be £12 until the user says otherwise).

I've been fiddling for a while trying to make the method as concise and 'swifty' as possible - but I'd really appreciate any feedback on my approach.

For the purposes here, I'm only trying split the money equally between people (but I still wanted to explain the 'user defined split' so the current code makes sense).

I'm using https://github.com/Flight-School/Money to represent the transaction value, all within a Transaction class. I need to round quite a bit to ensure the split and remainder stick to 2 decimal places. Here's the relevant code:

A struct to hold an amount along with if the user set it or not (needs to be custom object for codable reasons):

```<code>struct SplitTransactionAmount: Codable {
    let amount: Money<GBP>
    let setByUser: Bool
}
</code>```

A dictionary to hold the friend names, along with their split, and if it's set by the user - also a namesOfPeopleSplittingTransaction array for easy display.

```<code>var splitTransaction: [String: SplitTransactionAmount]
var namesOfPeopleSplittingTransaction = [String]()
</code>```

And here's the method to split the transaction:

```<code>private func splitTransaction(amount: Money<GBP>, with friends: [String]) -> [String: SplitTransactionAmount] {

    //First we remove any duplicate names.
    let uniqueFriends = friends.removingDuplicates()
    //Create an empty dictionary to hold the new values before returning.
    var newSplitTransaction = [String: SplitTransactionAmount]()

    let totalAmountToSplitRounded = amount.rounded.amount
    let numberOfSplitters = uniqueFriends.count

    let eachTotalRaw = totalAmountToSplitRounded / Decimal(numberOfSplitters)
    let eachTotalRounded = Money<GBP>(eachTotalRaw).rounded.amount

    let remainder = totalAmountToSplitRounded - (Decimal(numberOfSplitters) * eachTotalRounded)

    if remainder == 0 {
        //If the amount to split each goes in to the total with no remainder, everyone pays the same.
        for friend in uniqueFriends {
            newSplitTransaction[friend] = SplitTransactionAmount(amount: Money(eachTotalRounded), setByUser: false)
        }
    } else {
        for friend in uniqueFriends {
            if friend == uniqueFriends.first! {
                //Unlucky first friend has to pay a few pence more!
                newSplitTransaction[friend] = SplitTransactionAmount(amount: Money(eachTotalRounded + remainder), setByUser: false)
            } else {
                newSplitTransaction[friend] = SplitTransactionAmount(amount: Money(eachTotalRounded), setByUser: false)
            }
        }
    }
    return newSplitTransaction
}
</code>```

I think the problem I'm finding is the code makes perfect sense to me, but I'm not sure how clear it is to an outside reader. Any thoughts on my approach would be much appreciated (and sorry for the long question!). And I'd also love to know if there's anyway to write this more concisely!

Many thanks

答:
IMO, Simplify into a single loop over two loops on different ifs . And reduce repeated code (e.g init of SplitTransactionAmount)

```<code>
 for (index, friend) in uniqueFriends.enumerated(){ //or if you don't prefer enumerated, use == on first index like before.
    let money: Money<GBP>
    if remainder != 0, index == 0 { //ensure remainder is only used if has value.
        //Unlucky first friend has to pay a few pence more!
        money = Money(eachTotalRounded + remainder)
   } else {
        money = Money(eachTotalRounded)
   }

    newSplitTransaction[friend] = SplitTransactionAmount(amount: money setByUser: false)

 }

</code>```

Body:
I'm building a clone banking app at the moment, and one of the things I'm trying to do is add 'Split Transaction' (which can then be shared with a set of friends paying a given amount each).

Initially, the transaction is split equally amongst friends (unless it doesn't split equally, in which case the remainder gets added on to one unlucky friend). The user can then manually adjust the amount each pays, which then updates the others. If the user has manually adjust an amount for a friend, this friends 'split' doesn't get updated automatically if the user then adjust another friend's amount (i.e. if the user says friend1 pays £12, it will always be £12 until the user says otherwise).

I've been fiddling for a while trying to make the method as concise and 'swifty' as possible - but I'd really appreciate any feedback on my approach.

For the purposes here, I'm only trying split the money equally between people (but I still wanted to explain the 'user defined split' so the current code makes sense).

I'm using https://github.com/Flight-School/Money to represent the transaction value, all within a Transaction class. I need to round quite a bit to ensure the split and remainder stick to 2 decimal places. Here's the relevant code:

A struct to hold an amount along with if the user set it or not (needs to be custom object for codable reasons):

struct SplitTransactionAmount: Codable {
    let amount: Money<GBP>
    let setByUser: Bool
}

A dictionary to hold the friend names, along with their split, and if it's set by the user - also a namesOfPeopleSplittingTransaction array for easy display.

var splitTransaction: [String: SplitTransactionAmount]
var namesOfPeopleSplittingTransaction = [String]()

And here's the method to split the transaction:

private func splitTransaction(amount: Money<GBP>, with friends: [String]) -> [String: SplitTransactionAmount] {

    //First we remove any duplicate names.
    let uniqueFriends = friends.removingDuplicates()
    //Create an empty dictionary to hold the new values before returning.
    var newSplitTransaction = [String: SplitTransactionAmount]()

    let totalAmountToSplitRounded = amount.rounded.amount
    let numberOfSplitters = uniqueFriends.count

    let eachTotalRaw = totalAmountToSplitRounded / Decimal(numberOfSplitters)
    let eachTotalRounded = Money<GBP>(eachTotalRaw).rounded.amount

    let remainder = totalAmountToSplitRounded - (Decimal(numberOfSplitters) * eachTotalRounded)

    if remainder == 0 {
        //If the amount to split each goes in to the total with no remainder, everyone pays the same.
        for friend in uniqueFriends {
            newSplitTransaction[friend] = SplitTransactionAmount(amount: Money(eachTotalRounded), setByUser: false)
        }
    } else {
        for friend in uniqueFriends {
            if friend == uniqueFriends.first! {
                //Unlucky first friend has to pay a few pence more!
                newSplitTransaction[friend] = SplitTransactionAmount(amount: Money(eachTotalRounded + remainder), setByUser: false)
            } else {
                newSplitTransaction[friend] = SplitTransactionAmount(amount: Money(eachTotalRounded), setByUser: false)
            }
        }
    }
    return newSplitTransaction
}

I think the problem I'm finding is the code makes perfect sense to me, but I'm not sure how clear it is to an outside reader. Any thoughts on my approach would be much appreciated (and sorry for the long question!). And I'd also love to know if there's anyway to write this more concisely!

Many thanks

Body:
IMO, Simplify into a single loop over two loops on different ifs . And reduce repeated code (e.g init of SplitTransactionAmount)

 for (index, friend) in uniqueFriends.enumerated(){ //or if you don't prefer enumerated, use == on first index like before.
    let money: Money<GBP>
    if remainder != 0, index == 0 { //ensure remainder is only used if has value.
        //Unlucky first friend has to pay a few pence more!
        money = Money(eachTotalRounded + remainder)
   } else {
        money = Money(eachTotalRounded)
   }

    newSplitTransaction[friend] = SplitTransactionAmount(amount: money setByUser: false)

 }


问:
Some kind of a join-aggregation query in MongoDB
Inside my DB I have two collections:

```<code>Subjects Collection
 - id : ObjectID(own)
 - subjectCreator : ObjectID(of a user)
 - groups : Array
            [
                 ObjectID(of a group),
                 ObjectID(of a group),
                 ....more
            ]
 - media : Array
            [
                 {
                     id : ObjectID(of media)
                     mediaUploader: ObjectID(of user)
                     other properties that not important
                 },
                 {
                     id : ObjectID(of media)
                     mediaUploader: ObjectID(of user)
                     other properties that not important
                 },

            ]
</code>```

and a Groups collection

```<code>Groups Collection
 - id : ObjectID(own)
 - groupName: string
 - groupAdmin: ObjectID(of user)
 - members: Array
            [
                 ObjectID(of a user),
                 ObjectID(of a user),
                 ....more
            ]
</code>```

what I am trying to do is,
when given a user id (ObjectID)
to get an array of all Subjects that the user can see.

a user can see a subject by two criteria:

if they are the subject Creator

if they are members of the group that the subject include in the groups field

I understand that this is a kind of aggregation between the two queries,
but I cannot provide an example of my own trial because I am new to MongoDB,
and don't know even how to approach it.

I think (probably wrong) that if this was written in SQL server it would look like this:

given a @userID param

```<code>SELECT distinct s.*
FROM Subjects s
WHERE @userID = s.subjectCreator
OR
@userID in (
               SELECT members
               FROM Groups g
               WHERE g.GroupID in (
                                       SELECT groups
                                       FROM Subjects
                                       WHERE s.Groups.GroupID = g.GroupID
                                   )
           )
</code>```

my server side is written in NodeJS

and another small question, which one would be the best practice for the DB structure?
the structure above,
or the structure below?
the difference is within the arrays, please explain why

```<code>Subjects Collection
 - id : ObjectID(own)
 - subjectCreator : ObjectID(of a user)
 - groups : Array
            [
                 { groupID: ObjectID(of a group) },
                 { groupID: ObjectID(of a group) },,
                 ....more **OBJECTS**
            ]
 - media : Array
            [
                 {
                     id : ObjectID(of media)
                     mediaUploader: ObjectID(of user)
                     other properties that not important
                 },
                 {
                     id : ObjectID(of media)
                     mediaUploader: ObjectID(of user)
                     other properties that not important
                 },

            ]
</code>```

and a Groups collection

```<code>Groups Collection
 - id : ObjectID(own)
 - groupName: string
 - groupAdmin: ObjectID(of user)
 - members: Array
            [
                 { memberID : ObjectID(of a user) },
                 { memberID : ObjectID(of a user) },
                 ....more objects of members id
            ]
</code>```

答:
For the first question our strategy would be to use $lookup to "merge" these collections and then query on it.

```<code>db.collection.Subjetcs.aggregate([
        {
           $lookup: {
               from: "Groups",
               let: {group_ids: "$groups"},
               pipeline: [
                    {
                       $match: {
                          $expr:  {
                              $in: ["$id", "$$group_ids"]
                          }
                       }
                    }
               ]
               as: "group"
           }
        },
        {
           $match: {
              $or: [
                  {subjectCreator: ObjectId(givenUserID)},
                  {'group.members': ObjectId(givenUserID)}
              ]
           }
        },
])
</code>```

Design wise i would stick with the former, it makes queries look "cleaner" and from my experience will save you time and resources in the future when converting [{_id: 1}, {_id: 2}] to [1, 2] for whatever reason.

Note though that they are equivalent "power", i.e what can be accomplisht with it.

Also i'm not exactly sure how big the over head will be but i imagine indexing that field as an array is far easier for mongo in the case you do so.

Body:
Inside my DB I have two collections:

Subjects Collection
 - id : ObjectID(own)
 - subjectCreator : ObjectID(of a user)
 - groups : Array
            [
                 ObjectID(of a group),
                 ObjectID(of a group),
                 ....more
            ]
 - media : Array
            [
                 {
                     id : ObjectID(of media)
                     mediaUploader: ObjectID(of user)
                     other properties that not important
                 },
                 {
                     id : ObjectID(of media)
                     mediaUploader: ObjectID(of user)
                     other properties that not important
                 },

            ]

and a Groups collection

Groups Collection
 - id : ObjectID(own)
 - groupName: string
 - groupAdmin: ObjectID(of user)
 - members: Array
            [
                 ObjectID(of a user),
                 ObjectID(of a user),
                 ....more
            ]

what I am trying to do is,
when given a user id (ObjectID)
to get an array of all Subjects that the user can see.

a user can see a subject by two criteria:

if they are the subject Creator

if they are members of the group that the subject include in the groups field

I understand that this is a kind of aggregation between the two queries,
but I cannot provide an example of my own trial because I am new to MongoDB,
and don't know even how to approach it.

I think (probably wrong) that if this was written in SQL server it would look like this:

given a @userID param

SELECT distinct s.*
FROM Subjects s
WHERE @userID = s.subjectCreator
OR
@userID in (
               SELECT members
               FROM Groups g
               WHERE g.GroupID in (
                                       SELECT groups
                                       FROM Subjects
                                       WHERE s.Groups.GroupID = g.GroupID
                                   )
           )

my server side is written in NodeJS

and another small question, which one would be the best practice for the DB structure?
the structure above,
or the structure below?
the difference is within the arrays, please explain why

Subjects Collection
 - id : ObjectID(own)
 - subjectCreator : ObjectID(of a user)
 - groups : Array
            [
                 { groupID: ObjectID(of a group) },
                 { groupID: ObjectID(of a group) },,
                 ....more **OBJECTS**
            ]
 - media : Array
            [
                 {
                     id : ObjectID(of media)
                     mediaUploader: ObjectID(of user)
                     other properties that not important
                 },
                 {
                     id : ObjectID(of media)
                     mediaUploader: ObjectID(of user)
                     other properties that not important
                 },

            ]

and a Groups collection

Groups Collection
 - id : ObjectID(own)
 - groupName: string
 - groupAdmin: ObjectID(of user)
 - members: Array
            [
                 { memberID : ObjectID(of a user) },
                 { memberID : ObjectID(of a user) },
                 ....more objects of members id
            ]

Body:
For the first question our strategy would be to use $lookup to "merge" these collections and then query on it.

db.collection.Subjetcs.aggregate([
        {
           $lookup: {
               from: "Groups",
               let: {group_ids: "$groups"},
               pipeline: [
                    {
                       $match: {
                          $expr:  {
                              $in: ["$id", "$$group_ids"]
                          }
                       }
                    }
               ]
               as: "group"
           }
        },
        {
           $match: {
              $or: [
                  {subjectCreator: ObjectId(givenUserID)},
                  {'group.members': ObjectId(givenUserID)}
              ]
           }
        },
])

Design wise i would stick with the former, it makes queries look "cleaner" and from my experience will save you time and resources in the future when converting [{_id: 1}, {_id: 2}] to [1, 2] for whatever reason.

Note though that they are equivalent "power", i.e what can be accomplisht with it.

Also i'm not exactly sure how big the over head will be but i imagine indexing that field as an array is far easier for mongo in the case you do so.


问:
mysql select ids from one table which are not found in another table under certain conditions
Using the following two (simplified) table structures I'd like to find all DISTINCT session_id values that appear in TABLE1 where flag = yes that DO NOT appear in TABLE2 where progress = 11.

TABLE1 has no duplicate session_id values.

TABLE1

```<code>id_table1 | session_id | flag
------------------------------
1         | abcd       | yes
2         | efgh       | no
3         | ijkl       | yes
4         | mnop       | yes
5         | vwxyz      | yes
</code>```

TABLE2

```<code>id_table2 | session_id | progress
---------------------------------
1         | abcd       | 3
2         | efgh       | 11
3         | ijkl       | 2
4         | ijkl       | 7
5         | mnop       | 11
6         | vwxyz      | 10
7         | vwxyz      | 11
</code>```

The expected results here are:

```<code>abcd
ijkl
</code>```

答:
```<code>SELECT

DISTINCT t1.session_id

FROM
    id_table1 t1

INNER JOIN
    id_table2 t2
ON
    t1.session_id = t2.session_id

WHERE
    t1.flag = 'yes'
AND
    t2.progress NOT IN(11)
</code>```

Body:
Using the following two (simplified) table structures I'd like to find all DISTINCT session_id values that appear in TABLE1 where flag = yes that DO NOT appear in TABLE2 where progress = 11.

TABLE1 has no duplicate session_id values.

TABLE1

id_table1 | session_id | flag
------------------------------
1         | abcd       | yes
2         | efgh       | no
3         | ijkl       | yes
4         | mnop       | yes
5         | vwxyz      | yes

TABLE2

id_table2 | session_id | progress
---------------------------------
1         | abcd       | 3
2         | efgh       | 11
3         | ijkl       | 2
4         | ijkl       | 7
5         | mnop       | 11
6         | vwxyz      | 10
7         | vwxyz      | 11

The expected results here are:

abcd
ijkl


问:
weights, selected features in adaboost classifiers
Is there any keyword in scikit-learn for AdaBoostClassifier to return weights of the weak classifiers at each step?
IDK if the features are chosen randomly (For the weak Decision Trees that this classifiers provide for further learning processes) if it is so, how can we observe the chosen features?

答:
clf.estimator_weights_ would give the weights for each estimator in the ensemble.

Documentation

There is no sampling of random features in Adaboost classifier. There would be only sample weights based on the ensemble model error.

To know more about Adaboost technique, read here.

May be you can look at the feature importance of individual decision trees. You can start by tweaking this function.


问:
How to create a circle icon button in Flutter?
How can I create something similar to a FloatingActionButton?

答:
You can easily do the following:

```<code>FlatButton(
      onPressed: () {

       },
      child: new Icon(
        Icons.arrow_forward,
        color: Colors.white,
        size: 20.0,
      ),
      shape: new CircleBorder(),
      color: Colors.black12,
    )
</code>```

The result is

Body:
You can easily do the following:

FlatButton(
      onPressed: () {

       },
      child: new Icon(
        Icons.arrow_forward,
        color: Colors.white,
        size: 20.0,
      ),
      shape: new CircleBorder(),
      color: Colors.black12,
    )

The result is


问:
How to edit the display of date & time on order note of woocommerce?
https://imgur.com/a/BOuuHWt

The date / time display on the order detail page is displayed differently from the woocommerce setting.

I want to change the displayed date / time like this.
e.g.) Tuesday 28th 2019 May, 02:37 pm -> 2019-05-28 14:37

I think it would be nice to have a fix in the functions.php in the child theme.
Could you help me?

Best,

```<code><p class="woocommerce-OrderUpdate-meta meta">
    <?php echo date_i18n( __( 'l jS \o\f F Y, h:ia', 'woocommerce' ), strtotime( $note->comment_date ) ); ?>
</p>
</code>```

答: You need to replace your time format l jS \o\f F Y, h:ia to Y-m-d Hi

Body:
https://imgur.com/a/BOuuHWt

The date / time display on the order detail page is displayed differently from the woocommerce setting.

I want to change the displayed date / time like this.
e.g.) Tuesday 28th 2019 May, 02:37 pm -> 2019-05-28 14:37

I think it would be nice to have a fix in the functions.php in the child theme.
Could you help me?

Best,

    <?php echo date_i18n( __( 'l jS \o\f F Y, h:ia', 'woocommerce' ), strtotime( $note->comment_date ) ); ?>


问:
How do I run .map() starting from the second index onward?
I need to use map starting from the second index. I know how to use loop for with I start from 1 but I want to use map in this case.

Is there a correct way to do this with map?

I'm using JavaScript and ReactJS.

答:
Just slice before you map:

const arr = [1, 2, 3, 4];
const res = arr.slice(1).map(e => e * 2);
console.log(res);```
</div>
</div>
</p>
<p>Alternatively, use <code>shift</code> after mapping the full array:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const arr = [1, 2, 3, 4];
const res = arr.map(e => e * 2);
res.shift();
console.log(res);</code>```

Body:
Just slice before you map:

const arr = [1, 2, 3, 4];
const res = arr.slice(1).map(e => e * 2);
console.log(res);

Alternatively, use shift after mapping the full array:

const arr = [1, 2, 3, 4];
const res = arr.map(e => e * 2);
res.shift();
console.log(res);


问:
WPF validation, regular expression
I have problem with validation in wpf . I have a text textbox

```<code><TextBox x:Name="Login"  Grid.Column="2" Grid.Row="2">
        <TextBox.Text>
            <Binding  Mode="TwoWay" Path="Email"  UpdateSourceTrigger="PropertyChanged">
                <Binding.ValidationRules>
                    <DataErrorValidationRule />
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
        <TextBox.Style>
                <Setter Property="Validation.ErrorTemplate">
                    <Setter.Value>
                        <ControlTemplate>
                            <DockPanel LastChildFill="True">
                                <TextBlock DockPanel.Dock="Bottom" Foreground="Maroon" FontSize="10pt"
                                           Text="{Binding ElementName=Emael, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
                                </TextBlock>
                                <Border BorderBrush="DarkRed" BorderThickness="1">
                                    <AdornedElementPlaceholder Name="Emael" />
                                </Border>
                            </DockPanel>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </TextBox.Style>
    </TextBox>
</code>```

and the properties

```<code> public string Error => throw new NotImplementedException();

    public string this[string columnName]
    {
        get
        {
            string error = String.Empty;

            switch (columnName)
            {
                case "Email":
                    if (Email == null || Email == string.Empty)
                    {
                        error = "Field login must be required";
                    }
                    break;
            }
            return error;
        }
    }
</code>```

I don't know how use regular expression here, in a back-end I use the dataAnnotation

```<code>[Required(ErrorMessage = "This field should be filled in")]
[RegularExpression(@"\w+(@)[a-zA-z]+(\.)[a-zA-z]+", ErrorMessage = ("Use the right email format"))]
</code>```

how write the same logic in form (client validation). may be better to write my own validation class and somehow connect with property? What better to do?

答:
You could copy the annotations to your view model and implement a method that validates them for you:

```<code>[Required(ErrorMessage = "This field should be filled in")]
[RegularExpression(@"\w+(@)[a-zA-z]+(\.)[a-zA-z]+", ErrorMessage = ("Use the right email format"))]
public string Email { get; set; }

public string Error => throw new NotImplementedException();

public string this[string columnName]
{
    get
    {
        string error = String.Empty;

        switch (columnName)
        {
            case "Email":
                return ValidateModelProperty(Email, columnName);
        }
        return error;
    }
}

private string ValidateModelProperty(object value, string propertyName)
{
    ICollection<ValidationResult> validationResults = new List<ValidationResult>();
    ValidationContext validationContext =
        new ValidationContext(this, null, null) { MemberName = propertyName };
    if (!Validator.TryValidateProperty(value, validationContext, validationResults))
        foreach (ValidationResult validationResult in validationResults)
            return validationResult.ErrorMessage;
    return null;
}
</code>```

Please refer to this blog post for more information.

Title: WPF validation, regular expression

Body:
I have problem with validation in wpf . I have a text textbox

<TextBox x:Name="Login"  Grid.Column="2" Grid.Row="2">
        <TextBox.Text>
            <Binding  Mode="TwoWay" Path="Email"  UpdateSourceTrigger="PropertyChanged">
                <Binding.ValidationRules>
                    <DataErrorValidationRule />
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
        <TextBox.Style>
                <Setter Property="Validation.ErrorTemplate">
                    <Setter.Value>
                        <ControlTemplate>
                            <DockPanel LastChildFill="True">
                                <TextBlock DockPanel.Dock="Bottom" Foreground="Maroon" FontSize="10pt"
                                           Text="{Binding ElementName=Emael, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
                                </TextBlock>
                                <Border BorderBrush="DarkRed" BorderThickness="1">
                                    <AdornedElementPlaceholder Name="Emael" />
                                </Border>
                            </DockPanel>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </TextBox.Style>
    </TextBox>

and the properties

 public string Error => throw new NotImplementedException();

    public string this[string columnName]
    {
        get
        {
            string error = String.Empty;

            switch (columnName)
            {
                case "Email":
                    if (Email == null || Email == string.Empty)
                    {
                        error = "Field login must be required";
                    }
                    break;
            }
            return error;
        }
    }

I don't know how use regular expression here, in a back-end I use the dataAnnotation

[Required(ErrorMessage = "This field should be filled in")]
[RegularExpression(@"\w+(@)[a-zA-z]+(\.)[a-zA-z]+", ErrorMessage = ("Use the right email format"))]

how write the same logic in form (client validation). may be better to write my own validation class and somehow connect with property? What better to do?

Body:
You could copy the annotations to your view model and implement a method that validates them for you:

[Required(ErrorMessage = "This field should be filled in")]
[RegularExpression(@"\w+(@)[a-zA-z]+(\.)[a-zA-z]+", ErrorMessage = ("Use the right email format"))]
public string Email { get; set; }

public string Error => throw new NotImplementedException();

public string this[string columnName]
{
    get
    {
        string error = String.Empty;

        switch (columnName)
        {
            case "Email":
                return ValidateModelProperty(Email, columnName);
        }
        return error;
    }
}

private string ValidateModelProperty(object value, string propertyName)
{
    ICollection<ValidationResult> validationResults = new List<ValidationResult>();
    ValidationContext validationContext =
        new ValidationContext(this, null, null) { MemberName = propertyName };
    if (!Validator.TryValidateProperty(value, validationContext, validationResults))
        foreach (ValidationResult validationResult in validationResults)
            return validationResult.ErrorMessage;
    return null;
}

Please refer to this blog post for more information.


问:
How to replace a word in a blob with the next blob entry of the database table
I'm trying building a page which is able to read a table and write the Selected entries (time, sender, recipient, title and content) down which is working perfectly fine.

The problem I'm facing is the first content Entry is a text BLOB like this

```<code>ex.
TextTextTextTextTextText
TextTextTextText
img1.jpg
TextTextTextTextText
TextTextTextTextTextText
</code>```

the img1.jpg is saved in the next content entry saved a BLOB and has to be base64 encoded to be printed as a image and now I'm stuck while trying to write it down like this

```<code>TextTextTextTextTextText
TextTextTextText
(actual image from the next entry)
TextTextTextTextText
TextTextTextTextTextText
</code>```

I have tried to check with strpos if the content contains the filename of the next blob and then to replace that with the actual image but I can't manage to get the next table entry in the same row

Here is the code for the normal output

```<code>$res = mysqli_query($link, createRequest(true, $link)) or die(mysqli_error($link));
while($row = mysqli_fetch_assoc($res)){

    $title = $row["a_subject"];
    $time = $row["create_time"];
    $sender = $row["a_from"];
    $reciever = $row["a_to"];
    $body = $row["content"];
    $articleid = $row["id"];

    if (strpos($body, '')){
        $img = "```".''."```"

    ?>
    <tr>
    <td><?php echo ($time) ?></td>
    <td><?php echo ($sender) ?></td>
    <td><?php echo ($reciever) ?></td>
    <td><?php echo ($title) ?></td>
    <td><?php echo $img ?></td>
    <td>>Zeige Anhänge</td>
    </tr>
    <?php
    } else {
        ?>
    <tr>
    <td><?php echo ($time) ?></td>
    <td><?php echo ($sender) ?></td>
    <td><?php echo ($reciever) ?></td>
    <td><?php echo ($title) ?></td>
    <td><?php echo utf8_encode($body)?></td>
    <td>>Zeige Anhänge</td>
    </tr>
    <?php
</code>```

Right now I'm checking if the content is an image or just some text and then writing them down. What I want to be happening is that lets say the text content is:

```<code>text
img1
text
img2
text
img3
</code>```

which my current solution i get 4 html table entries
with the first being

```<code>text
img1.jpg
text
img2.jpg
text
img3 .jpg
</code>```

the second being

```<code>actual image of img1.jpg
</code>```

the third being

```<code>actual image of img2.jpg
</code>```

etc

What i want in the end is one table entry that looks like this

```<code>text
actual img1
text
actual img2
text
actual img3
</code>```

答:
OK, so from what I can gather, you've got some rows in this table which are actual content that you want to display, including references to some image filenames, then in the same table you have these actual images stored as base64 encoded BLOBs.

Impossible for me to test... so have a play around with it, and see if it offers what you're interested in.

I've commented my additions to make them more clear.

Oh and also I've used <?= shorthand purely because I think it makes the code a bit easier to read/more accessible. You obviously don't need to use this if you don't want to!

```<code><?php

<<PUT ANY OTHER EXISTING CODE HERE, E.G. THE START OF YOUR SCRIPT>>
$res = mysqli_query($link, createRequest(true, $link)) or die(mysqli_error($link));

// This function serves a dual purpose
// Given an image filename, e.g. `image001.png`, it will search the table for this filename and (hopefully) return a base64 encoded BLOB
// It then decodes this content and returns it
function get_image_from_filename ($filename, $db_connection) {
    $query = "SELECT article_attachment.content FROM article JOIN ticket ON article.ticket_id = ticket.id JOIN article_attachment on article.id = article_attachment.article_id WHERE article_attachment.filename = '$filename'";

    $res = mysqli_query($db_connection, $query) or die(mysqli_error($db_connection));

    while ($row = mysqli_fetch_assoc($res)) {
        return base64_decode($row["content"]);
    }
}

while($row = mysqli_fetch_assoc($res)) {

    $title = $row["a_subject"];
    $time = $row["create_time"];
    $sender = $row["a_from"];
    $reciever = $row["a_to"];
    $body = $row["content"];
    $articleid = $row["id"];

    if (base64_encode(base64_decode($body, true)) === $data){
        // If the `$body` can be decoded/encoded successfully, this row is an image - let's skip it
        continue;
    }
    else {
        // Otherwise, let's find all of the references to our images, and look them up in the database

        // This pattern will find the CID references and retrieve the associated image's filename
        $pattern = '/(?:cid:)([a-zA-Z0-9]+\.[a-zA-Z0-9]+)(@[a-zA-Z0-9]+\.[a-zA-Z0-9]+)+/';
        // This is the replacement that will be put into the `$body` variable, using the function at the top of this script
        $replacement = "```" . '' . "```";

        $body = preg_replace($pattern, $replacement, $body);

?>

<tr>
    <td><?=$time?></td>
    <td><?=$sender?></td>
    <td><?=$receiver?></td>
    <td><?=$title?></td>
    <td><?=$body?></td>
    <td>">Zeige Anhänge</td>
</tr>

<?php

    } // End base64 if

}
</code>```

Body:
I'm trying building a page which is able to read a table and write the Selected entries (time, sender, recipient, title and content) down which is working perfectly fine.

The problem I'm facing is the first content Entry is a text BLOB like this

ex.
TextTextTextTextTextText
TextTextTextText
img1.jpg
TextTextTextTextText
TextTextTextTextTextText

the img1.jpg is saved in the next content entry saved a BLOB and has to be base64 encoded to be printed as a image and now I'm stuck while trying to write it down like this

TextTextTextTextTextText
TextTextTextText
(actual image from the next entry)
TextTextTextTextText
TextTextTextTextTextText

I have tried to check with strpos if the content contains the filename of the next blob and then to replace that with the actual image but I can't manage to get the next table entry in the same row

Here is the code for the normal output

$res = mysqli_query($link, createRequest(true, $link)) or die(mysqli_error($link));
while($row = mysqli_fetch_assoc($res)){

    $title = $row["a_subject"];
    $time = $row["create_time"];
    $sender = $row["a_from"];
    $reciever = $row["a_to"];
    $body = $row["content"];
    $articleid = $row["id"];

    if (strpos($body, '')){
        $img = "
".''."
"

    ?>

    <?php echo ($time) ?>
    <?php echo ($sender) ?>
    <?php echo ($reciever) ?>
    <?php echo ($title) ?>
    <?php echo $img ?>
    <a href=<?php echo "http://localhost/php/imageviewer.php?ArticleID=".$row["id"].""?>>Zeige Anhänge

    <?php
    } else {
        ?>

    <?php echo ($time) ?>
    <?php echo ($sender) ?>
    <?php echo ($reciever) ?>
    <?php echo ($title) ?>
    <?php echo utf8_encode($body)?>
    <a href=<?php echo "http://localhost/php/imageviewer.php?ArticleID=".$row["id"].""?>>Zeige Anhänge

    <?php

Right now I'm checking if the content is an image or just some text and then writing them down. What I want to be happening is that lets say the text content is:

text
img1
text
img2
text
img3

which my current solution i get 4 html table entries
with the first being

text
img1.jpg
text
img2.jpg
text
img3 .jpg

the second being

actual image of img1.jpg

the third being

actual image of img2.jpg

etc

What i want in the end is one table entry that looks like this

text
actual img1
text
actual img2
text
actual img3

Body:
OK, so from what I can gather, you've got some rows in this table which are actual content that you want to display, including references to some image filenames, then in the same table you have these actual images stored as base64 encoded BLOBs.

Impossible for me to test... so have a play around with it, and see if it offers what you're interested in.

I've commented my additions to make them more clear.

Oh and also I've used <?= shorthand purely because I think it makes the code a bit easier to read/more accessible. You obviously don't need to use this if you don't want to!

<?php

<<PUT ANY OTHER EXISTING CODE HERE, E.G. THE START OF YOUR SCRIPT>>
$res = mysqli_query($link, createRequest(true, $link)) or die(mysqli_error($link));

// This function serves a dual purpose
// Given an image filename, e.g. `image001.png`, it will search the table for this filename and (hopefully) return a base64 encoded BLOB
// It then decodes this content and returns it
function get_image_from_filename ($filename, $db_connection) {
    $query = "SELECT article_attachment.content FROM article JOIN ticket ON article.ticket_id = ticket.id JOIN article_attachment on article.id = article_attachment.article_id WHERE article_attachment.filename = '$filename'";

    $res = mysqli_query($db_connection, $query) or die(mysqli_error($db_connection));

    while ($row = mysqli_fetch_assoc($res)) {
        return base64_decode($row["content"]);
    }
}

while($row = mysqli_fetch_assoc($res)) {

    $title = $row["a_subject"];
    $time = $row["create_time"];
    $sender = $row["a_from"];
    $reciever = $row["a_to"];
    $body = $row["content"];
    $articleid = $row["id"];

    if (base64_encode(base64_decode($body, true)) === $data){
        // If the `$body` can be decoded/encoded successfully, this row is an image - let's skip it
        continue;
    }
    else {
        // Otherwise, let's find all of the references to our images, and look them up in the database

        // This pattern will find the CID references and retrieve the associated image's filename
        $pattern = '/(?:cid:)([a-zA-Z0-9]+\.[a-zA-Z0-9]+)(@[a-zA-Z0-9]+\.[a-zA-Z0-9]+)+/';
        // This is the replacement that will be put into the `$body` variable, using the function at the top of this script
        $replacement = "<pre>" . '<img src="data:image/jpeg;base64,' . get_image_from_filename('$1', $link) . '" />' . "</pre>";

        $body = preg_replace($pattern, $replacement, $body);

?>

<tr>
    <td><?=$time?></td>
    <td><?=$sender?></td>
    <td><?=$receiver?></td>
    <td><?=$title?></td>
    <td><?=$body?></td>
    <td><a href="http://localhost/php/imageviewer.php?ArticleID=<?=$articleid?>">Zeige Anhänge</a></td>
</tr>

<?php

    } // End base64 if

}


问:
What is __pycache__?
From what I understand, a cache is an encrypted file of similar files.

What do we do with the __pycache__ folder? Is it what we give to people instead of our source code? Is it just my input data? This folder keeps getting created, what it is for?

答:
Execution of a python script would cause the byte code to be generated in memory and kept until the program is shutdown.
In case a module is imported, for faster reusability, Python would create a cache .pyc (PYC is 'Python' 'Compiled') file where the byte code of the module being imported is cached.
Idea is to speed up loading of python modules by avoiding re-compilation ( compile once, run multiple times policy ) when they are re-imported.

The name of the file is the same as the module name. The part after the initial dot indicates Python implementation that created the cache (could be CPython) followed by its version number.

Title: What is __pycache__?


问:
Is it possible to have a public API gateway open to the world in front of a private EC2 instance?
I was wondering if this is possible. I need to setup up a public API gateway open to the world, connecting to an annoying legacy API running in a docker swarm on an ec2 instance.

I followed the guides on how to set it up here https://aws.amazon.com/blogs/compute/introducing-amazon-api-gateway-private-endpoints/, but my API gateway is only available from inside the private EC2 instances. Is it possible to make that API gateway public without exposing the EC2 instance?

I just want to use the API gateway in a way to avoid using the basic auth that this legacy program requires.

I feel like i am missing just one simple part.

Here is the part that makes me thing why its only internally available. all my working APIs attached to lambda functions just say InvokeURL

https://imgur.com/a/vrRTY9Z

[Solved] I had chosen to create my Gateway as private instead of regional when first creating it. Recreating the API gateway as regional again fixed this issue

答:
Yes you can, following will be AWS services you will need to use.

API Gateway -> VPC Link -> NLB/ALB -> EC2 Instances

follow steps given here -> https://docs.aws.amazon.com/apigateway/latest/developerguide/getting-started-with-private-integration.html


问:
sapui5:How to display base64 image in Rich text editor?
I created an img element string with base64 source. when tried to display it in sap.ui.richtexteditor.RichTextEditor, I got nothing. How to display it? see my code.</p>

```<code>// controller
var template = {};
var image ="<img src="data:image/bmp;base64,/9j/4AAQSkZJRg...">";
template.body = image;
var oViewModel = new JSONModel(template);
this.getView().setModel(oViewModel, "template");
//view
<rte:RichTextEditor id="rte" value="{template>/body}" editorType="TinyMCE4" customToolbar="true" showGroupFont="true" showGroupInsert="true"
showGroupLink="true" height="360px"/>
</code>```

答:
why dont use the Image Control?

<Image src='data:image/png;base64,iVBORw0KGgoA...........=='/>

Body:
I created an img element string with base64 source. when tried to display it in sap.ui.richtexteditor.RichTextEditor, I got nothing. How to display it? see my code.

// controller
var template = {};
var image ="";
template.body = image;
var oViewModel = new JSONModel(template);
this.getView().setModel(oViewModel, "template");
//view
<rte:RichTextEditor id="rte" value="{template>/body}" editorType="TinyMCE4" customToolbar="true" showGroupFont="true" showGroupInsert="true"
showGroupLink="true" height="360px"/>


问:
Where can I find a list of all npm flags / tags / options?
I am looking for the meaning of the flag --u as in "npm run test --u" but I don't know where all the flags are documented.

Here at the bottom are some shorthands, but besides "gangster" and other cool ones, I couldn't find --u
https://github.com/npm/npmconf/blob/master/config-defs.js#L405

答:
"npm run test --u" ("--u") belongs to jest flag --updateSnapshot. If you run  npm run test help or npm test help you will get all the flags of jest.

Inorder to get npm flags list or npm commands you can run this command npm -l


问:
Unable to make public long com.sun.management.internal.OperatingSystemImpl.getOpenFileDescriptorCount()
I am getting the below error in server log in Java 11. Is there any solution for it?</p>

```<code>[2019-05-02 18:06:18 IST] [] ERROR com.codahale.metrics.ScheduledReporter [SID= UID= BGCD=] - Exception thrown from Slf4jReporter#report. Exception was suppressed.
java.lang.reflect.InaccessibleObjectException: Unable to make public long com.sun.management.internal.OperatingSystemImpl.getOpenFileDescriptorCount() accessible: module jdk.management does not "opens com.sun.management.internal" to unnamed module @489448ac
    at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:340)
    at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:280)
    at java.base/java.lang.reflect.Method.checkCanSetAccessible(Method.java:198)
    at java.base/java.lang.reflect.Method.setAccessible(Method.java:192)
    at deployment.myPage.war//com.codahale.metrics.jvm.FileDescriptorRatioGauge.invoke(FileDescriptorRatioGauge.java:48)
    at deployment.myPage.war//com.codahale.metrics.jvm.FileDescriptorRatioGauge.getRatio(FileDescriptorRatioGauge.java:35)
    at deployment.myPage.war//com.codahale.metrics.RatioGauge.getValue(RatioGauge.java:64)
    at deployment.myPage.war//com.codahale.metrics.RatioGauge.getValue(RatioGauge.java:11)
    at deployment.myPage.war//com.codahale.metrics.DerivativeGauge.getValue(DerivativeGauge.java:23)
    at deployment.myPage.war//com.codahale.metrics.Slf4jReporter.logGauge(Slf4jReporter.java:306)
    at deployment.myPage.war//com.codahale.metrics.Slf4jReporter.report(Slf4jReporter.java:220)
    at deployment.myPage.war//com.codahale.metrics.ScheduledReporter.report(ScheduledReporter.java:243)
    at deployment.myPage.war//com.codahale.metrics.ScheduledReporter$1.run(ScheduledReporter.java:182)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
    at java.base/java.util.concurrent.FutureTask.runAndReset(FutureTask.java:305)
    at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:305)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
</code>```

答:
One of the dependencies of your project is trying to access a jvm api which was moved to an internal java module, and is no longer exposed.

Running the application with following flag should solve the problem:

```<code>--add-opens jdk.management/com.sun.management.internal=ALL-UNNAMED
</code>```

Body:
I am getting the below error in server log in Java 11. Is there any solution for it?

[2019-05-02 18:06:18 IST] [] ERROR com.codahale.metrics.ScheduledReporter [SID= UID= BGCD=] - Exception thrown from Slf4jReporter#report. Exception was suppressed.
java.lang.reflect.InaccessibleObjectException: Unable to make public long com.sun.management.internal.OperatingSystemImpl.getOpenFileDescriptorCount() accessible: module jdk.management does not "opens com.sun.management.internal" to unnamed module @489448ac
    at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:340)
    at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:280)
    at java.base/java.lang.reflect.Method.checkCanSetAccessible(Method.java:198)
    at java.base/java.lang.reflect.Method.setAccessible(Method.java:192)
    at deployment.myPage.war//com.codahale.metrics.jvm.FileDescriptorRatioGauge.invoke(FileDescriptorRatioGauge.java:48)
    at deployment.myPage.war//com.codahale.metrics.jvm.FileDescriptorRatioGauge.getRatio(FileDescriptorRatioGauge.java:35)
    at deployment.myPage.war//com.codahale.metrics.RatioGauge.getValue(RatioGauge.java:64)
    at deployment.myPage.war//com.codahale.metrics.RatioGauge.getValue(RatioGauge.java:11)
    at deployment.myPage.war//com.codahale.metrics.DerivativeGauge.getValue(DerivativeGauge.java:23)
    at deployment.myPage.war//com.codahale.metrics.Slf4jReporter.logGauge(Slf4jReporter.java:306)
    at deployment.myPage.war//com.codahale.metrics.Slf4jReporter.report(Slf4jReporter.java:220)
    at deployment.myPage.war//com.codahale.metrics.ScheduledReporter.report(ScheduledReporter.java:243)
    at deployment.myPage.war//com.codahale.metrics.ScheduledReporter$1.run(ScheduledReporter.java:182)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
    at java.base/java.util.concurrent.FutureTask.runAndReset(FutureTask.java:305)
    at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:305)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)

Body:
One of the dependencies of your project is trying to access a jvm api which was moved to an internal java module, and is no longer exposed.

Running the application with following flag should solve the problem:

--add-opens jdk.management/com.sun.management.internal=ALL-UNNAMED


问:
How to catch a no parse exception from the read function in Haskell?
In my Haskell program, I want to read in a value given by the user using the getLine function.  I then want to use the read function to convert this value from a string to the appropriate Haskell type.  How can I catch parse errors thrown by the read function and ask the user to reenter the value?

Am I right in thinking that this is not an "IO Error" because it is not an error caused by the IO system not functioning correctly?  It is a semantic error, so I can't use IO error handling mechanisms?

答:
Here's an improved maybeRead which allows only for trailing whitespaces, but nothing else:

```<code>import Data.Maybe
import Data.Char

maybeRead2 :: Read a => String -> Maybe a
maybeRead2 = fmap fst . listToMaybe . filter (null . dropWhile isSpace . snd) . reads
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Here's an improved maybeRead which allows only for trailing whitespaces, but nothing else:

import Data.Maybe
import Data.Char

maybeRead2 :: Read a => String -> Maybe a
maybeRead2 = fmap fst . listToMaybe . filter (null . dropWhile isSpace . snd) . reads


问:
How do I add data into html table using jquery?
I'm trying to add data from my firebase realtime database into a html table using jquery and javascript. I'm new to jquery, so I more or less have no idea what I'm doing.
I can retrieve the data but I can't add it to the table on the html page.
Is something wrong with this line?:

```<code>$("#table_body tbody").append("<tr><td>" + name.Name + "</td><td>" +
user.Email +  "</td></td></td></tr>");
</code>```

the table_body is just the table's id. The table remains empty.
pls help

答:
You can add things to a table like this:</p>

```<code>function productsAdd() {
  $("#productTable tbody").append(
      "<tr>" +
        "<td>My First Item</td>" +
        "<td>6/11/2019</td>" +
        "<td>www.itemsite.com</td>" +
      "</tr>"
  );
}
</code>```

Body:
I'm trying to add data from my firebase realtime database into a html table using jquery and javascript. I'm new to jquery, so I more or less have no idea what I'm doing.
I can retrieve the data but I can't add it to the table on the html page.
Is something wrong with this line?:

$("#table_body tbody").append("
" + name.Name + "	" +
user.Email +  "
");

the table_body is just the table's id. The table remains empty.
pls help

Body:
You can add things to a table like this:

function productsAdd() {
  $("#productTable tbody").append(
      "<tr>" +
        "<td>My First Item</td>" +
        "<td>6/11/2019</td>" +
        "<td>www.itemsite.com</td>" +
      "</tr>"
  );
}


问:
Creating a list of leaves recursively in a binary tree java
My recursive function to count number of leaves in a Binary Tree works correctly:

```<code>public static int numberOfLeaves(BinaryTree<String> root) {

    if (root == null) return 0;
    else if(root.isLeaf()) return 1;
    int left = numberOfLeaves(root.leftTree);
    int right = numberOfLeaves(root.rightTree);
    return (left + right);
}
</code>```

But now I want to sum up the data of all the leaves in a List and return it.

Have a look at my hopeless attempt:

```<code>public ArrayList<String> getDataLeaves(BinaryTree<String> root) {

    ArrayList<String> list = new ArrayList<>();

    if (root == null) return list;
    else if (root.isLeaf()) list.add(root.data);
    else if(root.leftTree != null ) getDataLeaves(root.leftTree);
    else getDataLeaves(root.rightTree);

    return list;
}
</code>```

Can I (how do I) use the functionality/style of my numberOfLeaves function to help me write a recursive function which will sum up the data of all the leaves in a list and return it.

Note:
a node is of type BinaryTree<String>
with data, leftTree,RightTree as instance variables.

答:
You should add the leaves returned by the recursive calls:</p>

```<code>public ArrayList<String> getDataLeaves(BinaryTree<String> root) {

    ArrayList<String> list = new ArrayList<>();

    if (root == null)
        return list;
    else if (root.isLeaf())
        list.add(root.data);
    else {
        list.addAll(getDataLeaves(root.leftTree));
        list.addAll(getDataLeaves(root.rightTree));
    }

    return list;
}
</code>```

Body:
My recursive function to count number of leaves in a Binary Tree works correctly:

public static int numberOfLeaves(BinaryTree<String> root) {

    if (root == null) return 0;
    else if(root.isLeaf()) return 1;
    int left = numberOfLeaves(root.leftTree);
    int right = numberOfLeaves(root.rightTree);
    return (left + right);
}

But now I want to sum up the data of all the leaves in a List and return it.

Have a look at my hopeless attempt:

public ArrayList<String> getDataLeaves(BinaryTree<String> root) {

    ArrayList<String> list = new ArrayList<>();

    if (root == null) return list;
    else if (root.isLeaf()) list.add(root.data);
    else if(root.leftTree != null ) getDataLeaves(root.leftTree);
    else getDataLeaves(root.rightTree);

    return list;
}

Can I (how do I) use the functionality/style of my numberOfLeaves function to help me write a recursive function which will sum up the data of all the leaves in a list and return it.

Note:
a node is of type BinaryTree<String>
with data, leftTree,RightTree as instance variables.

Body:
You should add the leaves returned by the recursive calls:

public ArrayList<String> getDataLeaves(BinaryTree<String> root) {

    ArrayList<String> list = new ArrayList<>();

    if (root == null)
        return list;
    else if (root.isLeaf())
        list.add(root.data);
    else {
        list.addAll(getDataLeaves(root.leftTree));
        list.addAll(getDataLeaves(root.rightTree));
    }

    return list;
}


问:
Is there a way to enable tor as system proxy settings through Python in Linux
I am working on a project which requires accessing some websites with and without tor enabled, and record the content differences.
I am working on deepin (which is a linux based debian distro), and using Python 2.7 to accomplish the task. The problem is that I have to manually enable/disable tor, and change the system proxy settings every time I run the script. Now, I am aware that I can issue a shell command from Python itself to enable tor (service tor start), but I cannot figure out how to enable/disable the system proxy settings from Python.

I have already tried this, but no luck.

答:
Use os.system to set the desired proxy like this.

```<code>import os
os.system("export http_proxy="http://username:Password@Proxy_IP:Port/")
</code>```

To unset, simply use

```<code>os.system("unset http_proxy")
</code>```

EDIT

Tor uses SOCKS proxy. For socks proxy, use

```<code>os.system("export socks_proxy="socks://username:Password@Proxy_IP:Port/")
</code>```

Body:
Use os.system to set the desired proxy like this.

import os
os.system("export http_proxy="http://username:Password@Proxy_IP:Port/")

To unset, simply use

os.system("unset http_proxy")

EDIT

Tor uses SOCKS proxy. For socks proxy, use

os.system("export socks_proxy="socks://username:Password@Proxy_IP:Port/")


问:
Not able to parse JSON file in JavaScript
I am using JavaScript to Parse the JSON file. But I am not able understand the error I am getting. Could anybody please help me on this topic.

**My Code:
Html file:

```<code><title>JSON Parser</title>
<script type="text/javascript">
    function webGLStart() {
       var request = new XMLHttpRequest();
       request.open("GET","test.json");
       var my_JSON_object = JSON.parse(request.responseText);
     alert (my_JSON_object.result[0]);
    }

</script>
</head>
<body onload="webGLStart();">
</body>
</html>
</code>```

test.json File:

```<code>{"result": [0,1,2,3,4] }
</code>```

alert in above code does not show anything on the webpage.

答:
Your code for making the Ajax request is not correct.

First, var request = new XMLHttpRequest(); will not work incase of IE 5, 6; i.e. you need to make cross-browser object of XMLHttp

Second, request.open("GET","test.json"); does not indicate this request to be asynchronous... i.e. you are missing the third boolean parameter (true / false)

Thirdly, you are not sending the request to the web server using:

```<code>request.send(null);
</code>```

Try following link for Ajax:

http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp

Try this link for Parsing JSON using Javascript:

http://json.org/js.html

Hope this helps.

Body:
I am using JavaScript to Parse the JSON file. But I am not able understand the error I am getting. Could anybody please help me on this topic.

**My Code:
Html file:

<title>JSON Parser</title>

test.json File:

{"result": [0,1,2,3,4] }

alert in above code does not show anything on the webpage.

Body:
Your code for making the Ajax request is not correct.

First, var request = new XMLHttpRequest(); will not work incase of IE 5, 6; i.e. you need to make cross-browser object of XMLHttp

Second, request.open("GET","test.json"); does not indicate this request to be asynchronous... i.e. you are missing the third boolean parameter (true / false)

Thirdly, you are not sending the request to the web server using:

request.send(null);

Try following link for Ajax:

http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp

Try this link for Parsing JSON using Javascript:

http://json.org/js.html

Hope this helps.