问:
Python find mean of all rows by a column and then find distance
I have a dataframe as below. I understand that df.groupby("degree").mean() would provide me mean by column degree. I would like to take those means and find distance between each data point and those mean. In this case. For each data point, I would like to get 3 distances from means (output of df.groupby("degree").mean()) (4,40) (2,80) and (4,94) and create 3 new columns. Distance should be calculated by formula, BCA_mean=(name-4)^3+(score-40)^3,M.Tech_mean=(name-2)^3+(score-80)^3,MBA_mean=(name-4)^3+(score-94)^3

```<code>import pandas as pd

# dictionary of lists
dict = {'name':[5, 4, 2, 3],
        'degree': ["MBA", "BCA", "M.Tech", "MBA"],
        'score':[90, 40, 80, 98]}

# creating a dataframe from a dictionary
df = pd.DataFrame(dict)

print (df)

   name  degree  score
0     5     MBA     90
1     4     BCA     40
2     2  M.Tech     80
3     3     MBA     98

df.groupby("degree").mean()

degree name score
BCA     4   40
M.Tech  2   80
MBA     4   94
</code>```

update1

my real dataset has more than 100 columns. i would prefer something that could suit that need. The logic is still the same, for each mean, subtract mean value from a column and take cube of each cell and add

I found something like below. But not sure if there is any other efficient way

```<code>y=df.groupby("degree").mean()
print (y)
import numpy as np
(np.square(df[['name','score']].subtract(y.iloc[0,:],axis=1))).sum(axis=1)

df["mean0"]=(np.square(df[['name','score']].subtract(y.iloc[0,:],axis=1))).sum(axis=1)
df
</code>```

Body:
I have a dataframe as below. I understand that df.groupby("degree").mean() would provide me mean by column degree. I would like to take those means and find distance between each data point and those mean. In this case. For each data point, I would like to get 3 distances from means (output of df.groupby("degree").mean()) (4,40) (2,80) and (4,94) and create 3 new columns. Distance should be calculated by formula, BCA_mean=(name-4)^3+(score-40)^3,M.Tech_mean=(name-2)^3+(score-80)^3,MBA_mean=(name-4)^3+(score-94)^3

import pandas as pd

# dictionary of lists
dict = {'name':[5, 4, 2, 3],
        'degree': ["MBA", "BCA", "M.Tech", "MBA"],
        'score':[90, 40, 80, 98]}

# creating a dataframe from a dictionary
df = pd.DataFrame(dict)

print (df)

   name  degree  score
0     5     MBA     90
1     4     BCA     40
2     2  M.Tech     80
3     3     MBA     98

df.groupby("degree").mean()

degree name score
BCA     4   40
M.Tech  2   80
MBA     4   94

update1

my real dataset has more than 100 columns. i would prefer something that could suit that need. The logic is still the same, for each mean, subtract mean value from a column and take cube of each cell and add

I found something like below. But not sure if there is any other efficient way

y=df.groupby("degree").mean()
print (y)
import numpy as np
(np.square(df[['name','score']].subtract(y.iloc[0,:],axis=1))).sum(axis=1)

df["mean0"]=(np.square(df[['name','score']].subtract(y.iloc[0,:],axis=1))).sum(axis=1)
df

Body:
import pandas as pd

# dictionary of lists
dict = {'degree': ["MBA", "BCA", "M.Tech", "MBA","BCA"],
        'name':[5, 4, 2, 3,2],
        'score':[90, 40, 80, 98,60],
       'game':[100,200,300,100,400],
       'money':[100,200,300,100,400],
       'loan':[100,200,300,100,400],
       'rent':[100,200,300,100,400],
       'location':[100,200,300,100,400]}

# creating a dataframe from a dictionary
df = pd.DataFrame(dict)

print (df)

dfx=df.groupby("degree").mean()
print(dfx)

def fun(x):

    if x[0]=='BCA':
        return x[1:] - dfx.iloc[0,:].tolist()
    if x[0]=='M.Tech':
            return x[1:]-dfx.iloc[1,:].tolist()
    if x[0]=='MBA':
            return x[1:]-dfx.iloc[2,:].tolist()

df_added=df.apply(fun,axis=1)
df_added

result

   degree  name  score  game  money  loan  rent  location
0     MBA     5     90   100    100   100   100       100
1     BCA     4     40   200    200   200   200       200
2  M.Tech     2     80   300    300   300   300       300
3     MBA     3     98   100    100   100   100       100
4     BCA     2     60   400    400   400   400       400
``````
mean  which is dfx
``````````
        name  score  game  money  loan  rent  location
degree
BCA        3     50   300    300   300   300       300
M.Tech     2     80   300    300   300   300       300
MBA        4     94   100    100   100   100       100
````````````
df_added********
difference of each element from their mean column value
``````````
        name    score   game    money   loan    rent    location
   0       1      -4       0       0       0       0    0
   1       1     -10    -100     -100   -100    -100    -100
   2       0       0       0       0       0       0    0
   3      -1       4       0       0       0       0    0
   4      -1      10      100     100    100     100    100


来源: stackexchange

问:
Equal Sign and Type Mismatch
When working with the standard widget toolkit (SWT), I usually use something like this to define my GridLayout:

```<code>layout.marginTop = layout.marginBottom =
    layout.marginLeft = layout.marginRight =
        layout.horizontalSpacing = layout.verticalSpacing = 20
</code>```

It works in java but not in scala.
It gives me type mismatch; Found: Unit Required: Int.

So how can this solve it?

答: You have to write multiple assignments separately. As the compiler says, an assignment in Scala returns Unit, which can be seen as Java's void.

ContentLicense: CC BY-SA 3.0

Title: Equal Sign and Type Mismatch

Body:
When working with the standard widget toolkit (SWT), I usually use something like this to define my GridLayout:

layout.marginTop = layout.marginBottom =
    layout.marginLeft = layout.marginRight =
        layout.horizontalSpacing = layout.verticalSpacing = 20

It works in java but not in scala.
It gives me type mismatch; Found: Unit Required: Int.

So how can this solve it?


问:
Arrange data in bracket based on specific order in Python
I have an array and after programming, I get the position and the value of non-zero data, which looks like (x, y, z) = (row, column, value)

```<code>[(0, 0, 1), (0, 1, 1), (1, 0, 1), (2, 3, 2), (3, 0, 3), (3, 1, 3), (3, 3, 2)]
</code>```

This result in order in 'the smallest number of row to the highest'.

Is there any method that I can make the result order in 'the smallest number of column to the highest' and also 'the smallest number of value to the highest'?

Thanks for any help!!

This is the code I used:

```<code>import numpy as np

groupMatrix = np.array([
[1, 1, 0, 0],
[1, 0, 0, 0],
[0, 0, 0, 2],
[3, 3, 0, 2]
])
i = np.nonzero(groupMatrix)

res = np.vstack([i, groupMatrix[i]])
print(list(zip(*res)))
</code>```

答:
You can certainly do that,

In this case you can sort the list of tuples by key which is the column

```<code>import numpy as np

groupMatrix = np.array([
[1, 1, 0, 0],
[1, 0, 0, 0],
[0, 0, 0, 2],
[3, 3, 0, 2]
])
i = np.nonzero(groupMatrix)

res = np.vstack([i, groupMatrix[i]])
arr = list(zip(*res))

col_sorted = sorted(arr, key=lambda item: item[1]) # sorted by column
val_sorted = sorted(arr, key=lambda item: item[2]) # sorted by value
</code>```

Hope it helps you!

ContentLicense: CC BY-SA 4.0

Body:
I have an array and after programming, I get the position and the value of non-zero data, which looks like (x, y, z) = (row, column, value)

[(0, 0, 1), (0, 1, 1), (1, 0, 1), (2, 3, 2), (3, 0, 3), (3, 1, 3), (3, 3, 2)]

This result in order in 'the smallest number of row to the highest'.

Is there any method that I can make the result order in 'the smallest number of column to the highest' and also 'the smallest number of value to the highest'?

Thanks for any help!!

This is the code I used:

import numpy as np

groupMatrix = np.array([
[1, 1, 0, 0],
[1, 0, 0, 0],
[0, 0, 0, 2],
[3, 3, 0, 2]
])
i = np.nonzero(groupMatrix)

res = np.vstack([i, groupMatrix[i]])
print(list(zip(*res)))

Body:
You can certainly do that,

In this case you can sort the list of tuples by key which is the column

import numpy as np

groupMatrix = np.array([
[1, 1, 0, 0],
[1, 0, 0, 0],
[0, 0, 0, 2],
[3, 3, 0, 2]
])
i = np.nonzero(groupMatrix)

res = np.vstack([i, groupMatrix[i]])
arr = list(zip(*res))

col_sorted = sorted(arr, key=lambda item: item[1]) # sorted by column
val_sorted = sorted(arr, key=lambda item: item[2]) # sorted by value

Hope it helps you!


问:
How to count each value in multiple rows and same column?
I have the problem to count the number of each tags.

For example:

```<code>    tags
0  a,b,c,d
1  a,b
2  c,d
3  a,c
</code>```

My Expected Results:

```<code>tags   count
  a      3
  b      2
  c      3
  d      2
</code>```

答:
Welcome to StackOverFlow!

Do you have an example of your code? Your tag says "SQL" so that's what I'll assume. I can't tell much from your question right now as you haven't given us enough info to help. It would be nice for future questions to add a bit more detail as to what you've tried to do already.

Still, I found this post that's on counting occurrences of column values, so it could answer your question. You can always edit your questions for clarity if need be!

Body:
I have the problem to count the number of each tags.

For example:

    tags
0  a,b,c,d
1  a,b
2  c,d
3  a,c

My Expected Results:

tags   count
  a      3
  b      2
  c      3
  d      2


问:
javascript calling a function expression itself from inside it with arguments
Please, someone, tell me how is the result 384 here.
According to me:
Called function value is greater than 2 so, the result should be
8 * fac(8 - 2)
64-2
ans: 62
I understand something happening with "fac" please explain. </p>

```<code>let factoria = function fac(n){
    return n < 2 ? 1 : n * fac(n - 2);
}

console.log(factoria(8));
// result 384
</code>```

答:
This line n * fac(n - 2) is recursively calling the itself with new value. At first it will be called with 8 * fac(8 - 2)so now fac will be called again with 6, then again with 4 and so on

let factoria = function fac(n) {
  console.log(n)
  return n < 2 ? 1 : n * fac(n - 2); // recursive function
}

console.log(factoria(8));```

Body:
Please, someone, tell me how is the result 384 here.
According to me:
Called function value is greater than 2 so, the result should be
8 * fac(8 - 2)
64-2
ans: 62
I understand something happening with "fac" please explain.

let factoria = function fac(n){
    return n < 2 ? 1 : n * fac(n - 2);
}

console.log(factoria(8));
// result 384


问:
Trying to run a Maven package. Unable to find resource 'org.eclipse.m2e:lifecycle-mapping:pom:1.0.0'
This is working well on Windows, but not on Linux and I don't know what I'm doing wrong here.

After I go to my maven project directory, the one that contains the POM.xml file, and "mvn package -e" it, here is the console output:

```<code>[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building functionalTests
[INFO]    task-segment: [package]
[INFO] ------------------------------------------------------------------------
Downloading: http://repo1.maven.org/maven2/org/eclipse/m2e/lifecycle-mapping/1.0.0/lifecycle-mapping-1.0.0.pom
[INFO] Unable to find resource 'org.eclipse.m2e:lifecycle-mapping:pom:1.0.0' in repository central (http://repo1.maven.org/maven2)
Downloading: http://repo1.maven.org/maven2/org/eclipse/m2e/lifecycle-mapping/1.0.0/lifecycle-mapping-1.0.0.pom
[INFO] Unable to find resource 'org.eclipse.m2e:lifecycle-mapping:pom:1.0.0' in repository central (http://repo1.maven.org/maven2)
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] Error building POM (may not be this project's POM).

Project ID: org.eclipse.m2e:lifecycle-mapping

Reason: POM 'org.eclipse.m2e:lifecycle-mapping' not found in repository: Unable to download the artifact from any repository

  org.eclipse.m2e:lifecycle-mapping:pom:1.0.0

from the specified remote repositories:
  central (http://repo1.maven.org/maven2)

 for project org.eclipse.m2e:lifecycle-mapping

[INFO] ------------------------------------------------------------------------
[INFO] Trace
org.apache.maven.lifecycle.LifecycleExecutionException: Unable to build project for plugin 'org.eclipse.m2e:lifecycle-mapping': POM 'org.eclipse.m2e:lifecycle-mapping' not found in repository: Unable to download the artifact from any repository

  org.eclipse.m2e:lifecycle-mapping:pom:1.0.0

from the specified remote repositories:
  central (http://repo1.maven.org/maven2)

 for project org.eclipse.m2e:lifecycle-mapping
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.verifyPlugin(DefaultLifecycleExecutor.java:1557)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.bindPluginToLifecycle(DefaultLifecycleExecutor.java:1503)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.constructLifecycleMappings(DefaultLifecycleExecutor.java:1282)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:534)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:387)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:348)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:180)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:328)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:138)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:362)
    at org.apache.maven.cli.compat.CompatibleMain.main(CompatibleMain.java:60)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:616)
    at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315)
    at org.codehaus.classworlds.Launcher.launch(Launcher.java:255)
    at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430)
    at org.codehaus.classworlds.Launcher.main(Launcher.java:375)
Caused by: org.apache.maven.plugin.InvalidPluginException: Unable to build project for plugin 'org.eclipse.m2e:lifecycle-mapping': POM 'org.eclipse.m2e:lifecycle-mapping' not found in repository: Unable to download the artifact from any repository

  org.eclipse.m2e:lifecycle-mapping:pom:1.0.0

from the specified remote repositories:
  central (http://repo1.maven.org/maven2)

 for project org.eclipse.m2e:lifecycle-mapping
    at org.apache.maven.plugin.DefaultPluginManager.checkRequiredMavenVersion(DefaultPluginManager.java:293)
    at org.apache.maven.plugin.DefaultPluginManager.verifyVersionedPlugin(DefaultPluginManager.java:205)
    at org.apache.maven.plugin.DefaultPluginManager.verifyPlugin(DefaultPluginManager.java:184)
    at org.apache.maven.plugin.DefaultPluginManager.loadPluginDescriptor(DefaultPluginManager.java:1642)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.verifyPlugin(DefaultLifecycleExecutor.java:1540)
    ... 18 more
Caused by: org.apache.maven.project.ProjectBuildingException: POM 'org.eclipse.m2e:lifecycle-mapping' not found in repository: Unable to download the artifact from any repository

  org.eclipse.m2e:lifecycle-mapping:pom:1.0.0

from the specified remote repositories:
  central (http://repo1.maven.org/maven2)

 for project org.eclipse.m2e:lifecycle-mapping
    at org.apache.maven.project.DefaultMavenProjectBuilder.findModelFromRepository(DefaultMavenProjectBuilder.java:605)
    at org.apache.maven.project.DefaultMavenProjectBuilder.buildFromRepository(DefaultMavenProjectBuilder.java:251)
    at org.apache.maven.plugin.DefaultPluginManager.checkRequiredMavenVersion(DefaultPluginManager.java:277)
    ... 22 more
Caused by: org.apache.maven.artifact.resolver.ArtifactNotFoundException: Unable to download the artifact from any repository

  org.eclipse.m2e:lifecycle-mapping:pom:1.0.0

from the specified remote repositories:
  central (http://repo1.maven.org/maven2)

    at org.apache.maven.artifact.resolver.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:228)
    at org.apache.maven.artifact.resolver.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:90)
    at org.apache.maven.project.DefaultMavenProjectBuilder.findModelFromRepository(DefaultMavenProjectBuilder.java:558)
    ... 24 more
Caused by: org.apache.maven.wagon.ResourceDoesNotExistException: Unable to download the artifact from any repository
    at org.apache.maven.artifact.manager.DefaultWagonManager.getArtifact(DefaultWagonManager.java:404)
    at org.apache.maven.artifact.resolver.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:216)
    ... 26 more
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1 second
[INFO] Finished at: Wed Sep 04 12:38:23 EEST 2013
[INFO] Final Memory: 4M/15M
</code>```

This is my pom.xml file

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.pragmaticqa.tests</groupId>
    <artifactId>mailCheckerTest</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>functionalTests</name>
    <url>http://maven.apache.org</url>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <displayProps>target/selenium/display.properties</displayProps>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-firefox-driver</artifactId>
            <version>2.33.0</version>
        </dependency>
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.7</version>
        </dependency>
        <dependency>
            <groupId>javax.activation</groupId>
            <artifactId>activation</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>2.33.0</version>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.8</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.maven.surefire</groupId>
            <artifactId>surefire</artifactId>
            <version>2.5</version>
            <type>pom</type>
        </dependency>
        <dependency>
            <groupId>net.sf.opencsv</groupId>
            <artifactId>opencsv</artifactId>
            <version>2.3</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.eclipse.m2e</groupId>
                <artifactId>lifecycle-mapping</artifactId>
                <version>1.0.0</version>
                <configuration>
                    <lifecycleMappingMetadata>
                        <pluginExecutions>
                            <pluginExecution>
                                <pluginExecutionFilter>
                                    <groupId>org.codehaus.mojo</groupId>
                                    <artifactId>aspectj-maven-plugin</artifactId>
                                    <versionRange>[1.0,)</versionRange>
                                </pluginExecutionFilter>
                                <action>
                                    <execute />
                                </action>
                            </pluginExecution>
                        </pluginExecutions>
                    </lifecycleMappingMetadata>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>selenium-maven-plugin</artifactId>
                <version>2.3</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.5</version>
                <configuration>
                    <includes>
                        <include>**/*Test*.java</include>
                    </includes>
                    <systemPropertyVariables>
                    </systemPropertyVariables>
                </configuration>
                <executions>
                    <execution>
                        <phase>integration-test</phase>
                        <goals>
                            <goal>test</goal>
                        </goals>
                        <configuration>
                            <skip>true</skip>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

And this is the output of "mvn -version"

```<code>Apache Maven 2.2.1 (rdebian-1)
Java version: 1.6.0_27
Java home: /usr/lib/jvm/java-6-openjdk/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux" version: "2.6.32-45-generic" arch: "i386" Family: "unix"
</code>```

答: run mvn eclipse:eclipse  from your project directory, this should resolve your m2e lifecycle plugin error.

Body:
This is working well on Windows, but not on Linux and I don't know what I'm doing wrong here.

After I go to my maven project directory, the one that contains the POM.xml file, and "mvn package -e" it, here is the console output:

[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building functionalTests
[INFO]    task-segment: [package]
[INFO] ------------------------------------------------------------------------
Downloading: http://repo1.maven.org/maven2/org/eclipse/m2e/lifecycle-mapping/1.0.0/lifecycle-mapping-1.0.0.pom
[INFO] Unable to find resource 'org.eclipse.m2e:lifecycle-mapping:pom:1.0.0' in repository central (http://repo1.maven.org/maven2)
Downloading: http://repo1.maven.org/maven2/org/eclipse/m2e/lifecycle-mapping/1.0.0/lifecycle-mapping-1.0.0.pom
[INFO] Unable to find resource 'org.eclipse.m2e:lifecycle-mapping:pom:1.0.0' in repository central (http://repo1.maven.org/maven2)
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] Error building POM (may not be this project's POM).

Project ID: org.eclipse.m2e:lifecycle-mapping

Reason: POM 'org.eclipse.m2e:lifecycle-mapping' not found in repository: Unable to download the artifact from any repository

  org.eclipse.m2e:lifecycle-mapping:pom:1.0.0

from the specified remote repositories:
  central (http://repo1.maven.org/maven2)

 for project org.eclipse.m2e:lifecycle-mapping

[INFO] ------------------------------------------------------------------------
[INFO] Trace
org.apache.maven.lifecycle.LifecycleExecutionException: Unable to build project for plugin 'org.eclipse.m2e:lifecycle-mapping': POM 'org.eclipse.m2e:lifecycle-mapping' not found in repository: Unable to download the artifact from any repository

  org.eclipse.m2e:lifecycle-mapping:pom:1.0.0

from the specified remote repositories:
  central (http://repo1.maven.org/maven2)

 for project org.eclipse.m2e:lifecycle-mapping
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.verifyPlugin(DefaultLifecycleExecutor.java:1557)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.bindPluginToLifecycle(DefaultLifecycleExecutor.java:1503)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.constructLifecycleMappings(DefaultLifecycleExecutor.java:1282)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:534)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:387)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:348)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:180)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:328)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:138)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:362)
    at org.apache.maven.cli.compat.CompatibleMain.main(CompatibleMain.java:60)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:616)
    at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315)
    at org.codehaus.classworlds.Launcher.launch(Launcher.java:255)
    at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430)
    at org.codehaus.classworlds.Launcher.main(Launcher.java:375)
Caused by: org.apache.maven.plugin.InvalidPluginException: Unable to build project for plugin 'org.eclipse.m2e:lifecycle-mapping': POM 'org.eclipse.m2e:lifecycle-mapping' not found in repository: Unable to download the artifact from any repository

  org.eclipse.m2e:lifecycle-mapping:pom:1.0.0

from the specified remote repositories:
  central (http://repo1.maven.org/maven2)

 for project org.eclipse.m2e:lifecycle-mapping
    at org.apache.maven.plugin.DefaultPluginManager.checkRequiredMavenVersion(DefaultPluginManager.java:293)
    at org.apache.maven.plugin.DefaultPluginManager.verifyVersionedPlugin(DefaultPluginManager.java:205)
    at org.apache.maven.plugin.DefaultPluginManager.verifyPlugin(DefaultPluginManager.java:184)
    at org.apache.maven.plugin.DefaultPluginManager.loadPluginDescriptor(DefaultPluginManager.java:1642)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.verifyPlugin(DefaultLifecycleExecutor.java:1540)
    ... 18 more
Caused by: org.apache.maven.project.ProjectBuildingException: POM 'org.eclipse.m2e:lifecycle-mapping' not found in repository: Unable to download the artifact from any repository

  org.eclipse.m2e:lifecycle-mapping:pom:1.0.0

from the specified remote repositories:
  central (http://repo1.maven.org/maven2)

 for project org.eclipse.m2e:lifecycle-mapping
    at org.apache.maven.project.DefaultMavenProjectBuilder.findModelFromRepository(DefaultMavenProjectBuilder.java:605)
    at org.apache.maven.project.DefaultMavenProjectBuilder.buildFromRepository(DefaultMavenProjectBuilder.java:251)
    at org.apache.maven.plugin.DefaultPluginManager.checkRequiredMavenVersion(DefaultPluginManager.java:277)
    ... 22 more
Caused by: org.apache.maven.artifact.resolver.ArtifactNotFoundException: Unable to download the artifact from any repository

  org.eclipse.m2e:lifecycle-mapping:pom:1.0.0

from the specified remote repositories:
  central (http://repo1.maven.org/maven2)

    at org.apache.maven.artifact.resolver.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:228)
    at org.apache.maven.artifact.resolver.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:90)
    at org.apache.maven.project.DefaultMavenProjectBuilder.findModelFromRepository(DefaultMavenProjectBuilder.java:558)
    ... 24 more
Caused by: org.apache.maven.wagon.ResourceDoesNotExistException: Unable to download the artifact from any repository
    at org.apache.maven.artifact.manager.DefaultWagonManager.getArtifact(DefaultWagonManager.java:404)
    at org.apache.maven.artifact.resolver.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:216)
    ... 26 more
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1 second
[INFO] Finished at: Wed Sep 04 12:38:23 EEST 2013
[INFO] Final Memory: 4M/15M

This is my pom.xml file

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.pragmaticqa.tests</groupId>
    <artifactId>mailCheckerTest</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>functionalTests</name>
    <url>http://maven.apache.org</url>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <displayProps>target/selenium/display.properties</displayProps>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-firefox-driver</artifactId>
            <version>2.33.0</version>
        </dependency>
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.7</version>
        </dependency>
        <dependency>
            <groupId>javax.activation</groupId>
            <artifactId>activation</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>2.33.0</version>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.8</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.maven.surefire</groupId>
            <artifactId>surefire</artifactId>
            <version>2.5</version>
            <type>pom</type>
        </dependency>
        <dependency>
            <groupId>net.sf.opencsv</groupId>
            <artifactId>opencsv</artifactId>
            <version>2.3</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.eclipse.m2e</groupId>
                <artifactId>lifecycle-mapping</artifactId>
                <version>1.0.0</version>
                <configuration>
                    <lifecycleMappingMetadata>
                        <pluginExecutions>
                            <pluginExecution>
                                <pluginExecutionFilter>
                                    <groupId>org.codehaus.mojo</groupId>
                                    <artifactId>aspectj-maven-plugin</artifactId>
                                    <versionRange>[1.0,)</versionRange>
                                </pluginExecutionFilter>
                                <action>
                                    <execute />
                                </action>
                            </pluginExecution>
                        </pluginExecutions>
                    </lifecycleMappingMetadata>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>selenium-maven-plugin</artifactId>
                <version>2.3</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.5</version>
                <configuration>
                    <includes>
                        <include>**/*Test*.java</include>
                    </includes>
                    <systemPropertyVariables>
                    </systemPropertyVariables>
                </configuration>
                <executions>
                    <execution>
                        <phase>integration-test</phase>
                        <goals>
                            <goal>test</goal>
                        </goals>
                        <configuration>
                            <skip>true</skip>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

And this is the output of "mvn -version"

Apache Maven 2.2.1 (rdebian-1)
Java version: 1.6.0_27
Java home: /usr/lib/jvm/java-6-openjdk/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux" version: "2.6.32-45-generic" arch: "i386" Family: "unix"


问:
cypress semantic-ui-react menu tests - not getting content of menu options
I am writing some tests here on a component that uses semantic-react-ui using cypress js to test with.

Here is the div containing the elements I wish to test on:

```<code><div data-testid="images-count" class="customize-row images-count">
   <h3 data-testid="option-name-8" class="option-name">Font Size</h3>
   <div data-testid="font-select" role="listbox" aria-expanded="true" class="ui active visible selection dropdown option-input images-select" tabindex="0">
      <div class="text" role="alert" aria-live="polite">Medium</div>
      <i aria-hidden="true" class="dropdown icon"></i>
      <div class="menu transition visible">
         <div role="option" aria-checked="false" aria-selected="false" class="item" style="pointer-events: all;"><span class="text">Small</span></div>
         <div role="option" aria-checked="true" aria-selected="true" class="active selected item" style="pointer-events: all;"><span class="text">Medium</span></div>
         <div role="option" aria-checked="false" aria-selected="false" class="item" style="pointer-events: all;"><span class="text">Large</span></div>
         <div role="option" aria-checked="false" aria-selected="false" class="item" style="pointer-events: all;"><span class="text">Extra Large</span></div>
      </div>
   </div>
</div>
</code>```

Here is a small test that I have done so far for elements within that div:

```<code>    cy.get("[data-testid=images-count]").within($result => {
       cy.findByRole("alert").should("have.text", "Medium");
       cy.get(".icon").should("be.visible");
       cy.get(".menu").should("not.be.visible");
       cy.get("[data-testid=font-select]").click();
       cy.get(".menu").should("be.visible");
    });
</code>```

I attempted to get the options from the menu into an array, then validate them against another array:

```<code>cy.get('.menu').then(options => {
  const actual = [...options].map(o => o.value)
  expect(actual).to.deep.eq(['Small', 'Medium', 'Large', 'Extra Large'])
})
</code>```

However this returns the list of divs and not the actual test contant I am looking for. Any ideas?

答:
To get options passed into .then(options => ...), you will need to be more specific in the cy.get() selector.

An element's text content would be returned from the o.innerText property instead of o.value.

cy.get('.menu .item').then(options => {
  const actual = [...options].map(o => o.innerText );
  expect(actual).to.deep.eq(['Small', 'Medium', 'Large', 'Extra Large']);
})
```

<hr>

<p>You can be a bit more concise by getting all the text in one string</p>

<pre class="lang-js prettyprint-override"><code>cy.get('.menu .item')
  .invoke('text')
  .should('eq', 'SmallMediumLargeExtra Large')

// OR

cy.get('.menu')
  .invoke('text')
  .should('eq', '\n  Small\n  Medium\n  Large\n  Extra Large\n')
</code>```

With these, be careful of the possibility of non-option text within the menu, as it just grabs all the text it can find within the selector you give it.

Body:
I am writing some tests here on a component that uses semantic-react-ui using cypress js to test with.

Here is the div containing the elements I wish to test on:

Font Size

Medium

Small

Medium

Large

Extra Large

Here is a small test that I have done so far for elements within that div:

    cy.get("[data-testid=images-count]").within($result => {
       cy.findByRole("alert").should("have.text", "Medium");
       cy.get(".icon").should("be.visible");
       cy.get(".menu").should("not.be.visible");
       cy.get("[data-testid=font-select]").click();
       cy.get(".menu").should("be.visible");
    });

I attempted to get the options from the menu into an array, then validate them against another array:

cy.get('.menu').then(options => {
  const actual = [...options].map(o => o.value)
  expect(actual).to.deep.eq(['Small', 'Medium', 'Large', 'Extra Large'])
})

However this returns the list of divs and not the actual test contant I am looking for. Any ideas?

Body:
To get options passed into .then(options => ...), you will need to be more specific in the cy.get() selector.

An element's text content would be returned from the o.innerText property instead of o.value.

cy.get('.menu .item').then(options => {
  const actual = [...options].map(o => o.innerText );
  expect(actual).to.deep.eq(['Small', 'Medium', 'Large', 'Extra Large']);
})

You can be a bit more concise by getting all the text in one string

cy.get('.menu .item')
  .invoke('text')
  .should('eq', 'SmallMediumLargeExtra Large')

// OR

cy.get('.menu')
  .invoke('text')
  .should('eq', '\n  Small\n  Medium\n  Large\n  Extra Large\n')

With these, be careful of the possibility of non-option text within the menu, as it just grabs all the text it can find within the selector you give it.


答:
You can use STRING_SPLIT to achieve this

```<code>SELECT
value, count(*) as countOfTags
FROM
(
VALUES
(0,  'a,b,c,d')
,(1,  'a,b'    )
,(2,  'c,d'    )
,(3,  'a,c'    )
) as t(id, tags)
CROSS APPLY
string_split(tags,',')
GROUP BY value;
</code>```

The result set

```<code>+-------+-------------+
| value | countOfTags |
+-------+-------------+
| a     |           3 |
| b     |           2 |
| c     |           3 |
| d     |           2 |
+-------+-------------+
</code>```

Title: How to count each value in multiple rows and same column?

Body:
You can use STRING_SPLIT to achieve this

SELECT
value, count(*) as countOfTags
FROM
(
VALUES
(0,  'a,b,c,d')
,(1,  'a,b'    )
,(2,  'c,d'    )
,(3,  'a,c'    )
) as t(id, tags)
CROSS APPLY
string_split(tags,',')
GROUP BY value;

The result set

+-------+-------------+
| value | countOfTags |
+-------+-------------+
| a     |           3 |
| b     |           2 |
| c     |           3 |
| d     |           2 |
+-------+-------------+


问:
PHP / MySQL: Error after delete a row ta PHP page (filtered)
I have a problem with my delete function. Before that, I will brief to you about the flow of the system

1) At dashboard_engineer.php, there's 3 select options which is team, time from and time to.

2) user need to select 3 select option and press button "Search" to display the result.

3) The result will display at dashboard_engineer2.php.

4) The result will display all data rows and each row contains one delete button.

My problem is, after I click button delete, it was successful delete but the dashboard_engineer2.php page doesn't display the result that same as point 3 above. The result empty.

What I want is that, after delete, the dashboard_engineer2.php will display the remaining data rows that already filtered before. Below is my code.

dashboard_engineer.php

```<code><?php

    $smt = $conn->prepare("SELECT * FROM ot_team INNER JOIN ot_users ON ot_team.team_id = ot_users.team_id WHERE ot_users.roles_id = 7 AND ot_users.team_id <> 1 ORDER BY ot_users.fullname ASC");
    $smt->execute();
    $data = $smt->fetchAll();

?>

<form method = 'post' action = 'dashboard_engineer2.php' >
  <td width="40%">
    <select class="form-control"  name="team" id="team" required>
      <option value="">Please select...</option>
      <?php foreach ($data as $row2): ?>
      <option value= <?php echo $row2["team_id"]; ?> ><?php echo $row2["fullname"]; ?></option>
      <?php endforeach ?>
    </select>
  </td>
  <td width="1%"></td>
  <td width="20%"><input type="text" name="from" id="from" class="form-control" placeholder="From" required></td>
  <td width="1%"></td>
  <td width="20%"><input type="text" name="to" id="to" class="form-control" placeholder="To" required></td>
  <td width="1%"></td>
  <td width="10%"><button type="submit" value="Search" class="btn btn-primary" >Send</button><td>
</form>

<script>
$(document).ready(function(){
  $.datepicker.setDefaults({
    dateFormat: 'yy-mm-dd'
  });
  $(function(){
    $("#from").datepicker().attr("autocomplete", "off");;
    $("#to").datepicker().attr("autocomplete", "off");;
  });

});
</script>
</code>```

dashboard_engineer2.php

```<code><?php

    if(isset($_POST["from"], $_POST["to"], $_POST["team"])){

        $result = '';
        $query = "SELECT * FROM ot_report LEFT JOIN ot_users ON ot_report.badgeid = ot_users.badgeid WHERE ot_users.team_id = '".$_POST["team"]."' AND report_date BETWEEN '".$_POST["from"]."' AND '".$_POST["to"]."' ORDER BY ot_report.report_date DESC";
        $sql = $conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
        $sql -> execute();

        if($sql->rowCount() > 0){

        echo'

        <table class = "table-bordered" width = "100%">
        <thead>
        <tr>
        <th width = "10%"><input type="checkbox" id="checkAl"> All</th>
        <th width = "3%">id</th>
        <th width = "15%">Date</th>
        <th width = "30%">Task Name</th>
        <th width = "10%">Status</th>
        <th colspan = "2" width = "7%">Action</th>
        </tr>
        </thead>
        <tbody>';

            $i=0;

            while($row = $sql->fetch(PDO::FETCH_ASSOC)){

            $datereport = $row['report_date'];
            $datereport2 = strtotime($datereport);
            $report_date = date('d M Y', $datereport2);

            $report_id = $row["report_id"];

            echo'<tr>';
                echo '<td><input type="checkbox" id="checkItem" name="check[]" value='.$row['report_id'].'></td>';
                echo '<td>'.$report_id.'</td>';
                echo '<td>'.$report_date.'</td>';
                echo '<td>'.$row["task_name"].'</td>';
                echo '<td align="center"><strong>'.$row["report_status"].'</strong></td>';
                echo '<td align="center">';
                echo '<form action = "view_task/view_task.php" method = "post">';
                echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
                echo '<button type = "submit" class="btn-primary">View</button>';
                echo '</form>';

                echo "<form action = 'delete.php' method = 'post' onClick=\"return confirm('Do you want to remove team?')\">";
                echo '<input type = "hidden" name = "from" value = "'.$_POST["from"].'">';
                echo '<input type = "hidden" name = "to" value = "'.$_POST["to"].'">';
                echo '<input type = "hidden" name = "team" value = "'.$_POST["team"].'">';
                echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
                echo '<button type = "submit" class="btn-danger">Delete</button>';
                echo '</form>';

                echo '</td>';
            echo '</tr>';
            $i++;

            }
            echo '<tr>';
                echo '<td><p align="center"><button type="submit" class="btn-danger btn-sm" name="save">DELETE</button></p></td>';
            echo '</tr>';
            echo '</form>';

        }
        else
        {
            echo '
            <table class = "table-bordered" width = "100%">
            <thead>
            <tr>
            <th width = "5%">id</th>
            <th width = "12%">Date</th>
            <th width = "23%">Task Name</th>
            <th width = "10%">Status</th>
            <th width = "7%">Action</th>
            </tr>
            <tr>
            <td colspan="5">No report found</td>
            </tr>';
        }
        echo '</body></table></div></div>';

        }

?>
</code>```

delete.php

```<code>  <?php

        $report_id = $_POST['report_id'];

        $sql = "DELETE FROM ot_report WHERE report_id=:report_id";
        $query = $conn->prepare($sql);
        $query->execute(array(':report_id' => $report_id));

        header("Location: dashboard_engineer2.php");

  ?>
</code>```

Can anyone help me on how to fix this?

答:
this case is the same as the question
PHP / MySQL: Display some error after successfully updated the data

that's because in dashboard_engineer2.php your code will display data from the database if the from, to, team variable is posted.

from delete.php redirect to dashboard_engineer2.php being the get method and the data that was previously posted is missing

change the delete.php code to be like this

```<code><?php
        $report_id = $_POST['report_id'];
        $from = $_POST['from'];
        $to = $_POST['to'];
        $team = $_POST['team'];

        $sql = "DELETE FROM ot_report WHERE report_id=:report_id";
        $query = $conn->prepare($sql);
        $query->execute(array(':report_id' => $report_id));

        // so that the data previously posted is taken
        // when redirecting to the dashboard_engineer2.php page
        // even though it is a GET method

        header("Location: dashboard_engineer2.php?from={$from}&to={$to}&team={$team}");
?>
</code>```

and there was a slight change in dashboard_engineer2.php to be like this

```<code><?php

    // change the initial conditions to be like this
    // $_REQUEST will get data if there is data in POST or GET

    if(isset($_REQUEST["from"], $_REQUEST["to"], $_REQUEST["team"])){

        $from = $_REQUEST['from'];
        $to   = $_REQUEST['to'];
        $team = $_REQUEST['team'];

        $result = '';
        $query = "SELECT * FROM ot_report LEFT JOIN ot_users ON ot_report.badgeid = ot_users.badgeid WHERE ot_users.team_id = '".$team."' AND report_date BETWEEN '".$from."' AND '".$to."' ORDER BY ot_report.report_date DESC";

        $sql = $conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
        $sql -> execute();

        if($sql->rowCount() > 0){

        echo'

        <table class = "table-bordered" width = "100%">
        <thead>
        <tr>
        <th width = "10%"><input type="checkbox" id="checkAl"> All</th>
        <th width = "3%">id</th>
        <th width = "15%">Date</th>
        <th width = "30%">Task Name</th>
        <th width = "10%">Status</th>
        <th colspan = "2" width = "7%">Action</th>
        </tr>
        </thead>
        <tbody>';

            $i=0;

            while($row = $sql->fetch(PDO::FETCH_ASSOC)){

            $datereport = $row['report_date'];
            $datereport2 = strtotime($datereport);
            $report_date = date('d M Y', $datereport2);

            $report_id = $row["report_id"];

            echo'<tr>';
                echo '<td><input type="checkbox" id="checkItem" name="check[]" value='.$row['report_id'].'></td>';
                echo '<td>'.$report_id.'</td>';
                echo '<td>'.$report_date.'</td>';
                echo '<td>'.$row["task_name"].'</td>';
                echo '<td align="center"><strong>'.$row["report_status"].'</strong></td>';
                echo '<td align="center">';
                echo '<form action = "view_task/view_task.php" method = "post">';
                echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
                echo '<button type = "submit" class="btn-primary">View</button>';
                echo '</form>';

                echo "<form action = 'delete.php' method = 'post' onClick=\"return confirm('Do you want to remove team?')\">";
                echo '<input type = "hidden" name = "from" value = "'.$from.'">';
                echo '<input type = "hidden" name = "to" value = "'.$to.'">';
                echo '<input type = "hidden" name = "team" value = "'.$team.'">';
                echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
                echo '<button type = "submit" class="btn-danger">Delete</button>';
                echo '</form>';

                echo '</td>';
            echo '</tr>';
            $i++;

            }
            echo '<tr>';
                echo '<td><p align="center"><button type="submit" class="btn-danger btn-sm" name="save">DELETE</button></p></td>';
            echo '</tr>';
            echo '</form>';

        }
        else
        {
            echo '
            <table class = "table-bordered" width = "100%">
            <thead>
            <tr>
            <th width = "5%">id</th>
            <th width = "12%">Date</th>
            <th width = "23%">Task Name</th>
            <th width = "10%">Status</th>
            <th width = "7%">Action</th>
            </tr>
            <tr>
            <td colspan="5">No report found</td>
            </tr>';
        }
        echo '</body></table></div></div>';

        }

?>
</code>```

Body:
I have a problem with my delete function. Before that, I will brief to you about the flow of the system

1) At dashboard_engineer.php, there's 3 select options which is team, time from and time to.

2) user need to select 3 select option and press button "Search" to display the result.

3) The result will display at dashboard_engineer2.php.

4) The result will display all data rows and each row contains one delete button.

My problem is, after I click button delete, it was successful delete but the dashboard_engineer2.php page doesn't display the result that same as point 3 above. The result empty.

What I want is that, after delete, the dashboard_engineer2.php will display the remaining data rows that already filtered before. Below is my code.

dashboard_engineer.php

<?php

    $smt = $conn->prepare("SELECT * FROM ot_team INNER JOIN ot_users ON ot_team.team_id = ot_users.team_id WHERE ot_users.roles_id = 7 AND ot_users.team_id <> 1 ORDER BY ot_users.fullname ASC");
    $smt->execute();
    $data = $smt->fetchAll();

?>

<form method = 'post' action = 'dashboard_engineer2.php' >

    <select class="form-control"  name="team" id="team" required>
      <option value="">Please select...</option>
      <?php foreach ($data as $row2): ?>
      <option value= <?php echo $row2["team_id"]; ?> ><?php echo $row2["fullname"]; ?></option>
      <?php endforeach ?>
    </select>

  <input type="text" name="from" id="from" class="form-control" placeholder="From" required>

  <input type="text" name="to" id="to" class="form-control" placeholder="To" required>

  <button type="submit" value="Search" class="btn btn-primary" >Send</button>
</form>

dashboard_engineer2.php

<?php

    if(isset($_POST["from"], $_POST["to"], $_POST["team"])){

        $result = '';
        $query = "SELECT * FROM ot_report LEFT JOIN ot_users ON ot_report.badgeid = ot_users.badgeid WHERE ot_users.team_id = '".$_POST["team"]."' AND report_date BETWEEN '".$_POST["from"]."' AND '".$_POST["to"]."' ORDER BY ot_report.report_date DESC";
        $sql = $conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
        $sql -> execute();

        if($sql->rowCount() > 0){

        echo'

        <input type="checkbox" id="checkAl"> All
        id
        Date
        Task Name
        Status
        Action

';

            $i=0;

            while($row = $sql->fetch(PDO::FETCH_ASSOC)){

            $datereport = $row['report_date'];
            $datereport2 = strtotime($datereport);
            $report_date = date('d M Y', $datereport2);

            $report_id = $row["report_id"];

            echo'
';
                echo '<input type="checkbox" id="checkItem" name="check[]" value='.$row['report_id'].'>	';
                echo ''.$report_id.'	';
                echo ''.$report_date.'	';
                echo ''.$row["task_name"].'	';
                echo ''.$row["report_status"].'	';
                echo '';
                echo '<form action = "view_task/view_task.php" method = "post">';
                echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
                echo '<button type = "submit" class="btn-primary">View</button>';
                echo '</form>';

                echo "<form action = 'delete.php' method = 'post' onClick=\"return confirm('Do you want to remove team?')\">";
                echo '<input type = "hidden" name = "from" value = "'.$_POST["from"].'">';
                echo '<input type = "hidden" name = "to" value = "'.$_POST["to"].'">';
                echo '<input type = "hidden" name = "team" value = "'.$_POST["team"].'">';
                echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
                echo '<button type = "submit" class="btn-danger">Delete</button>';
                echo '</form>';

                echo '	';
            echo '
';
            $i++;

            }
            echo '
';
                echo '
<button type="submit" class="btn-danger btn-sm" name="save">DELETE</button>
	';
            echo '
';
            echo '</form>';

        }
        else
        {
            echo '

            id
            Date
            Task Name
            Status
            Action

            No report found

';
        }
        echo '

';

        }

?>

delete.php

  <?php

        $report_id = $_POST['report_id'];

        $sql = "DELETE FROM ot_report WHERE report_id=:report_id";
        $query = $conn->prepare($sql);
        $query->execute(array(':report_id' => $report_id));

        header("Location: dashboard_engineer2.php");

  ?>

Can anyone help me on how to fix this?

Body:
this case is the same as the question
PHP / MySQL: Display some error after successfully updated the data

that's because in dashboard_engineer2.php your code will display data from the database if the from, to, team variable is posted.

from delete.php redirect to dashboard_engineer2.php being the get method and the data that was previously posted is missing

change the delete.php code to be like this

<?php
        $report_id = $_POST['report_id'];
        $from = $_POST['from'];
        $to = $_POST['to'];
        $team = $_POST['team'];

        $sql = "DELETE FROM ot_report WHERE report_id=:report_id";
        $query = $conn->prepare($sql);
        $query->execute(array(':report_id' => $report_id));

        // so that the data previously posted is taken
        // when redirecting to the dashboard_engineer2.php page
        // even though it is a GET method

        header("Location: dashboard_engineer2.php?from={$from}&to={$to}&team={$team}");
?>

and there was a slight change in dashboard_engineer2.php to be like this

<?php

    // change the initial conditions to be like this
    // $_REQUEST will get data if there is data in POST or GET

    if(isset($_REQUEST["from"], $_REQUEST["to"], $_REQUEST["team"])){

        $from = $_REQUEST['from'];
        $to   = $_REQUEST['to'];
        $team = $_REQUEST['team'];

        $result = '';
        $query = "SELECT * FROM ot_report LEFT JOIN ot_users ON ot_report.badgeid = ot_users.badgeid WHERE ot_users.team_id = '".$team."' AND report_date BETWEEN '".$from."' AND '".$to."' ORDER BY ot_report.report_date DESC";

        $sql = $conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
        $sql -> execute();

        if($sql->rowCount() > 0){

        echo'

        <table class = "table-bordered" width = "100%">
        <thead>
        <tr>
        <th width = "10%"><input type="checkbox" id="checkAl"> All</th>
        <th width = "3%">id</th>
        <th width = "15%">Date</th>
        <th width = "30%">Task Name</th>
        <th width = "10%">Status</th>
        <th colspan = "2" width = "7%">Action</th>
        </tr>
        </thead>
        <tbody>';

            $i=0;

            while($row = $sql->fetch(PDO::FETCH_ASSOC)){

            $datereport = $row['report_date'];
            $datereport2 = strtotime($datereport);
            $report_date = date('d M Y', $datereport2);

            $report_id = $row["report_id"];

            echo'<tr>';
                echo '<td><input type="checkbox" id="checkItem" name="check[]" value='.$row['report_id'].'></td>';
                echo '<td>'.$report_id.'</td>';
                echo '<td>'.$report_date.'</td>';
                echo '<td>'.$row["task_name"].'</td>';
                echo '<td align="center"><strong>'.$row["report_status"].'</strong></td>';
                echo '<td align="center">';
                echo '<form action = "view_task/view_task.php" method = "post">';
                echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
                echo '<button type = "submit" class="btn-primary">View</button>';
                echo '</form>';

                echo "<form action = 'delete.php' method = 'post' onClick=\"return confirm('Do you want to remove team?')\">";
                echo '<input type = "hidden" name = "from" value = "'.$from.'">';
                echo '<input type = "hidden" name = "to" value = "'.$to.'">';
                echo '<input type = "hidden" name = "team" value = "'.$team.'">';
                echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
                echo '<button type = "submit" class="btn-danger">Delete</button>';
                echo '</form>';

                echo '</td>';
            echo '</tr>';
            $i++;

            }
            echo '<tr>';
                echo '<td><p align="center"><button type="submit" class="btn-danger btn-sm" name="save">DELETE</button></p></td>';
            echo '</tr>';
            echo '</form>';

        }
        else
        {
            echo '
            <table class = "table-bordered" width = "100%">
            <thead>
            <tr>
            <th width = "5%">id</th>
            <th width = "12%">Date</th>
            <th width = "23%">Task Name</th>
            <th width = "10%">Status</th>
            <th width = "7%">Action</th>
            </tr>
            <tr>
            <td colspan="5">No report found</td>
            </tr>';
        }
        echo '</body></table></div></div>';

        }

?>


问:
does vb.net array contains only references to the value types variables allocated on the stack?

This image is from visual basic.net by Jesse Liberty. I just wanted to know that what the author is trying to say here. Does vb.net array only contains references to the value type variables allocated on the stack or the array contains actual values on the heap.

答:
There are no pointers in VB.NET so it's not possible for an array to contain pointers. You can basically think of an array as a group of variables. Each element of an array behaves pretty much exactly like a variable of the same type behaves.

All variables are Nothing by default, so all array elements are Nothing by default. Value type variables contain a value, so getting that variable gives you a copy of the value. The same is true of elements in an array of a value type. Reference type variables contain a reference to an object, so getting that variable gives you a copy of that reference to the same object. The same is true of elements in an array of a reference type. In simple terms, structures are value types and classes are reference types so an array of structures contains those objects in the elements while an array of classes contains references to those objects in the elements.


问:
SQL: How to display records for only 30 days
I tried to use

```<code>SELECT * from Results
WHERE DATEDIFF(d,Date,getdate())<30
</code>```

But it seem having error with this.

For each record submitted will only display 30 days. May I know if my syntax is correct?

Greatly Appreciated,
Stan

答:
Try this:

```<code>SELECT *
FROM results
WHERE ([Date] between DateAdd("d", -30, Date()) and Date())
</code>```

One other heads-up. Naming a field "Date" in Access is generally a bad idea. It is a reserved word and you will have to use brackets [] around it in all of your queries.

OwnerDisplayName: Stanley

LastEditorDisplayName: JohnFx

ContentLicense: CC BY-SA 2.5

Body:
I tried to use

SELECT * from Results
WHERE DATEDIFF(d,Date,getdate())<30

But it seem having error with this.

For each record submitted will only display 30 days. May I know if my syntax is correct?

Greatly Appreciated,
Stan

Body:
Try this:

SELECT *
FROM results
WHERE ([Date] between DateAdd("d", -30, Date()) and Date())

One other heads-up. Naming a field "Date" in Access is generally a bad idea. It is a reserved word and you will have to use brackets [] around it in all of your queries.

OwnerDisplayName: JohnFx


问:
Implementing Actor Model in C# 5 / Async CTP
In an Actor Model, the actors have some sort of message loop where messages are matched using e.g. pattern matching (depending on language ofc)

e.g. pseudo F#

```<code> let message_loop() =
     let! message = receive_message() //sync receive message
     match message with
     | Foo(a,b) -> DoStuff(a,b)
     | Bar(c) -> DoOtherStuff(c)
     | _ -> error ("unknown message")
     message_loop()
</code>```

So pretty much, a message signature is matched and associated with some action to perform on the message content.

Is there any conceptual difference between this and calling actual methods?
e.g. if I would do the following in C# 5:

```<code>class MyActor
{
   //message signature Foo(a,b)
   public void Foo(int a,string b)
   {
      Act( () => DoStuff(a,b) );
   }

   //message signature Bar(c)
   public void Bar(int c)
   {
      Act( () => DoOtherStuff(c));
   }

   // the rest is infrasturcture code, can be refactored into an Actor Base class

   //this emulates the sync behavior of the above actor
   //each action is pushed onto a queue
   //and then processed synchronously by the message handler
   private void Act(Action action)
   {
       actions.Post(action);
   }

   private BufferBlock<Action> actions = new BufferBlock<Action>();

   //this needs max degreee of parallellism = 1
   private ActionBlock<Action> messageHandler = new ....
}
</code>```

This way, invoking a method on MyActor will result in an async message posted onto a message queue which only handles a single kind of message; an Action.
However, the behavor associated with the message is contained in the message itself (posted from the public method)

So would this be a considered a clean way to do actors in C# 5 / Async CTP?

The benefits would be that messages are simply defined as normal messages instead of creating awkward message DTO like classes.

So would this be enough to make it work?

答:
There is a slight difference between Task-based asynchrony and MailboxProcessor.  Mailbox processor will always end up in the same thread, similar to Winforms message loop.  Task keeps a SynchronizationContext.  This means the same behavior for Winforms and WPF, but you could end up on a different thread when working with a thread-pool.

Otherwise, and conceptually, looks right to me.

Body:
In an Actor Model, the actors have some sort of message loop where messages are matched using e.g. pattern matching (depending on language ofc)

e.g. pseudo F#

 let message_loop() =
     let! message = receive_message() //sync receive message
     match message with
     | Foo(a,b) -> DoStuff(a,b)
     | Bar(c) -> DoOtherStuff(c)
     | _ -> error ("unknown message")
     message_loop()

So pretty much, a message signature is matched and associated with some action to perform on the message content.

Is there any conceptual difference between this and calling actual methods?
e.g. if I would do the following in C# 5:

class MyActor
{
   //message signature Foo(a,b)
   public void Foo(int a,string b)
   {
      Act( () => DoStuff(a,b) );
   }

   //message signature Bar(c)
   public void Bar(int c)
   {
      Act( () => DoOtherStuff(c));
   }

   // the rest is infrasturcture code, can be refactored into an Actor Base class

   //this emulates the sync behavior of the above actor
   //each action is pushed onto a queue
   //and then processed synchronously by the message handler
   private void Act(Action action)
   {
       actions.Post(action);
   }

   private BufferBlock<Action> actions = new BufferBlock<Action>();

   //this needs max degreee of parallellism = 1
   private ActionBlock<Action> messageHandler = new ....
}

This way, invoking a method on MyActor will result in an async message posted onto a message queue which only handles a single kind of message; an Action.
However, the behavor associated with the message is contained in the message itself (posted from the public method)

So would this be a considered a clean way to do actors in C# 5 / Async CTP?

The benefits would be that messages are simply defined as normal messages instead of creating awkward message DTO like classes.

So would this be enough to make it work?


问:
Why can't I run python code from my command prompt?

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

答:
You have to run the Python interpreter first.

Type "python" and hit Enter.


问:
How to reveal progressing border on window scroll
In this code title border is "spreading" on hover and I want to create the same effect on a scroll. How can I do this?

.title {
  position: relative;
  font-size: 40px;
  font-weight: bolder;
  font-family: 'Poppins', sans-serif;
  text-transform: uppercase;
  color: #262626;
}

.title::before {
  content: "";
  position: absolute;
  left: 50%;
  right: 50%;
  bottom: 0;
  height: 5px;
  background: linear-gradient(90deg, #ED1C24, rgb(230, 7, 74));
}

.section-box:hover .title::before {
  left: 0;
  right: 0;
  height: 2px;
  transition: 1s;
  background: #ED1C24;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="section-box" id="about">
  <div class="container">
    <div class="section-head">
      <h1 class="title">about us</h1>
    </div>
  </div>
</section></code>```

答:
I don't know what you mean by "on scroll," but the animation you want is applied by the CSS psuedo-class :hover. There is no psuedo-class for scroll, so you'll need to probably involve Javascript.

The list of available CSS psuedo-classes can be found here. Try experimenting with them to see if they'll do what you want.

The Javascript onscroll event can be found here.

Body:
In this code title border is "spreading" on hover and I want to create the same effect on a scroll. How can I do this?

.title {
  position: relative;
  font-size: 40px;
  font-weight: bolder;
  font-family: 'Poppins', sans-serif;
  text-transform: uppercase;
  color: #262626;
}

.title::before {
  content: "";
  position: absolute;
  left: 50%;
  right: 50%;
  bottom: 0;
  height: 5px;
  background: linear-gradient(90deg, #ED1C24, rgb(230, 7, 74));
}

.section-box:hover .title::before {
  left: 0;
  right: 0;
  height: 2px;
  transition: 1s;
  background: #ED1C24;
}

about us


问:
Need to implement onPress logic on react native app to perfume two tasks
Hey stackoverflow I am new in react native world learning it through documentation and tutorials. My problem is I want to perform two tasks on single button-through onPress. Here is what I want I have two pages. On first page user enter his phone number and I save it in DB. When user press verify button it inserts the value in DB now I want the behaviour when user press button the data is inserted and my user move to second screen basically two onPress on one single button how I achieve this kind of functionality my code :

//mobilecheck.js
import React, { Component } from 'react';
import { View, Text, StyleSheet, TextInput, TouchableOpacity, ActivityIndicator, Platform,Button} from 'react-native';

export default class MobileCheck extends React.Component
{

    constructor(){
         super()
         this.state = {
            TextInput_mobile_number: '',
            mobile_number: '', loading: false, disabled: false

         }

    }

    sendDatafun=()=>{
        this.props.navigation.navigate('VerifyCode',{
            mobile_number:this.state.mobile_number
        });

    }

    saveData = () =>
    {
        this.setState({ loading: true, disabled: true }, () =>
        {
            fetch('http://192.168.2.186/otplogin/mobile_checkapi.php',
            {
                method: 'POST',
                headers:
                {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(
                {
                    mobile_number: this.state.mobile_number,

                })

            }).then((response) => response.json()).then((responseJson) =>
            {
                alert(responseJson);
                this.setState({ loading: false, disabled: false });
            }).catch((error) =>
            {
                console.error(error);
                this.setState({ loading: false, disabled: false });
            });
        });

    }

    render()
    {
        const { navigate } = this.props.navigation;
        return(
            <View style = { styles.container }>
                <TextInput underlineColorAndroid = "transparent" placeholder = "Please Enter Your Mobile Number" style = { styles.textInput } onChangeText = {(text) => this.setState({ mobile_number: text })}
               // onChangeText={data => this.setState({ TextInput_mobile_number: data })}
                keyboardType={'numeric'}

                />

                <TouchableOpacity disabled = { this.state.disabled } activeOpacity = { 0.8 } style = { styles.Btn } onPress = { this.saveData } onPress={this.sendDatafun}  >
                    <Text style = { styles.btnText }>Get Code</Text>

                </TouchableOpacity>
                <Button title = 'Next'
                    onPress={this.sendDatafun}
                />

                {
                    (this.state.loading)
                    ?
                        (<ActivityIndicator size = "large" />)
                    :
                        null
                }

            </View>
        );
    }
}
//verifycode.js
import React, { Component } from 'react';
import { View, Text, StyleSheet, TextInput, TouchableOpacity, ActivityIndicator, Platform,Button } from 'react-native';

export default class VerifyCode extends React.Component
{
    constructor(props)
    {
        super(props);

        this.state = {
            code: '',
            TextInput_mobile_number: '',
            mobile_number: '',

            // new code
            UserName: '',
            UserEmail: '',
            UserPassword: '',
            UserCity: '',

            loading: false,
            disabled: false,

        }
    }
//     nextbutton = () =>
//   {
//      this.props.navigation.navigate('SignUp');

//   }

    saveData = () =>
    {

        // new code
        const { UserName }  = this.state ;
        const { UserEmail }  = this.state ;
        const { UserPassword }  = this.state ;
        const { UserCity }  = this.state ;
        this.setState({ loading: true, disabled: true }, () =>
        {
            fetch('http://192.168.2.186/otplogin/verify_codeapi.php',
            {
                method: 'POST',
                headers:
                {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(
                {
                    code: this.state.code,
                    mobile_number: this.props.navigation.state.params.mobile_number,

                    //new code
                    user_name: UserName,

                    user_email: UserEmail,

                    user_password: UserPassword,

                    user_city: UserCity,

                })

            }).then((response) => response.json()).then((responseJson) =>
            {
                alert(responseJson);
                this.setState({ loading: false, disabled: false });
            }).catch((error) =>
            {
                console.error(error);
                this.setState({ loading: false, disabled: false });
            });
        });
    }

    render()
    {
        return(
            <View style = { styles.container }>

                <Text style={styles.textStyle}>
                We send verification code to : {this.props.navigation.state.params.mobile_number}
                </Text>
                <TextInput underlineColorAndroid = "transparent" placeholder = "Please Enter Your Verification Code" style = { styles.textInput } onChangeText = {(text) => this.setState({code: text })}
                    keyboardType={'numeric'}
                />
                <TextInput
                placeholder="Enter Your Full Name"
                onChangeText={UserName => this.setState({ UserName })}
                underlineColorAndroid="transparent"
                style={styles.TextInput}
                />
                <TextInput
                placeholder="Enter Your Email"
                onChangeText={UserEmail => this.setState({ UserEmail })}
                underlineColorAndroid="transparent"
                style={styles.TextInput}
                />
                <TextInput
                placeholder="Enter Your Password"
                onChangeText={UserPassword => this.setState({ UserPassword })}
                underlineColorAndroid="transparent"
                style={styles.TextInput}
                />
                <TextInput
                placeholder="Enter Your City name"
                onChangeText={UserCity => this.setState({ UserCity })}
                underlineColorAndroid="transparent"
                style={styles.TextInput}
                />
                <TouchableOpacity disabled = { this.state.disabled } activeOpacity = { 0.8 } style = { styles.Btn } onPress = { this.saveData }>
                   <Text style = { styles.btnText }>Verify</Text>
                </TouchableOpacity>
                <Button title = 'Next'
                    onPress={this.nextbutton}
                />

                {
                    (this.state.loading)
                    ?
                        (<ActivityIndicator size = "large" />)
                    :
                        null
                }

            </View>
        );
    }
}```

答:
You can achieve this with single onPress itself. if the database response is success you can go to next page in two ways,

if you wanna render multiple screens based on the state update, You can set the login screen state as false and then desired screensstateastrue` like below. Let's say your desired screen is Home screen,

```<code>this.setState({
   loading: false,
   disabled: false,
   loginScreen: false,
   homeScreen: true    //This `state` update will render the home screen
});
</code>```

Then your render() must be like this,

```<code>  render() {
      if(this.state.loginScreen) {
         //login screen content
      } else if(this.state.homeScreen) {
         //home screen content
      }
  }
</code>```

2.If you are using any routing package then you can go to next screen as follows,

```<code>  this.props.history.push('/homeScreen');
</code>```

this is just an example if you use react-router-native . There are other packages which does same.

remember that, Either of above ways must be implemented inside the response of your database request.

Feel free to ask you have any doubt.

Body:
You can achieve this with single onPress itself. if the database response is success you can go to next page in two ways,

if you wanna render multiple screens based on the state update, You can set the login screen state as false and then desired screensstateastrue` like below. Let's say your desired screen is Home screen,

this.setState({
   loading: false,
   disabled: false,
   loginScreen: false,
   homeScreen: true    //This `state` update will render the home screen
});

Then your render() must be like this,

  render() {
      if(this.state.loginScreen) {
         //login screen content
      } else if(this.state.homeScreen) {
         //home screen content
      }
  }

2.If you are using any routing package then you can go to next screen as follows,

  this.props.history.push('/homeScreen');

this is just an example if you use react-router-native . There are other packages which does same.

remember that, Either of above ways must be implemented inside the response of your database request.

Feel free to ask you have any doubt.


问:
What are all possible POS tags of NLTK?
How do I find a list with all possible POS tags used by the Natural Language Toolkit (NLTK)?</p>

Title: What are all possible POS tags of NLTK?

Body:
['LS', 'TO', 'VBN', "''", 'WP', 'UH', 'VBG', 'JJ', 'VBZ', '--', 'VBP', 'NN', 'DT', 'PRP', ':', 'WP$', 'NNPS', 'PRP$', 'WDT', '(', ')', '.', ',', '``', '$', 'RB', 'RBR', 'RBS', 'VBD', 'IN', 'FW', 'RP', 'JJR', 'JJS', 'PDT', 'MD', 'VB', 'WRB', 'NNP', 'EX', 'NNS', 'SYM', 'CC', 'CD', 'POS']

Based on Doug Shore's method but make it more copy-paste friendly


问:
How can I find & delete duplicate strings from ~800gb worth of text files?
I have a dataset of ~800gb worth of text files, with about 50k .txt files in total.

I'd like to go through and make a master .txt file from these, with all duplicate lines removed from all txt files.

I can't find a way to do this that isn't going to take months for my computer to process, idealy i'd like to keep it less than a week.

答:
```<code>sort -u <data.txt >clean.txt
</code>```

All you need is a large disk.

sort is quite efficient: it will automatically split the file into manageable bites, sort each one separately, then merge them (which can be done in O(N) time); and while merging, it will discard the dupes (due to -u option). But you will need at least the space for the output file, plus the space for all the intermediate files.

Body:
sort -u <data.txt >clean.txt

All you need is a large disk.

sort is quite efficient: it will automatically split the file into manageable bites, sort each one separately, then merge them (which can be done in O(N) time); and while merging, it will discard the dupes (due to -u option). But you will need at least the space for the output file, plus the space for all the intermediate files.


问:
Can't push merge to server after merging branch with master branch on git
Working on a git repository and I merged my new branch with the master branch locally. Now I want to push this merge to the git server but I am getting an error:
Update was rejected because the update contains work that you do not have locally. This is usually caused by another reppository pushing to the same ref.</p>

答:
This is a really common error faced by many people out here so it is not a big issue. You just need to do a git pull, which will merge changes made on the remote(i.e the GitHub/BitBucket/GitLab repository) while you were working on your code.

After that you can git push to push your changes upstream :)

Best.


问:
fetch all rows from mysql db with php using aFetch($sql) problem
i inherited this code from some-one and this only returns the first row it finds:

```<code>function getMessages($userID, $from, $limit)
{
  $id = $_SESSION['user_id'];
  $sql = "SELECT * FROM rc_message_box_table WHERE profile_id_to = {$userID} AND rc_message_box_table.profile_id_from NOT IN (SELECT profile_id_block FROM rc_blocklist_table WHERE profile_id = {$id}) LIMIT {$from}, {$limit}";
  $row = $this->aFetch($sql);
  return $row;
}

function aFetch($sSql)
{
//print_r($sSql);
$aResults = array();
if(is_string($sSql))
{
      $fnSql = $this->query($sSql);
    }

   while($row = mysql_fetch_assoc($fnSql))
   {
  $aResults[] = $row;
   }
   return  $aResults;
}
</code>```

how can i with this code return all rows where profile_id_to = {$userID} ??
thanks

答:
Your result may be limited by $from, $limit parameters.

Look at the code where getMessages is being invoked, and analyse what values it is passing.

Body:
i inherited this code from some-one and this only returns the first row it finds:

function getMessages($userID, $from, $limit)
{
  $id = $_SESSION['user_id'];
  $sql = "SELECT * FROM rc_message_box_table WHERE profile_id_to = {$userID} AND rc_message_box_table.profile_id_from NOT IN (SELECT profile_id_block FROM rc_blocklist_table WHERE profile_id = {$id}) LIMIT {$from}, {$limit}";
  $row = $this->aFetch($sql);
  return $row;
}

function aFetch($sSql)
{
//print_r($sSql);
$aResults = array();
if(is_string($sSql))
{
      $fnSql = $this->query($sSql);
    }

   while($row = mysql_fetch_assoc($fnSql))
   {
  $aResults[] = $row;
   }
   return  $aResults;
}

how can i with this code return all rows where profile_id_to = {$userID} ??
thanks


问:
Android Docx4J Error when reading in MS Word file: Didn't find class org.eclipse.persistence.oxm.NamespacePrefixMapper on path
I am trying to use the Docx4j library in order to read in the contents of Word files selected by the user (tried to follow the code in https://github.com/plutext/Docx4j4Android4) However, I receive the following error when I read in a MS Word file:

```<code>W/System.err: log4j:ERROR Could not parse url [jar:file:/data/app/com.example.diffcheckertest-8hLouozp5QPE6U8NaxyKYA==/base.apk!/log4j.xml].
    javax.xml.parsers.ParserConfigurationException: No validating DocumentBuilder implementation available
        at org.apache.harmony.xml.parsers.DocumentBuilderFactoryImpl.newDocumentBuilder(DocumentBuilderFactoryImpl.java:61)
...
Process 20716 terminated.
    Caused by: java.lang.ClassNotFoundException: Didn't find class "org.eclipse.persistence.oxm.NamespacePrefixMapper" on path: DexPathList[[zip file "/data/app/com.example.diffcheckertest-8hLouozp5QPE6U8NaxyKYA==/base.apk"]
</code>```

Below is the line of code in MainActivity.kt where I open the MS Word document and where the error occurs (I have imported the necessary utilities):

```<code>import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

import org.apache.commons.lang3.StringUtils;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import java.io.BufferedReader
import java.io.InputStreamReader

class MainActivity : AppCompatActivity() {
    private var READ_IN_FILE:Int = 2; // Request code used when reading in a file

    // Asks a user to read in a file
    private fun chooseFile(view: View) {
        // Only the below specified mime types are allowed in the picker
        var selectFile = Intent(Intent.ACTION_GET_CONTENT)
        selectFile.type = "*/*"
        selectFile = Intent.createChooser(selectFile, "Choose a file")
        startActivityForResult(selectFile, READ_IN_FILE)
    }

    // After receiving a result for a launched activity...
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == READ_IN_FILE) { // When a result has been received, check if it is the result for READ_IN_FILE
            if (resultCode == Activity.RESULT_OK) { // heck if the operation to retrieve the Activity's result is successful
                // Attempt to retrieve the file
                try {
                    var uri = data?.data // Retrieve the file's resource locator
                    var document = WordprocessingMLPackage.load(uri?.let { contentResolver.openInputStream(it) });
                    //var documentPart: MainDocumentPart = document.getMainDocumentPart();
                    Toast.makeText(this, "DiffChecker successfully read in the file :D", Toast.LENGTH_SHORT).show()
                } catch (e: Exception) { // If the app failed to attempt to retrieve the error file, throw an error alert
                    println("Exception: " + e.toString());
                    Toast.makeText(this, "Sorry, but there was an error reading in the file", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        findViewById<Button>(R.id.file1).setOnClickListener(::chooseFile);
    }
}
</code>```

Below is my build.gradle code (app-level):

```<code>apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.example.diffcheckertest"
        minSdkVersion 22
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/ASL2.0'
        exclude("META-INF/*.kotlin_module")
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation files('libs/activation.jar')
    implementation files('libs/additionnal.jar')
    implementation files('libs/awt-bastardised-17v8.jar')
    implementation files('libs/istack-commons-runtime-3.0.4-SNAPSHOT.jar')
    implementation files('libs/jaxb-core-2.3.0-SNAPSHOT-ANDROID.jar')
    implementation files('libs/jaxb-runtime-2.3.0-SNAPSHOT-ANDROID.jar')

    //implementation files('libs/commons-lang3-3.7.jar')
    //implementation files('libs/commons-text-1.2.jar')
    implementation 'javax.xml.stream:stax-api:1.0-2'
    implementation 'com.fasterxml:aalto-xml:1.0.0'

    implementation files('libs/docx4j-6.1.1-SNAPSHOT-shaded.jar')

}
</code>```

Build is my build.gradle code (project-level):

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.3.61'
    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

答:
How did your project work without the javax.xml.bind:jaxb-api:2.2.12 dependency? It should throw  java.lang.NoClassDefFoundError: Failed resolution of: Ljavax/xml/bind/JAXBContext; at the first place.

Android does not support JAXB out of the box, and you must add the dependency explicitly.

```<code>implementation 'javax.xml.bind:jaxb-api:2.2.12'
</code>```

Instead of trying your gradle settings I decided to create a new project and start everything from scratch. Fortunately, I could run and load any docx files without issues.

Please download my sample repository and try in your system.

Body:
I am trying to use the Docx4j library in order to read in the contents of Word files selected by the user (tried to follow the code in https://github.com/plutext/Docx4j4Android4) However, I receive the following error when I read in a MS Word file:

W/System.err: log4j:ERROR Could not parse url [jar:file:/data/app/com.example.diffcheckertest-8hLouozp5QPE6U8NaxyKYA==/base.apk!/log4j.xml].
    javax.xml.parsers.ParserConfigurationException: No validating DocumentBuilder implementation available
        at org.apache.harmony.xml.parsers.DocumentBuilderFactoryImpl.newDocumentBuilder(DocumentBuilderFactoryImpl.java:61)
...
Process 20716 terminated.
    Caused by: java.lang.ClassNotFoundException: Didn't find class "org.eclipse.persistence.oxm.NamespacePrefixMapper" on path: DexPathList[[zip file "/data/app/com.example.diffcheckertest-8hLouozp5QPE6U8NaxyKYA==/base.apk"]

Below is the line of code in MainActivity.kt where I open the MS Word document and where the error occurs (I have imported the necessary utilities):

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

import org.apache.commons.lang3.StringUtils;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import java.io.BufferedReader
import java.io.InputStreamReader

class MainActivity : AppCompatActivity() {
    private var READ_IN_FILE:Int = 2; // Request code used when reading in a file

    // Asks a user to read in a file
    private fun chooseFile(view: View) {
        // Only the below specified mime types are allowed in the picker
        var selectFile = Intent(Intent.ACTION_GET_CONTENT)
        selectFile.type = "*/*"
        selectFile = Intent.createChooser(selectFile, "Choose a file")
        startActivityForResult(selectFile, READ_IN_FILE)
    }

    // After receiving a result for a launched activity...
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == READ_IN_FILE) { // When a result has been received, check if it is the result for READ_IN_FILE
            if (resultCode == Activity.RESULT_OK) { // heck if the operation to retrieve the Activity's result is successful
                // Attempt to retrieve the file
                try {
                    var uri = data?.data // Retrieve the file's resource locator
                    var document = WordprocessingMLPackage.load(uri?.let { contentResolver.openInputStream(it) });
                    //var documentPart: MainDocumentPart = document.getMainDocumentPart();
                    Toast.makeText(this, "DiffChecker successfully read in the file :D", Toast.LENGTH_SHORT).show()
                } catch (e: Exception) { // If the app failed to attempt to retrieve the error file, throw an error alert
                    println("Exception: " + e.toString());
                    Toast.makeText(this, "Sorry, but there was an error reading in the file", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        findViewById<Button>(R.id.file1).setOnClickListener(::chooseFile);
    }
}

Below is my build.gradle code (app-level):

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.example.diffcheckertest"
        minSdkVersion 22
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/ASL2.0'
        exclude("META-INF/*.kotlin_module")
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation files('libs/activation.jar')
    implementation files('libs/additionnal.jar')
    implementation files('libs/awt-bastardised-17v8.jar')
    implementation files('libs/istack-commons-runtime-3.0.4-SNAPSHOT.jar')
    implementation files('libs/jaxb-core-2.3.0-SNAPSHOT-ANDROID.jar')
    implementation files('libs/jaxb-runtime-2.3.0-SNAPSHOT-ANDROID.jar')

    //implementation files('libs/commons-lang3-3.7.jar')
    //implementation files('libs/commons-text-1.2.jar')
    implementation 'javax.xml.stream:stax-api:1.0-2'
    implementation 'com.fasterxml:aalto-xml:1.0.0'

    implementation files('libs/docx4j-6.1.1-SNAPSHOT-shaded.jar')

}

Build is my build.gradle code (project-level):

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.3.61'
    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Body:
How did your project work without the javax.xml.bind:jaxb-api:2.2.12 dependency? It should throw  java.lang.NoClassDefFoundError: Failed resolution of: Ljavax/xml/bind/JAXBContext; at the first place.

Android does not support JAXB out of the box, and you must add the dependency explicitly.

implementation 'javax.xml.bind:jaxb-api:2.2.12'

Instead of trying your gradle settings I decided to create a new project and start everything from scratch. Fortunately, I could run and load any docx files without issues.

Please download my sample repository and try in your system.


问:
GCP network usage monitoring
is there any network monitor for GCP VMs?
I think that my apps is experiencing some network problem, keep on facing JSONP failed request

Thanks in advance

答:
Stackdriver is best for GCP as that has better visibility. There is logging, monitoring, trace, debugger, profile.
links:
https://cloud.google.com/logging | https://cloud.google.com/monitoring | https://cloud.google.com/trace | https://cloud.google.com/debugger https://cloud.google.com/profiler

Title: GCP network usage monitoring