问:
Unable to get existing Hive tables from HiveContext using Spark
I am trying to get databases or table details of Hive from spark using HiveContext. But I am unable to point to existing Hive Database as shown below:
Spark Version: 2.2.0
Hive Version : 2.3.0

Using below script in Spark Shell to connect to existing Hive Server(127.0.0.1 used below is my machine ip address):

```<code>scala> val hc = new org.apache.spark.sql.hive.HiveContext(sc)
warning: there was one deprecation warning; re-run with -deprecation for details
hc: org.apache.spark.sql.hive.HiveContext = org.apache.spark.sql.hive.HiveContext@6dde913e

scala> hc.setConf("hive.metastore.uris","thrift://127.0.0.1:9083")

scala> val df = hc.sql("show databases")
df: org.apache.spark.sql.DataFrame = [databaseName: string]

scala> df.show
+------------+
|databaseName|
+------------+
|     default|
+------------+

scala> val dfTables = hc.sql("show tables");
dfTables: org.apache.spark.sql.DataFrame = [database: string, tableName: string ... 1 more field]

scala> dfTables.show
+--------+---------+-----------+
|database|tableName|isTemporary|
+--------+---------+-----------+
+--------+---------+-----------+
</code>```

As shown above I am unable to get the existing Hive databases and tables available. HiveContext is pointing to new database(default) and no tables available.
Below are my hive db listed:

```<code>hive> show databases;
OK
default
mydbbackup
Time taken: 7.593 seconds, Fetched: 2 row(s)
hive> use mydbbackup;
OK
Time taken: 0.021 seconds
hive> show tables;
OK
customers
customerspart
customerspart1
Time taken: 0.194 seconds, Fetched: 3 row(s)
hive>
</code>```

Below is my hive-site.xml:

<configuration>
<property>
<name>javax.jdo.option.ConnectionURL</name>
<value>jdbc:derby:;databaseName=/home/hduser/apache-hive-2.3.0-bin/metastore_db;create=true</value>
<description>
JDBC connect string for a JDBC metastore.
To use SSL to encrypt/authenticate the connection, provide database-specific SSL flag in the connection URL.
For example, jdbc:postgresql://myhost/db?ssl=true for postgres database.
</description>
</property>
<property>
<name>hive.metastore.warehouse.dir</name>
<value>/user/hive/warehouse</value>
<description>location of default database for the warehouse</description>
</property>
<property>
<name>hive.metastore.uris</name>
<value/>
<description>Thrift URI for the remote metastore. Used by metastore client to connect to remote metastore.</description>
</property>
<property>
<name>javax.jdo.option.ConnectionDriverName</name>
<value>org.apache.derby.jdbc.EmbeddedDriver</value>
<description>Driver class name for a JDBC metastore</description>
</property>
<property>
<name>javax.jdo.PersistenceManagerFactoryClass</name>
<value>org.datanucleus.api.jdo.JDOPersistenceManagerFactory</value>
<description>class implementing the jdo persistence</description>
</property>
</configuration>
```

<p>Below is my spark conf Directory:</p>

```total 40
drwxr-xr-x  2 root root 4096 Nov 12 20:22 ./
drwxr-xr-x 12 root root 4096 Nov  9 22:57 ../
-rw-r--r--  1 root root  996 Nov  9 22:57 docker.properties.template
-rw-r--r--  1 root root 1105 Nov  9 22:57 fairscheduler.xml.template
-rw-r--r--  1 root root 2025 Nov  9 22:57 log4j.properties.template
-rw-r--r--  1 root root 7313 Nov  9 22:57 metrics.properties.template
-rw-r--r--  1 root root  865 Nov  9 22:57 slaves.template
-rw-r--r--  1 root root 1292 Nov  9 22:57 spark-defaults.conf.template
-rwxr-xr-x  1 root root 3699 Nov  9 22:57 spark-env.sh.template*
```

Do I need to modify any thing to point to existing Hive server rather than creating new. Kindly help me on the same.

答:
In hive-site.xml use properties :

```<code><property>
  <name>javax.jdo.option.ConnectionURL</name>
  <value>jdbc:mysql://<<hostname>>:<<port>>/hive?createDatabaseIfNotExist=true</value>
</property>

<property>
  <name>javax.jdo.option.ConnectionDriverName</name>
  <value>com.mysql.jdbc.Driver</value>
</property>

<property>
  <name>javax.jdo.option.ConnectionUserName</name>
  <value>username</value>
</property>

<property>
  <name>javax.jdo.option.ConnectionPassword</name>
  <value>password</value>
</property>
</code>```

Then,  put hive-site.xml in conf folder of spark installation after it try again

Body:
I am trying to get databases or table details of Hive from spark using HiveContext. But I am unable to point to existing Hive Database as shown below:
Spark Version: 2.2.0
Hive Version : 2.3.0

Using below script in Spark Shell to connect to existing Hive Server(127.0.0.1 used below is my machine ip address):

scala> val hc = new org.apache.spark.sql.hive.HiveContext(sc)
warning: there was one deprecation warning; re-run with -deprecation for details
hc: org.apache.spark.sql.hive.HiveContext = org.apache.spark.sql.hive.HiveContext@6dde913e

scala> hc.setConf("hive.metastore.uris","thrift://127.0.0.1:9083")

scala> val df = hc.sql("show databases")
df: org.apache.spark.sql.DataFrame = [databaseName: string]

scala> df.show
+------------+
|databaseName|
+------------+
|     default|
+------------+

scala> val dfTables = hc.sql("show tables");
dfTables: org.apache.spark.sql.DataFrame = [database: string, tableName: string ... 1 more field]

scala> dfTables.show
+--------+---------+-----------+
|database|tableName|isTemporary|
+--------+---------+-----------+
+--------+---------+-----------+

As shown above I am unable to get the existing Hive databases and tables available. HiveContext is pointing to new database(default) and no tables available.
Below are my hive db listed:

hive> show databases;
OK
default
mydbbackup
Time taken: 7.593 seconds, Fetched: 2 row(s)
hive> use mydbbackup;
OK
Time taken: 0.021 seconds
hive> show tables;
OK
customers
customerspart
customerspart1
Time taken: 0.194 seconds, Fetched: 3 row(s)
hive>

Below is my hive-site.xml:

<configuration>
<property>
<name>javax.jdo.option.ConnectionURL</name>
<value>jdbc:derby:;databaseName=/home/hduser/apache-hive-2.3.0-bin/metastore_db;create=true</value>
<description>
JDBC connect string for a JDBC metastore.
To use SSL to encrypt/authenticate the connection, provide database-specific SSL flag in the connection URL.
For example, jdbc:postgresql://myhost/db?ssl=true for postgres database.
</description>
</property>
<property>
<name>hive.metastore.warehouse.dir</name>
<value>/user/hive/warehouse</value>
<description>location of default database for the warehouse</description>
</property>
<property>
<name>hive.metastore.uris</name>
<value/>
<description>Thrift URI for the remote metastore. Used by metastore client to connect to remote metastore.</description>
</property>
<property>
<name>javax.jdo.option.ConnectionDriverName</name>
<value>org.apache.derby.jdbc.EmbeddedDriver</value>
<description>Driver class name for a JDBC metastore</description>
</property>
<property>
<name>javax.jdo.PersistenceManagerFactoryClass</name>
<value>org.datanucleus.api.jdo.JDOPersistenceManagerFactory</value>
<description>class implementing the jdo persistence</description>
</property>
</configuration>

Below is my spark conf Directory:

total 40
drwxr-xr-x  2 root root 4096 Nov 12 20:22 ./
drwxr-xr-x 12 root root 4096 Nov  9 22:57 ../
-rw-r--r--  1 root root  996 Nov  9 22:57 docker.properties.template
-rw-r--r--  1 root root 1105 Nov  9 22:57 fairscheduler.xml.template
-rw-r--r--  1 root root 2025 Nov  9 22:57 log4j.properties.template
-rw-r--r--  1 root root 7313 Nov  9 22:57 metrics.properties.template
-rw-r--r--  1 root root  865 Nov  9 22:57 slaves.template
-rw-r--r--  1 root root 1292 Nov  9 22:57 spark-defaults.conf.template
-rwxr-xr-x  1 root root 3699 Nov  9 22:57 spark-env.sh.template*

Do I need to modify any thing to point to existing Hive server rather than creating new. Kindly help me on the same.

Body:
In hive-site.xml use properties :

<property>
  <name>javax.jdo.option.ConnectionURL</name>
  <value>jdbc:mysql://<<hostname>>:<<port>>/hive?createDatabaseIfNotExist=true</value>
</property>

<property>
  <name>javax.jdo.option.ConnectionDriverName</name>
  <value>com.mysql.jdbc.Driver</value>
</property>

<property>
  <name>javax.jdo.option.ConnectionUserName</name>
  <value>username</value>
</property>

<property>
  <name>javax.jdo.option.ConnectionPassword</name>
  <value>password</value>
</property>

Then,  put hive-site.xml in conf folder of spark installation after it try again


来源: stackexchange

问:
DAO method can be annotated with only one of the following:Insert,Delete,Query,Update
Im new of Room library and want to make simple project .

Here is entity class.

```<code>@Entity(tableName = "user")
public class User {

    @PrimaryKey
    private Integer id;
    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
</code>```

Here is dao class.

```<code>@Dao
public interface UserDao extends Dao {

    @Query("SELECT * FROM user")
    List<User> getAll();

    @Insert
    void insert(User users);

}
</code>```

Here is AppDatabase class.

```<code>@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {

    private static AppDatabase INSTANCE;

    public abstract UserDao userDao();

    public static AppDatabase getAppDatabase(Context context) {
        if (INSTANCE == null) {
            INSTANCE =
                    Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, "database-test")
                            .allowMainThreadQueries()
                            .build();
        }
        return INSTANCE;
    }

    public static void destroyInstance() {
        INSTANCE = null;
    }
}
</code>```

And here is my mainactivity.

```<code>User user = new User();
        user.setName("Test");
        user.setId(2);

        AppDatabase.getAppDatabase(this).userDao().insert(user);
        AppDatabase.getAppDatabase(this).userDao().getAll();
</code>```

But when I run this code above . I get error behind below .

Error:(14, 8) error: Abstract method in DAO must be annotated with
  interface android.arch.persistence.room.Query AND interface
  android.arch.persistence.room.Insert

I search it but cannot find anything . Thanks for any suggestion .

答:
Your DAO interface shouldn't extend Dao interface.</p>

```<code>@Dao
public interface UserDao {

    @Query("SELECT * FROM user")
    List<User> getAll();

    @Insert
    void insert(User users);

}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Im new of Room library and want to make simple project .

Here is entity class.

@Entity(tableName = "user")
public class User {

    @PrimaryKey
    private Integer id;
    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Here is dao class.

@Dao
public interface UserDao extends Dao {

    @Query("SELECT * FROM user")
    List<User> getAll();

    @Insert
    void insert(User users);

}

Here is AppDatabase class.

@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {

    private static AppDatabase INSTANCE;

    public abstract UserDao userDao();

    public static AppDatabase getAppDatabase(Context context) {
        if (INSTANCE == null) {
            INSTANCE =
                    Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, "database-test")
                            .allowMainThreadQueries()
                            .build();
        }
        return INSTANCE;
    }

    public static void destroyInstance() {
        INSTANCE = null;
    }
}

And here is my mainactivity.

User user = new User();
        user.setName("Test");
        user.setId(2);

        AppDatabase.getAppDatabase(this).userDao().insert(user);
        AppDatabase.getAppDatabase(this).userDao().getAll();

But when I run this code above . I get error behind below .

Error:(14, 8) error: Abstract method in DAO must be annotated with
  interface android.arch.persistence.room.Query AND interface
  android.arch.persistence.room.Insert

I search it but cannot find anything . Thanks for any suggestion .

Body:
Your DAO interface shouldn't extend Dao interface.

@Dao
public interface UserDao {

    @Query("SELECT * FROM user")
    List<User> getAll();

    @Insert
    void insert(User users);

}


问:
datatables.net: how to use responsive plus checkbox in datatables?
i am using Datatable.net framework for tables.

my problem is this i want 2 thing in same datatable one is responsive and 2nd is Checkbox.

this is script i am using for this

```<code>$(document).ready(function() {
    $('#example').DataTable( {
        responsive: true,
        columnDefs: [ {
            orderable: false,
            className: 'select-checkbox',
            targets:   0
        } ],
        select: {
            style:    'os',
            selector: 'tr'
        },
        order: [[ 1, 'asc' ]]
    } );
} );
</code>```

this is HTML i am using.

```<code><table id="example" class="display" width="100%" cellspacing="0">
    <thead>
        <tr>
            <th></th>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Salary</th>
        </tr>
    </thead>
    <tfoot>
        <tr>
            <th></th>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Salary</th>
        </tr>
    </tfoot>
    <tbody>
        <tr>
            <td></td>
            <td>Tiger Nixon</td>
            <td>System Architect</td>
            <td>Edinburgh</td>
            <td>61</td>
            <td>$320,800</td>
        </tr>
    </tbody>
</table>
</code>```

答:
I think you missed something, if you want use Datatables's extensions then you should add extensions library, otherwise it won't work,

So you can see working code in this link  jsfiddle.net/1eLg1Lgy/

JavaScript

```<code>$(document).ready(function() {
    $('#example').DataTable( {
        responsive: true,
        columnDefs: [ {
            orderable: false,
            className: 'select-checkbox',
            targets:   0
        } ],
        select: {
            style:    'os',
            selector: 'tr'
        },
        order: [[ 1, 'asc' ]]
    } );
} );
</code>```

HTML

```<code><table id="example" class="display" width="100%" cellspacing="0">
<thead>
<tr>
    <th></th>
    <th>Name</th>
    <th>Position</th>
    <th>Office</th>
    <th>Age</th>
    <th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
    <th></th>
    <th>Name</th>
    <th>Position</th>
    <th>Office</th>
    <th>Age</th>
    <th>Salary</th>
</tr>
</tfoot>
<tbody>
<tr>
    <td></td>
    <td>Tiger Nixon</td>
    <td>System Architect</td>
    <td>Edinburgh</td>
    <td>61</td>
    <td>$320,800</td>
</tr>
</tbody>
</code>```

and extension link is here cdn.datatables.net/#Extensions

Body:
i am using Datatable.net framework for tables.

my problem is this i want 2 thing in same datatable one is responsive and 2nd is Checkbox.

this is script i am using for this

$(document).ready(function() {
    $('#example').DataTable( {
        responsive: true,
        columnDefs: [ {
            orderable: false,
            className: 'select-checkbox',
            targets:   0
        } ],
        select: {
            style:    'os',
            selector: 'tr'
        },
        order: [[ 1, 'asc' ]]
    } );
} );

this is HTML i am using.

            Name
            Position
            Office
            Age
            Salary

            Name
            Position
            Office
            Age
            Salary

            Tiger Nixon
            System Architect
            Edinburgh
            61
            $320,800

Body:
I think you missed something, if you want use Datatables's extensions then you should add extensions library, otherwise it won't work,

So you can see working code in this link  jsfiddle.net/1eLg1Lgy/

JavaScript

$(document).ready(function() {
    $('#example').DataTable( {
        responsive: true,
        columnDefs: [ {
            orderable: false,
            className: 'select-checkbox',
            targets:   0
        } ],
        select: {
            style:    'os',
            selector: 'tr'
        },
        order: [[ 1, 'asc' ]]
    } );
} );

HTML

<table id="example" class="display" width="100%" cellspacing="0">
<thead>
<tr>
    <th></th>
    <th>Name</th>
    <th>Position</th>
    <th>Office</th>
    <th>Age</th>
    <th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
    <th></th>
    <th>Name</th>
    <th>Position</th>
    <th>Office</th>
    <th>Age</th>
    <th>Salary</th>
</tr>
</tfoot>
<tbody>
<tr>
    <td></td>
    <td>Tiger Nixon</td>
    <td>System Architect</td>
    <td>Edinburgh</td>
    <td>61</td>
    <td>$320,800</td>
</tr>
</tbody>

and extension link is here cdn.datatables.net/#Extensions


问:
Unifying surrogate pairs in Japanese "dakuten" characters using R
I was trying to match a vector of Japanese strings (originally imported from a comma-separated file) with a list of filenames extracted from a folder under Mac OSX.

One element from the vector is a:

```<code>> a
[1] "立ち上げる.mp3"
</code>```

The corresponding element from the filename is b

```<code>> b
[1] "立ち上げる.mp3"
</code>```

The problem is that they are not logically equal to each other in R:

```<code>> a == b
[1] FALSE
</code>```

I already found out that this is a problem emerged from the surrogate pairs of Japanese "dakuten" characters (i.e. the げ character that was extended from け by adding additional dots). So they're in fact different from each other:

```<code>> iconv(a, "latin1")
[1] "ç«\u008bã\u0081¡ä¸\u008aã\u0081\u0092ã\u0082\u008b.mp3"
> iconv(b, "latin1")
[1] "ç«\u008bã\u0081¡ä¸\u008aã\u0081\u0091ã\u0082\u0099ã\u0082\u008b.mp3"

> nchar(a)
[1] 9
> nchar(b)
[1] 10
</code>```

How do I convert these two versions of the same Japanese characters so that they can be matched validly (i.e. they should be the same) using R?

答:
There is an open-source bridge library to call ICU library RUnicode. You may normalize search key to NFD(Mac OS X style) when on Mac OS X.

It normalizes other Japanese letters like full-width and half-width katakana, which might or might not for your purpose.

Body:
I was trying to match a vector of Japanese strings (originally imported from a comma-separated file) with a list of filenames extracted from a folder under Mac OSX.

One element from the vector is a:

> a
[1] "立ち上げる.mp3"

The corresponding element from the filename is b

> b
[1] "立ち上げる.mp3"

The problem is that they are not logically equal to each other in R:

> a == b
[1] FALSE

I already found out that this is a problem emerged from the surrogate pairs of Japanese "dakuten" characters (i.e. the げ character that was extended from け by adding additional dots). So they're in fact different from each other:

> iconv(a, "latin1")
[1] "ç«\u008bã\u0081¡ä¸\u008aã\u0081\u0092ã\u0082\u008b.mp3"
> iconv(b, "latin1")
[1] "ç«\u008bã\u0081¡ä¸\u008aã\u0081\u0091ã\u0082\u0099ã\u0082\u008b.mp3"

> nchar(a)
[1] 9
> nchar(b)
[1] 10

How do I convert these two versions of the same Japanese characters so that they can be matched validly (i.e. they should be the same) using R?


问:
Create a method called filter that has two string parameters and returns a string
The method will filter out all occurrences of the second string from the first sting. The filter is case sensitive. Do not filter out cat if the second argument is CAT.

```<code>public static void main(String[] args){        // should filter out the
  System.out.println("method: filter");       // second string
  System.out.println(filter( "CS221 is terrible", "terrible"));
  System.out.println(filter( "my cat is a nice cat", "cat"));
  System.out.println(filter( "ababababa","ab"));
  System.out.println(filter( "not here", "a"));
  System.out.println(filter( "abababab","ab"));
  System.out.println(filter( "CATcatCAT","CAT"));
  System.out.println(filter( "dark","k"));
  System.out.println(filter("ususerer", "user"));
}
public static String filter ( String str, String filter){
  String temp = "";
  int i = 0;

  while(i < str.length() && str.indexOf(filter,i) != -1){
     if(str.indexOf(filter,i)!=-1){
         temp+=str.substring(i, str.indexOf(filter,i));
     }else{
         temp+=str.substring(i,str.length());
     }
     i = str.indexOf(filter, i)+ filter.length();
     i++;
  }
  return temp;

}
</code>```

Output of the code

```<code> CS221 is
 my is a nice
 b

 b
 at
 dar
 us
</code>```

Expected output

```<code> CS221 is
 my is a nice
 a
 not here
 nothing prints at all on this line its just blank
 cat
 dar
 user
</code>```

答:
I don't know why you're reinventing the wheel...

```<code>public static String filter (String str, String filter)
    return str.replaceAll(" ?" + filter, "");
}
</code>```

You need to use regex to get the optional leading space, which turns:

```<code>"my cat is a nice cat" // input
"my is a nice"         // output correct as per your question
</code>```

If you use plain replacement, ie str.replace(filter, ""), you get this effect:

```<code>"my cat is a nice cat" // input
"my  is a nice "       // incorrect: notice the double spaces
</code>```

Body:
The method will filter out all occurrences of the second string from the first sting. The filter is case sensitive. Do not filter out cat if the second argument is CAT.

public static void main(String[] args){        // should filter out the
  System.out.println("method: filter");       // second string
  System.out.println(filter( "CS221 is terrible", "terrible"));
  System.out.println(filter( "my cat is a nice cat", "cat"));
  System.out.println(filter( "ababababa","ab"));
  System.out.println(filter( "not here", "a"));
  System.out.println(filter( "abababab","ab"));
  System.out.println(filter( "CATcatCAT","CAT"));
  System.out.println(filter( "dark","k"));
  System.out.println(filter("ususerer", "user"));
}
public static String filter ( String str, String filter){
  String temp = "";
  int i = 0;

  while(i < str.length() && str.indexOf(filter,i) != -1){
     if(str.indexOf(filter,i)!=-1){
         temp+=str.substring(i, str.indexOf(filter,i));
     }else{
         temp+=str.substring(i,str.length());
     }
     i = str.indexOf(filter, i)+ filter.length();
     i++;
  }
  return temp;

}

Output of the code

 CS221 is
 my is a nice
 b

 b
 at
 dar
 us

Expected output

 CS221 is
 my is a nice
 a
 not here
 nothing prints at all on this line its just blank
 cat
 dar
 user

Body:
I don't know why you're reinventing the wheel...

public static String filter (String str, String filter)
    return str.replaceAll(" ?" + filter, "");
}

You need to use regex to get the optional leading space, which turns:

"my cat is a nice cat" // input
"my is a nice"         // output correct as per your question

If you use plain replacement, ie str.replace(filter, ""), you get this effect:

"my cat is a nice cat" // input
"my  is a nice "       // incorrect: notice the double spaces


问:
Temp Table usuage in a Multi User Environment
here's the situation:

I have an SSRS report that uses an SP as a Dataset.  The SP creates a Temp Table, inserts a bunch of data into it, and select's it back out for SSRS to report. Pretty straight forward.

Question:

If multiple users run the report with different parameters selected, will the temp table created by the SP collide in the tempdb and potentially not return the data set expected?

答: A temp table with a single # is a local temporary table and its scope is limited to the session that created it, so collisions should not be a problem.

ContentLicense: CC BY-SA 2.5


问:
Getting a loaded SCRIPT variable in nightmarejs
I want to get the value from a loaded script.js when using .evaluate() in nightmare. So let's say there is this basic html on some website...

```<code><!doctype html>
<head>
<title> far-away-website.com</title>
    <script src="script.js"></script>
 <script src="script-two.js"></script>
</head>

<body>
  <div> DOM stuff</div>
</body>
</html>
</code>```

And it's script.js has this...

```<code>func.prototype.hasData = function() {
                return this.data
            }
</code>```

How can I get the value of this.data from .evaluate() in nightmarejs?...

```<code>var Nightmare = require('nightmare');
var nightmare = Nightmare({
    // waitTimeout: 60000, // in ms
    openDevTools: {
        //mode: 'detach'
    },
    show: true
})
nightmare.goto('https://www.far-away-website.com')

    .evaluate(() => {
            return this.data // needed from script.js
    })

.then((data) => {
console.log(data)
})
</code>```

P.S. The value of this.data can be seen using watch in chrome dev tools.

答:
The following code simply shows that this refers to only that object. If that object is in global window, you can access it by creating a object and using the .hasData() function property.

Otherwise you cannot access this.data since it's in a different function scope. You can read more about how you can take advantage of that by reading some materials.

Also, you did not share a real working website/code, cannot help much without that.

Read more about this, here and here.
Read more about scopes, here.

Body:
I want to get the value from a loaded script.js when using .evaluate() in nightmare. So let's say there is this basic html on some website...

<!doctype html>

<title> far-away-website.com</title>

 DOM stuff

And it's script.js has this...

func.prototype.hasData = function() {
                return this.data
            }

How can I get the value of this.data from .evaluate() in nightmarejs?...

var Nightmare = require('nightmare');
var nightmare = Nightmare({
    // waitTimeout: 60000, // in ms
    openDevTools: {
        //mode: 'detach'
    },
    show: true
})
nightmare.goto('https://www.far-away-website.com')

    .evaluate(() => {
            return this.data // needed from script.js
    })

.then((data) => {
console.log(data)
})

P.S. The value of this.data can be seen using watch in chrome dev tools.


问:
"log4j.logger.java.sql=DETAIL, roothandle" prints query and resultSet, Is there any way to mask some column fields of query result?
"log4j.logger.java.sql=DETAIL, roothandle"

When this line is added in log4j properties file, it prints iBatis/myBatis query and results of those queries.
Result might have password, cardNumber or some other personal information, which I dont want to print in logs.

Is there any way to mask such fields while printing in logs??

答:
Given your package name is com.mypackage
Then remove this line:

"log4j.logger.java.sql=DETAIL, roothandle"

Just make sure this line is in the log4j.properties:

"log4j.logger.com.mypackage=DEBUG, roothandle"

This will result in the log showing:
* The sql statement
* The parameters passed in to the sql

Hope the above helps


问:
Connect to a MySQL server over SSH in PHP
I have my database on remote Linux machine, and I want to connect using SSH and PHP functions (I am currently using ssh2 library for that). I tried using mysql_connect, but it gives me can't access (although I have granted permission)
when I tried using this function:

```<code>$connection = ssh2_connect('SERVER IP', 22);

ssh2_auth_password($connection, 'username', 'password');

$tunnel = ssh2_tunnel($connection, 'DESTINATION IP', 3307);

$db = mysqli_connect('127.0.0.1', 'DB_USERNAME', 'DB_PASSWORD',
                         'dbname', 3307, $tunnel)
    or die ('Fail: '.mysql_error());
</code>```

I got error "mysqli_connect() expects parameter 6 to be string, resource given". How can I resolve this?

答:
even i tried it by doing ssh both by root credentials and and public private key pair, but it allows me to conect through command line but not through php code. I tried by creating tunnel also(by using ssh2 functions),ans running shell commands from php code(system,exec etc), nothing worked. Finally i tried ssh2 function to execute shell command and it finally worked :) Here is code, if it helps you:----

```<code>$connection = ssh2_connect($remotehost, '22');
if (ssh2_auth_password($connection, $user,$pass)) {
    echo "Authentication Successful!\n";
} else {
    die('Authentication Failed...');
}

$stream=ssh2_exec($connection,'echo "select * from zingaya.users where id=\"1606\";" | mysql');
stream_set_blocking($stream, true);
while($line = fgets($stream)) {
    flush();
    echo $line."\n";
}
</code>```

it worked for me try this if want to use php functions specifically.

OwnerDisplayName: spooja

LastEditorDisplayName: Till

ContentLicense: CC BY-SA 4.0

Body:
I have my database on remote Linux machine, and I want to connect using SSH and PHP functions (I am currently using ssh2 library for that). I tried using mysql_connect, but it gives me can't access (although I have granted permission)
when I tried using this function:

$connection = ssh2_connect('SERVER IP', 22);

ssh2_auth_password($connection, 'username', 'password');

$tunnel = ssh2_tunnel($connection, 'DESTINATION IP', 3307);

$db = mysqli_connect('127.0.0.1', 'DB_USERNAME', 'DB_PASSWORD',
                         'dbname', 3307, $tunnel)
    or die ('Fail: '.mysql_error());

I got error "mysqli_connect() expects parameter 6 to be string, resource given". How can I resolve this?

Body:
even i tried it by doing ssh both by root credentials and and public private key pair, but it allows me to conect through command line but not through php code. I tried by creating tunnel also(by using ssh2 functions),ans running shell commands from php code(system,exec etc), nothing worked. Finally i tried ssh2 function to execute shell command and it finally worked :) Here is code, if it helps you:----

$connection = ssh2_connect($remotehost, '22');
if (ssh2_auth_password($connection, $user,$pass)) {
    echo "Authentication Successful!\n";
} else {
    die('Authentication Failed...');
}

$stream=ssh2_exec($connection,'echo "select * from zingaya.users where id=\"1606\";" | mysql');
stream_set_blocking($stream, true);
while($line = fgets($stream)) {
    flush();
    echo $line."\n";
}

it worked for me try this if want to use php functions specifically.


问:
Android: add buttons to a preference screen
The thing is...I want to use PreferenceActivity to add a new row in my custom list view. So my preference ativity will consist of a few EditTextPreferences, my custom TimePickerPreference and a coulpe of ListPreferences... Like this: http://www.google.com/help/hc/images/android/android_ug/168567.5.png . The question is how they added buttons on the bottom? And.. is it possible to use OnClickListener for obtaining inputed values and how? Thanks!</p>

答: A PreferenceActivity inherits from ListActivity. By default, ListActivity creates its own ListView, but you can supply your own layout via setContentView(), so long as your ListView in the layout has the right android:id. Here is the layout for the alarm activity.


问:
Array highest value or create next value?
I have an array of names and id's.

```<code>Array(
    0=>array(
        name=>New York,
        id=>45763448349,
        can=0
    ),
    1=>array(
        name=>New York2,
        id=>45763464566,
        can=0
    ),
    3=>array(
        name=>New York3,
        id=>45763464854,
        can=0
    ),
    4=>array(
        name=>New York4,
        id=>45763464955,
        can=0
    ),
    5=>array(
        name=>New York5,
        id=>45763464745,
        can=0
    ),
    6=>array(
        name=>New York6,
        id=>45763464235,
        can=1
    )
)
</code>```

For example (there will be different names (not all New York)) and I have an x variable with a name (for example x=New York) what I need to do is find the highest name and get the id and then make sure can is 1 otherwise specific the next highest name.

For example let's assume that I have x=New York so I look through the array and find that the highest array name is New York6. I see that can=1 so I just get the id. Now if can != 1 then I could specific New York7.

NOTE: This array will contain many different values (not all New York, I just used those for an example)

Now how on earth would I even get started?

答:
In code:

```<code>function city_cmp($record_a, $record_b) {
  return strcmp($record_a["name"], $record_b["name"];
}

usort($cities, 'city_cmp');
end($cities);
$city = current($cities);
do {
    if ($city["can"] === 1) {
         $can_city = $city;
         break;
    }

} while ($city = prev($cities));
</code>```

Note: optionally, you could skip the break and make $can_city part of your while condition. Some prefer that as it can make the loop exit condition clearer.

In quick steps:

usort() the array

use end() to point at the end of the array and prev() until you find a can=1.

Body:
I have an array of names and id's.

Array(
    0=>array(
        name=>New York,
        id=>45763448349,
        can=0
    ),
    1=>array(
        name=>New York2,
        id=>45763464566,
        can=0
    ),
    3=>array(
        name=>New York3,
        id=>45763464854,
        can=0
    ),
    4=>array(
        name=>New York4,
        id=>45763464955,
        can=0
    ),
    5=>array(
        name=>New York5,
        id=>45763464745,
        can=0
    ),
    6=>array(
        name=>New York6,
        id=>45763464235,
        can=1
    )
)

For example (there will be different names (not all New York)) and I have an x variable with a name (for example x=New York) what I need to do is find the highest name and get the id and then make sure can is 1 otherwise specific the next highest name.

For example let's assume that I have x=New York so I look through the array and find that the highest array name is New York6. I see that can=1 so I just get the id. Now if can != 1 then I could specific New York7.

NOTE: This array will contain many different values (not all New York, I just used those for an example)

Now how on earth would I even get started?

Body:
In code:

function city_cmp($record_a, $record_b) {
  return strcmp($record_a["name"], $record_b["name"];
}

usort($cities, 'city_cmp');
end($cities);
$city = current($cities);
do {
    if ($city["can"] === 1) {
         $can_city = $city;
         break;
    }

} while ($city = prev($cities));

Note: optionally, you could skip the break and make $can_city part of your while condition. Some prefer that as it can make the loop exit condition clearer.

In quick steps:

usort() the array

use end() to point at the end of the array and prev() until you find a can=1.


问:
CSS - can't get two divs to center within containing div
I need to get divs stacked on top of each other, horizontally aligned center -- within the black box.

I have this much:

.notification-dot-layer {
    margin: auto;
    width: 48px;
    height: 60px;
    position: relative;
    text-align: center;
    border: 1px solid black;
        text-align: center;
}

    .test {
  content: "";
  position: absolute;
  z-index: -10;
  top: 0;
  bottom: 0;
  left: 50%;
  border-left: 4px solid #00ff00;
  transform: translate(-50%);
width: 0px;
  }

.notificationbluedot {
    height: 48px;
    width: 48px;
    background-color: #3a3b7e;
    border-radius: 50%;
    margin: 0 auto;
 }

.notification-dot-text {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="notification-dot-layer">
<div class="test">
<div class="notificationbluedot">
<div class="notification-dot-text">
55
</div>
</div>
</div>
</div></code>```

Run the code snippet to see the results. Unfortunately, I can't get the blue circle with the "55" on it on top of the green line, centered. When the circle with the 55 is over the green line, only the portions of the green line that would be exposed should show.

What am I missing?

I need this to work in IE11 and Chrome.

答:
add  .notificationbluedot {margin-left: -25px ;top:10%;position: absolute;} on your css

.notification-dot-layer {
  margin: auto;
  width: 48px;
  height: 60px;
  position: relative;
  text-align: center;
  border: 1px solid black;
  text-align: center;
}

.test {
  content: "";
  position: absolute;
  z-index: -10;
  top: 0;
  bottom: 0;
  left: 50%;
  border-left: 4px solid #00ff00;
  transform: translate(-50%);
  width: 0;
  //margin: 5px auto;

}

.notificationbluedot {
  height: 48px;
  width: 48px;
  background-color: #3a3b7e;
  border-radius: 50%;
  margin-left: -25px ;
  top:10%;
  position: absolute;

}

.notification-dot-text {
  position: relative;
  top: 50%;
 // left: -50%;
  transform: translateY(-50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="notification-dot-layer">
  <div class="test">
    <div class="notificationbluedot">
      <div class="notification-dot-text">
        55
      </div>
    </div>
  </div>
</div></code>```

Body:
I need to get divs stacked on top of each other, horizontally aligned center -- within the black box.

I have this much:

.notification-dot-layer {
    margin: auto;
    width: 48px;
    height: 60px;
    position: relative;
    text-align: center;
    border: 1px solid black;
        text-align: center;
}

    .test {
  content: "";
  position: absolute;
  z-index: -10;
  top: 0;
  bottom: 0;
  left: 50%;
  border-left: 4px solid #00ff00;
  transform: translate(-50%);
width: 0px;
  }

.notificationbluedot {
    height: 48px;
    width: 48px;
    background-color: #3a3b7e;
    border-radius: 50%;
    margin: 0 auto;
 }

.notification-dot-text {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
 }

55

Run the code snippet to see the results. Unfortunately, I can't get the blue circle with the "55" on it on top of the green line, centered. When the circle with the 55 is over the green line, only the portions of the green line that would be exposed should show.

What am I missing?

I need this to work in IE11 and Chrome.

Body:
add  .notificationbluedot {margin-left: -25px ;top:10%;position: absolute;} on your css

.notification-dot-layer {
  margin: auto;
  width: 48px;
  height: 60px;
  position: relative;
  text-align: center;
  border: 1px solid black;
  text-align: center;
}

.test {
  content: "";
  position: absolute;
  z-index: -10;
  top: 0;
  bottom: 0;
  left: 50%;
  border-left: 4px solid #00ff00;
  transform: translate(-50%);
  width: 0;
  //margin: 5px auto;

}

.notificationbluedot {
  height: 48px;
  width: 48px;
  background-color: #3a3b7e;
  border-radius: 50%;
  margin-left: -25px ;
  top:10%;
  position: absolute;

}

.notification-dot-text {
  position: relative;
  top: 50%;
 // left: -50%;
  transform: translateY(-50%);
}

<div class="notification-dot-layer">
  <div class="test">
    <div class="notificationbluedot">
      <div class="notification-dot-text">
        55
      </div>
    </div>
  </div>
</div>


问:
How to set authorization header in node js?
Hello I am working on node application in which I am working on jsonwebtokens,passport-jwt.I created application backend side and working fine on postman but I stuck on front end side. when i send token in headers in postman then token based page open on postman fine but on front side display unauthorized.How can i send token in header so that this page also open on front end side.
My code:

```<code>app.post("/login", function(req, res) {
  if(req.body.name && req.body.password){
    var name = req.body.name;
    var password = req.body.password;
  }

  var user = users[_.findIndex(users, {name: name})];
  if( ! user ){
    res.status(401).json({message:"no such user found"});
  }

  if(user.password === req.body.password) {
    // from now on we'll identify the user by the id and the id is the only personalized value that goes into our token
    var payload = {id: user.id};
    var token = jwt.sign(payload, jwtOptions.secretOrKey);
    //res.json({message: "ok", token: token});
   res.redirect('/secret')
  } else {
    res.status(401).json({message:"passwords did not match"});
  }
});

app.get("/secret", passport.authenticate('jwt', { session: false }), function(req, res){
    res.json("Success! You can not see this without a token");

  });
</code>```

Where am i doing wrong??

答:
```<code>if you are getting token,you can send it as:
</code>```

**

let headers = new Headers({ 'Content-Type': 'application/json',
  'Authorization': 'Bearer ' + this.token });

**

Body:
Hello I am working on node application in which I am working on jsonwebtokens,passport-jwt.I created application backend side and working fine on postman but I stuck on front end side. when i send token in headers in postman then token based page open on postman fine but on front side display unauthorized.How can i send token in header so that this page also open on front end side.
My code:

app.post("/login", function(req, res) {
  if(req.body.name && req.body.password){
    var name = req.body.name;
    var password = req.body.password;
  }

  var user = users[_.findIndex(users, {name: name})];
  if( ! user ){
    res.status(401).json({message:"no such user found"});
  }

  if(user.password === req.body.password) {
    // from now on we'll identify the user by the id and the id is the only personalized value that goes into our token
    var payload = {id: user.id};
    var token = jwt.sign(payload, jwtOptions.secretOrKey);
    //res.json({message: "ok", token: token});
   res.redirect('/secret')
  } else {
    res.status(401).json({message:"passwords did not match"});
  }
});

app.get("/secret", passport.authenticate('jwt', { session: false }), function(req, res){
    res.json("Success! You can not see this without a token");

  });

Where am i doing wrong??

Body:
if you are getting token,you can send it as:

**

let headers = new Headers({ 'Content-Type': 'application/json',
  'Authorization': 'Bearer ' + this.token });

**


问:
Upload contents of Excel worksheet to Google Sheet worksheet
I have an Excel sheet with a worksheet named test_sheet. I have a Google sheet named G_sheet having 5 tabs. I would like to automate the process of copying the contents of Excel worksheet test_sheet and paste it in a specific tab, say 'sheet1', of the Google sheet. How can be done this using excel VBA?

I am using Excel 2013.

答:
You could use googles program called Backup and Sync to easily save any folder on your computer to your google drive.

You just have to set up the sync settings to where it only saves that one excel sheet to a place on your computer. And then every time you save the doc it will automatically be synced with the copy of the excel sheet on your google drive.


问:
editText.setOnEditorActionListener error on developer.android.com
I see this code on developer.android.com for handle the IME_ACTION of the softkeyboard:

```<code>EditText editText = (EditText) findViewById(R.id.search);
editText.setOnEditorActionListener(new OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        boolean handled = false;
        if (actionId == EditorInfo.IME_ACTION_SEND) {
            sendMessage();
            handled = true;
        }
        return handled;
    }
});
</code>```

If you see, this code not working because the mehod OnEditorActionListener is for a TextView type...

So, what are the right method to haddling the IME_ACTION of the softkeyboard?

答:
Please use ButterKnife instead

```<code>@OnEditorAction(R.id.editText)
protected boolean actionDo(int actionId){
    if (actionId == EditorInfo.IME_ACTION_DONE) {
        doCalculate();
        return true;
    }
    return false;
}
</code>```

It works!

Body:
I see this code on developer.android.com for handle the IME_ACTION of the softkeyboard:

EditText editText = (EditText) findViewById(R.id.search);
editText.setOnEditorActionListener(new OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        boolean handled = false;
        if (actionId == EditorInfo.IME_ACTION_SEND) {
            sendMessage();
            handled = true;
        }
        return handled;
    }
});

If you see, this code not working because the mehod OnEditorActionListener is for a TextView type...

So, what are the right method to haddling the IME_ACTION of the softkeyboard?

Body:
Please use ButterKnife instead

@OnEditorAction(R.id.editText)
protected boolean actionDo(int actionId){
    if (actionId == EditorInfo.IME_ACTION_DONE) {
        doCalculate();
        return true;
    }
    return false;
}

It works!


问:
select data from mysql views
I have 2 tables subscribed-channels and channel-videos.
What i want to achieve is. Select maximum 5 channels from subscribed-channels and then maximum 4 videos fro each channel.
The channels’s position need to be sorted by their most recent uploaded video time. Example below.

Channel 1 – last video uploaded was 5 days ago.

Channel 2 – last video was uploaded 3 days ago.

Channel 3 – last video was uploaded 1 hour ago.

Position in the subscribed-channels.php page for these channels will be like this:

Position 1 (at the top) – Channel 3

Position 2 – Channel 2

Position 3 – Channel 1.

kindly guide me how to write this query.
What I tried:

```<code>SELECT
  usersubscriptions.*,
  uservideos.videoId,uservideos.videoThumbnail
FROM
  usersubscriptions
JOIN
  uservideos ON usersubscriptions.subscribedTo = uservideos.userId
ORDER BY
  uservideos.videoTime DESC,
  usersubscriptions.subscribedTo
</code>```

I created the join but i am not able to limit the data or sort it.

答:
You are seeking a "top n per category" (top 4 per channel) solution. This is harder than it could be because MySQL (as at v5.7 as current) lacks window functions in general and row_number() in particular. There is however a workaround using variables to mimic row_number()

```<code>SELECT
       *
FROM (
      SELECT
            usersubscriptions.*
          , uservideos.videoId
          , uservideos.videoTime
          , uservideos.videoThumbnail
          , @rn := IF(@prev = usersubscriptions.subscribedTo, @rn + 1, 1) AS rn
          , @prev := usersubscriptions.subscribedTo
      FROM usersubscriptions
      JOIN uservideos ON usersubscriptions.subscribedTo = uservideos.userId
      CROSS JOIN (SELECT @prev := NULL, @rn := 0) AS vars
      ORDER BY
            usersubscriptions.subscribedTo
          , uservideos.videoTime DESC
      ) d
WHERE rn <= 4
ORDER BY
      d.videoTime DESC
    , d.subscribedTo
LIMIT 20
;
</code>```

Title: select data from mysql views

Body:
I have 2 tables subscribed-channels and channel-videos.
What i want to achieve is. Select maximum 5 channels from subscribed-channels and then maximum 4 videos fro each channel.
The channels’s position need to be sorted by their most recent uploaded video time. Example below.

Channel 1 – last video uploaded was 5 days ago.

Channel 2 – last video was uploaded 3 days ago.

Channel 3 – last video was uploaded 1 hour ago.

Position in the subscribed-channels.php page for these channels will be like this:

Position 1 (at the top) – Channel 3

Position 2 – Channel 2

Position 3 – Channel 1.

kindly guide me how to write this query.
What I tried:

SELECT
  usersubscriptions.*,
  uservideos.videoId,uservideos.videoThumbnail
FROM
  usersubscriptions
JOIN
  uservideos ON usersubscriptions.subscribedTo = uservideos.userId
ORDER BY
  uservideos.videoTime DESC,
  usersubscriptions.subscribedTo

I created the join but i am not able to limit the data or sort it.

Body:
You are seeking a "top n per category" (top 4 per channel) solution. This is harder than it could be because MySQL (as at v5.7 as current) lacks window functions in general and row_number() in particular. There is however a workaround using variables to mimic row_number()

SELECT
       *
FROM (
      SELECT
            usersubscriptions.*
          , uservideos.videoId
          , uservideos.videoTime
          , uservideos.videoThumbnail
          , @rn := IF(@prev = usersubscriptions.subscribedTo, @rn + 1, 1) AS rn
          , @prev := usersubscriptions.subscribedTo
      FROM usersubscriptions
      JOIN uservideos ON usersubscriptions.subscribedTo = uservideos.userId
      CROSS JOIN (SELECT @prev := NULL, @rn := 0) AS vars
      ORDER BY
            usersubscriptions.subscribedTo
          , uservideos.videoTime DESC
      ) d
WHERE rn <= 4
ORDER BY
      d.videoTime DESC
    , d.subscribedTo
LIMIT 20
;


问:
News manager php/mysql
Can you suggest me a free News Manager in php/mysql for my site?</p>

答: Check Fusion News Management System</p>

Title: News manager php/mysql

Body: Check Fusion News Management System


问:
Java - How do I call this method from the main() method in Java
I am still learning Java and would appreciate some assistance with this current problem: I am trying to call this static method from the main() method, however everything I try comes up with an error message. Thanks for any help.

This is my code:

```<code>public class Statistics {

    static double avgFor(List<Integer> list) {

        list.add(10);
        list.add(20);
        list.add(30);
        list.add(40);
        list.add(50);
        list.add(60);

        int max = list.get(0);

        for (int i : list) {
            max = max < i ? max : i;
        }

        return max;

    }

    public static void main(String[] args) {

        avgFor();

    }

}
</code>```

答:
Your method takes a List as argument. You cannot call the method without providing the argument.</p>

```<code>List<Integer> myList = new ArrayList<>();
avgFor(myList);
</code>```

Body:
I am still learning Java and would appreciate some assistance with this current problem: I am trying to call this static method from the main() method, however everything I try comes up with an error message. Thanks for any help.

This is my code:

public class Statistics {

    static double avgFor(List<Integer> list) {

        list.add(10);
        list.add(20);
        list.add(30);
        list.add(40);
        list.add(50);
        list.add(60);

        int max = list.get(0);

        for (int i : list) {
            max = max < i ? max : i;
        }

        return max;

    }

    public static void main(String[] args) {

        avgFor();

    }

}

Body:
Your method takes a List as argument. You cannot call the method without providing the argument.

List<Integer> myList = new ArrayList<>();
avgFor(myList);


问:
Any type of positioners doesn't work with user-defined element
There's a code of Sensor element. It is like a base class for other sensor types elements:

```<code>Rectangle {
    property real value: 0

    property alias imageWidth: image.width
    property alias imageSource: image.source
    property alias displayWidth: display.width

    width: Math.max(image.width, display.width)
    height: image.height + display.height

    border.width: 1

    Rectangle {
        id: display
        width: 40
        height: 20
        border.width: 1
        color: "lightgreen"

        Text {
            anchors.centerIn: parent
            text: value
            font.pixelSize: parent.width * 0.3;
        }
    }

    Image {
        id: image
        width: display.width * 0.5
        anchors.top: display.bottom
        anchors.horizontalCenter: display.horizontalCenter
        source: "qrc:/images/temperature.png"
        fillMode: Image.PreserveAspectFit
    }
}
</code>```

If I put sensors in a Column, they are located properly.

The implementation of derived type - Pressure:

```<code>Item {
    Sensor {
        imageSource: "qrc:/images/pressure.png"
        imageWidth: displayWidth * 0.4
    }
}
</code>```

But if I put Pressure sensors in a Row or a Column, all sensors just overlap each other.

```<code>Column {
        spacing: 10
        Pressure {}
        Pressure {}
        Pressure {}
}
</code>```

Pressures and Sensors comparison (image)

Could you please explain what's wrong with it?

答:
Oh, it seems I've found the answer by myself.

Items in derived class like Pressure don't have own width and height. If I delete Item, it works properly:

```<code>Sensor {
    imageSource: "qrc:/images/pressure.png"
    imageWidth: displayWidth * 0.4
}
</code>```

Body:
There's a code of Sensor element. It is like a base class for other sensor types elements:

Rectangle {
    property real value: 0

    property alias imageWidth: image.width
    property alias imageSource: image.source
    property alias displayWidth: display.width

    width: Math.max(image.width, display.width)
    height: image.height + display.height

    border.width: 1

    Rectangle {
        id: display
        width: 40
        height: 20
        border.width: 1
        color: "lightgreen"

        Text {
            anchors.centerIn: parent
            text: value
            font.pixelSize: parent.width * 0.3;
        }
    }

    Image {
        id: image
        width: display.width * 0.5
        anchors.top: display.bottom
        anchors.horizontalCenter: display.horizontalCenter
        source: "qrc:/images/temperature.png"
        fillMode: Image.PreserveAspectFit
    }
}

If I put sensors in a Column, they are located properly.

The implementation of derived type - Pressure:

Item {
    Sensor {
        imageSource: "qrc:/images/pressure.png"
        imageWidth: displayWidth * 0.4
    }
}

But if I put Pressure sensors in a Row or a Column, all sensors just overlap each other.

Column {
        spacing: 10
        Pressure {}
        Pressure {}
        Pressure {}
}

Pressures and Sensors comparison (image)

Could you please explain what's wrong with it?

Body:
Oh, it seems I've found the answer by myself.

Items in derived class like Pressure don't have own width and height. If I delete Item, it works properly:

Sensor {
    imageSource: "qrc:/images/pressure.png"
    imageWidth: displayWidth * 0.4
}


问:
Why isn't my for loop adding more than one random value to my list?
I'm trying to create a bubble sort algorithm in java and I'm trying to create a list with random integers in it with a for loop, however it only ever has one value. This is the code:</p>

```<code>public class bubbleSort {

public static void main(String[] args)
{

    int length = getLength();

    System.out.println(length);

    List<Integer> randomList = createArray(length);

    System.out.println(randomList);

}

public static int getLength()
{
    System.out.println("Please enter how long you want the array to be");

    Scanner reader = new Scanner(System.in);

    int length = Integer.parseInt(reader.nextLine());

    return length;
}

public static List<Integer> createArray(int length)
{
    Random rand = new Random();

    List<Integer> randomList = new ArrayList<Integer>();

    for(int x = 0 ; x < (length + 1) ; x++);
    {
        int randomnumber = rand.nextInt((100 - 1) + 1) + 1;
        randomList.add(randomnumber);
    }

    return randomList;
}

}
</code>```

答:
```<code>public static List<Integer> createArray(int length)
{
   Random rand = new Random();

   List<Integer> randomList = new ArrayList<Integer>();

   for(int x = 0 ; x < (length + 1) ; x++)
   {
        int randomnumber = rand.nextInt((100 - 1) + 1) + 1;
        randomList.add(randomnumber);
   }

   return randomList;
}
</code>```

Your problem is here.

You should only create a single Random instance that you use to generate your random numbers.

This is because the random numbers are from a seed value, and when you don't provide a seed for the random number number generator generator, it will be created with a seed value from epoch time, so all your numbers are the same because of this.

A simple solution would be to update your createArray(int length) to take a random instance, like so createArray(int length, Random random) and use this instance to generate the numbers.

Body:
I'm trying to create a bubble sort algorithm in java and I'm trying to create a list with random integers in it with a for loop, however it only ever has one value. This is the code:

public class bubbleSort {

public static void main(String[] args)
{

    int length = getLength();

    System.out.println(length);

    List<Integer> randomList = createArray(length);

    System.out.println(randomList);

}

public static int getLength()
{
    System.out.println("Please enter how long you want the array to be");

    Scanner reader = new Scanner(System.in);

    int length = Integer.parseInt(reader.nextLine());

    return length;
}

public static List<Integer> createArray(int length)
{
    Random rand = new Random();

    List<Integer> randomList = new ArrayList<Integer>();

    for(int x = 0 ; x < (length + 1) ; x++);
    {
        int randomnumber = rand.nextInt((100 - 1) + 1) + 1;
        randomList.add(randomnumber);
    }

    return randomList;
}

}

Body:
public static List<Integer> createArray(int length)
{
   Random rand = new Random();

   List<Integer> randomList = new ArrayList<Integer>();

   for(int x = 0 ; x < (length + 1) ; x++)
   {
        int randomnumber = rand.nextInt((100 - 1) + 1) + 1;
        randomList.add(randomnumber);
   }

   return randomList;
}

Your problem is here.

You should only create a single Random instance that you use to generate your random numbers.

This is because the random numbers are from a seed value, and when you don't provide a seed for the random number number generator generator, it will be created with a seed value from epoch time, so all your numbers are the same because of this.

A simple solution would be to update your createArray(int length) to take a random instance, like so createArray(int length, Random random) and use this instance to generate the numbers.


问:
Get channel category from channel with Discord.js
How does one get the channel category of a channel in Discord.js?</p>

答:
I suggest you read the docs.</p>

```<code>channel.parent;
</code>```

Body:
I suggest you read the docs.

channel.parent;


问:
perl get reference to temp list returned by function without making a copy?
I have a function in perl that returns a list. It is my understanding that when foo() is assigned to list a copy is made:

```<code>sub foo() { return `ping 127.0.0.1` }

my @list = foo();
</code>```

That @list then needs to be transferred to another list like @oldlist = @list; and another copy is made. So I was thinking can I just make a reference from the returned list like my $listref = \foo(); and then I can assign that reference, but that doesn't work.

The function I'm working with runs a command that returns a pretty big list (the ping command is just for example purposes) and I have call it often so I want to minimize the copies if possible. what is a good way to deal with that?

答:
Make an anonymous array reference of the list that is returned

```<code>my $listref = [ foo() ];
</code>```

But, can you not return an arrayref to start with?  That is better in general, too.

What you attempted "takes a reference of a list" ... what one cannot do in the literal sense; a list stands for a mere collection of scalars in a program†, while a reference can be taken (my emphasis)

By using the backslash operator on a variable, subroutine, or value.

and a "list" isn't either (with a subroutine we need syntax \&sub_name)

However, with the \ operator a reference is taken, either to each element of the list if in list context

```<code>my @ref_of_LIST = \( 1,2,3 );  #-->  @ref_of_LIST: (\1, \2, \3)
</code>```

or to a scalar if in scalar context, which is what happens in your attempt. Since your sub returns a list of values, they are evaluated by the comma operator and discarded, one by one, until the last one.  The reference is then taken of that scalar

```<code>my $ref_of_LIST = \( 1,2,3 );  #--> $ref_of_LIST: \3
</code>```

As it happens, all this applies without parens as well, with \foo().

† See the last part of this post (and links in it), for example

Body:
I have a function in perl that returns a list. It is my understanding that when foo() is assigned to list a copy is made:

sub foo() { return `ping 127.0.0.1` }

my @list = foo();

That @list then needs to be transferred to another list like @oldlist = @list; and another copy is made. So I was thinking can I just make a reference from the returned list like my $listref = \foo(); and then I can assign that reference, but that doesn't work.

The function I'm working with runs a command that returns a pretty big list (the ping command is just for example purposes) and I have call it often so I want to minimize the copies if possible. what is a good way to deal with that?

Body:
Make an anonymous array reference of the list that is returned

my $listref = [ foo() ];

But, can you not return an arrayref to start with?  That is better in general, too.

What you attempted "takes a reference of a list" ... what one cannot do in the literal sense; a list stands for a mere collection of scalars in a program†, while a reference can be taken (my emphasis)

By using the backslash operator on a variable, subroutine, or value.

and a "list" isn't either (with a subroutine we need syntax \&sub_name)

However, with the \ operator a reference is taken, either to each element of the list if in list context

my @ref_of_LIST = \( 1,2,3 );  #-->  @ref_of_LIST: (\1, \2, \3)

or to a scalar if in scalar context, which is what happens in your attempt. Since your sub returns a list of values, they are evaluated by the comma operator and discarded, one by one, until the last one.  The reference is then taken of that scalar

my $ref_of_LIST = \( 1,2,3 );  #--> $ref_of_LIST: \3

As it happens, all this applies without parens as well, with \foo().

† See the last part of this post (and links in it), for example


问:
Text field containing multiple values, suggestions in a drop-down (like Gmail "To:" field)
I need functionality in my web application similar to Gmail's drop-down of suggestions when entering recipient addresses, or Stack Overflow's drop-down when entering tags for in question composition.

In Gmail, there is a text field for the "To:" address. Once you start typing, a drop-down appears with suggestions. If you enter a semi-colon or comma, you can enter another address. Again, once you start typing this address, a drop-down appears with suggestions.

The suggestions are the subset of your address book containing the text you've entered. (E.g. if you typed "jo" then "John" and "Foojoe" would appear as suggestions, but "XYZ" would not.) The matched part of the word is highlighted in bold.

If you press "enter" or use the up and down cursor keys, you can navigate around the drop-down suggestion list.

I could presumably program this myself, however I have the feeling there must be standard solutions out there I could incorporate. However, all I found were solutions where the value of the field led to the suggestions, and not the value of the current part of the field led to the suggestions (where each part was separated by a separator, for example "," or ";" in the case of Gmail, or space in the case of Stack Overflow tags).

I am using Wicket (Java server-side Web framework) so any Wicket-specific solution would be great, but otherwise I'm sure I can incorporate any plain Javascript library in the project.

答:
You can use the AutoCompleteTextField class in wicket-extensions for this.

Wicket Examples provides a sample implementation as the first item in its AJAX section. The source code link is kind of hard to see, it's at the right edge of the gray bar.

(The description even says "like google suggest!")


问:
React 16 input type=checkbox not rendered correctly if nested in html a-tag
I have a peculiar problem with using a html a-tag with input type=checkbox  from React. The thing is that if I click directly on the checkbox and not the a-tag the checkbox will not re-render correctly but my state has updated.

Example: Given the code below I render the component and click directly on the checkbox. In this case showMap will be set to false since we set it to true in the constructor but the checkbox will still be checked in the html view. If I however click on the a-tag but not directly on the checkbox both the state showMap is updated correctly as well as the view.

I can make it work by not calling event.preventDefault(); in toggleCheckbox but if I do that the app will scroll to the top of the page if I click on the a-tag.

Example:

https://codesandbox.io/s/w2x8vqq8xl

Code:

```<code>import React from "react";
import { render } from "react-dom";

const styles = {
  fontFamily: "sans-serif",
  textAlign: "center",
  //marginTop: "1000px"
};

class Menu extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showMap: true
    };
  }

  toggleCheckbox = event => {
    this.setState({ showMap: !this.state.showMap });
    event.preventDefault();
  };

  render() {
    return (
      <div>
        <h1>{this.state.showMap ? "Show" : "hide"}</h1>
        <a href="#" role="button" onClick={this.toggleCheckbox}>
          <input
            type="checkbox"
            title="test"
            name="showMap"
            checked={this.state.showMap}
            readOnly
          />
          Show map
        </a>
      </div>

    );
  }
}

const App = () => (
    <div style={styles}>
      <Menu />
    </div>
);

render(<App />, document.getElementById("root"));
</code>```

Update:

Created an issue with React.

https://github.com/facebook/react/issues/11539

答: Instead of using # in href you can use javascript:void(0) in your a-tag to avoid scroll to top. This is useful only if you are having scrolling issue when clicking a tag. Hope this helps!

Body:
I have a peculiar problem with using a html a-tag with input type=checkbox  from React. The thing is that if I click directly on the checkbox and not the a-tag the checkbox will not re-render correctly but my state has updated.

Example: Given the code below I render the component and click directly on the checkbox. In this case showMap will be set to false since we set it to true in the constructor but the checkbox will still be checked in the html view. If I however click on the a-tag but not directly on the checkbox both the state showMap is updated correctly as well as the view.

I can make it work by not calling event.preventDefault(); in toggleCheckbox but if I do that the app will scroll to the top of the page if I click on the a-tag.

Example:

https://codesandbox.io/s/w2x8vqq8xl

Code:

import React from "react";
import { render } from "react-dom";

const styles = {
  fontFamily: "sans-serif",
  textAlign: "center",
  //marginTop: "1000px"
};

class Menu extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showMap: true
    };
  }

  toggleCheckbox = event => {
    this.setState({ showMap: !this.state.showMap });
    event.preventDefault();
  };

  render() {
    return (

{this.state.showMap ? "Show" : "hide"}

          <input
            type="checkbox"
            title="test"
            name="showMap"
            checked={this.state.showMap}
            readOnly
          />
          Show map

    );
  }
}

const App = () => (

      <Menu />

);

render(<App />, document.getElementById("root"));

Update:

Created an issue with React.

https://github.com/facebook/react/issues/11539


问:
Running a Linux command from R on Windows Server 2012

I have an R installation on Windows Server 2012, and I am trying to execute a command on a Linux Server - something like

bash echo \"samplecommand?filename=testfile.zip\" | nc -vv -w 2 testserver portnumber

As far as I understand, WSL exists from Windows 10 which makes it easy to execute linux bash scripts.

Is it possible to do this in R from Windows Server 2012 R2, or any other way to achieve this?

Thanks

答:
I think my question might have been worded incorrectly. The actual app I wanted to execute was netcat (nc), so all I needed to do was install netcat for windows and then execute </p>

```<code>input = "cd C:\\folderwherenetcatisinstalled
echo samplecommand?filename=testfilename| nc -w2 servername portnumber"
system("cmd.exe", input = input)
</code>```

Body:
I think my question might have been worded incorrectly. The actual app I wanted to execute was netcat (nc), so all I needed to do was install netcat for windows and then execute

input = "cd C:\\folderwherenetcatisinstalled
echo samplecommand?filename=testfilename| nc -w2 servername portnumber"
system("cmd.exe", input = input)


答:
Your method has a parameter so when your are call it you have to pass the arguments for parameter also </p>

```<code>List<Integer> intList = new ArrayList<>();

    avgFor(intList);
</code>```

Title: Java - How do I call this method from the main() method in Java

Body:
Your method has a parameter so when your are call it you have to pass the arguments for parameter also

List<Integer> intList = new ArrayList<>();

    avgFor(intList);


问:
How to remove index custom element in 2 dimensional array with empty value Javascript
Supposed I have 2 dimensional array in javascript and I want remove the empty element something like this [] in array, for example:

```<code>// like this
var newArray = [["test1", "test2"], ["test3", "test4"], []];

// or like this
var newArray= [["test1", "test2"], [], ["test3", "test4"]];
</code>```

and my code so far

```<code>var newArray= [["test1", "test2"], ["test3", "test4"], []];
for(var loop = 0; loop < newArray.length; loop++){
        if (newArray[loop] === null){
            // remove this empty element
            newArray[loop].slice();
        }
    }
console.log(newArray);
</code>```

And my output so far

```<code>[ [ 'test1', 'test2' ], [ 'test3', 'test4' ], [] ]
</code>```

How to remove that empty element? and when I print to the console the result that I want must:

```<code>[ [ 'test1', 'test2' ], [ 'test3', 'test4' ] ]
</code>```

Please help and thank you

答:
Try

```<code>array = array.filter(a => a && a.length !== 0);
</code>```

filter is one of the standard array functions provided by JavaScript. It is a higher order function that takes a predicate function which it applies to each element in the array. In this case we have an array of arrays so a is an array.

Body:
Supposed I have 2 dimensional array in javascript and I want remove the empty element something like this [] in array, for example:

// like this
var newArray = [["test1", "test2"], ["test3", "test4"], []];

// or like this
var newArray= [["test1", "test2"], [], ["test3", "test4"]];

and my code so far

var newArray= [["test1", "test2"], ["test3", "test4"], []];
for(var loop = 0; loop < newArray.length; loop++){
        if (newArray[loop] === null){
            // remove this empty element
            newArray[loop].slice();
        }
    }
console.log(newArray);

And my output so far

[ [ 'test1', 'test2' ], [ 'test3', 'test4' ], [] ]

How to remove that empty element? and when I print to the console the result that I want must:

[ [ 'test1', 'test2' ], [ 'test3', 'test4' ] ]

Please help and thank you

Body:
Try

array = array.filter(a => a && a.length !== 0);

filter is one of the standard array functions provided by JavaScript. It is a higher order function that takes a predicate function which it applies to each element in the array. In this case we have an array of arrays so a is an array.


问:
Django Rest Serializers: Return data of related field
I created models which are Contracts and ContractItems. ContractItems table contains a foreign key attribute of Contracts table. I need to return Contracts with their relevant ContractItems.

I implemented a serializer like it.

```<code>class ContractSerializer(ModelSerializer):
    class Meta:
        model = Contract
        fields = ('id', 'name')
</code>```

I could not get ContractItems to relevant Contract.

Could anyone suggest any way to get Contracts with their relevant ContractItems? And also One Contract can have many ContractItems.

答:
Maybe you try this too. You can get the related objects serialized too.

```<code>class ContractItemSerializer(ModelSerializer):
    class Meta:
        model = ContractItems
        exclude = ()
class ContractSerializer(ModelSerializer):
    contract_items  =  ContractItemSerializer(many=True, read_only=True)
    class Meta:
        model = Contract
        fields = ('id', 'name')
</code>```

Check this for reference: Example

Body:
I created models which are Contracts and ContractItems. ContractItems table contains a foreign key attribute of Contracts table. I need to return Contracts with their relevant ContractItems.

I implemented a serializer like it.

class ContractSerializer(ModelSerializer):
    class Meta:
        model = Contract
        fields = ('id', 'name')

I could not get ContractItems to relevant Contract.

Could anyone suggest any way to get Contracts with their relevant ContractItems? And also One Contract can have many ContractItems.

Body:
Maybe you try this too. You can get the related objects serialized too.

class ContractItemSerializer(ModelSerializer):
    class Meta:
        model = ContractItems
        exclude = ()
class ContractSerializer(ModelSerializer):
    contract_items  =  ContractItemSerializer(many=True, read_only=True)
    class Meta:
        model = Contract
        fields = ('id', 'name')

Check this for reference: Example


问:
how do you send email from R
I want to send emails from R. This is what I have so far:

```<code>library(sendmailR)

from <- "eamil@example.com"
to <- "email2@example.com"
subject <- "Performance Result"
body <- "This is the result of the test:"
mailControl=list(smtpServer="snmpt server address")

sendmail(from=from,to=to,subject=subject,msg=body,control=mailControl)
</code>```

When I execute this script, my R session hangs. Any ideas what might be happening?

答:
Sorry for bumping up this thread. If you want to send email from R using Microsoft outlook, below is the way to go using the RDCOMClient package. I myself spent a lot of time trying to find an answer on this. I thought it would be useful to have this solution too in this thread for users.

Full credit to @agstudy who provided the original solution in this link - Sending email in R via outlook

```<code>library (RDCOMClient)

OutApp <- COMCreate("Outlook.Application")
outMail = OutApp$CreateItem(0)
outMail[["To"]] = "test@test.com"
outMail[["subject"]] = "Test Subject"
outMail[["body"]] = "Body of email"
outMail$Send()
</code>```

Title: how do you send email from R

Body:
I want to send emails from R. This is what I have so far:

library(sendmailR)

from <- "eamil@example.com"
to <- "email2@example.com"
subject <- "Performance Result"
body <- "This is the result of the test:"
mailControl=list(smtpServer="snmpt server address")

sendmail(from=from,to=to,subject=subject,msg=body,control=mailControl)

When I execute this script, my R session hangs. Any ideas what might be happening?

Body:
Sorry for bumping up this thread. If you want to send email from R using Microsoft outlook, below is the way to go using the RDCOMClient package. I myself spent a lot of time trying to find an answer on this. I thought it would be useful to have this solution too in this thread for users.

Full credit to @agstudy who provided the original solution in this link - Sending email in R via outlook

library (RDCOMClient)

OutApp <- COMCreate("Outlook.Application")
outMail = OutApp$CreateItem(0)
outMail[["To"]] = "test@test.com"
outMail[["subject"]] = "Test Subject"
outMail[["body"]] = "Body of email"
outMail$Send()


问:
C: weird behavior when passing pointer to struct to function
Still need to get the hang of pointers in C so I wouldn't be surprised if this has a simple explanation...

I have code to perform matrix multiplication in C. To do this, I've defined a custom matrix struct which encodes the entire matrix in a row major 1D array to avoid passing double pointers:

```<code>typedef struct matrix matrix;

struct matrix {
  int n_rows;
  int n_cols;
  double *entries;
};
</code>```

The problem is when I pass a pointer to this matrix struct as an arg to my matrix multiply function.

```<code>matrix *matrix_mult(matrix *m, matrix *n){
    if (m->n_cols != n->n_rows){
        fprintf(stderr, "dimension mismatch\n");
        exit(1);
    } else {
        int rows = m->n_rows;
        int cols = n->n_cols;
        matrix *new = (matrix*)malloc(8+rows*cols*sizeof(double));
        new->n_rows = rows;
        new->n_cols = cols;

        new->entries = (double*)malloc(rows*cols*sizeof(double));

        for (int i = 0; i < rows*cols; i++) new->entries[i] = dot_prod( row_vec(m, i/cols), col_vec(n, i%cols) );
    }
    return new;
}
</code>```

Written this way, certain matrix elements get mysteriously zeroed out when the whole matrix is passed to matrix_mult! For instance, I have a 3x3 matrix *M whose entries are initialized as:

```<code>1.000000 0.000000 0.000000 0.250000 1.000000 0.000000 0.062500 0.500000 1.000000
</code>```

When I pass *M to matrix_mult and ask matrix_mult to printf the entries I find that they are now (this is before the matrix mult is ever performed):

```<code>1.000000 0.000000 0.000000 0.000000 1.000000 0.000000 0.062500 0.500000 0.000000
</code>```

However, when I modify matrix_mult as follows, explicitly defining a row and column vector to perform the dot product:

```<code>matrix *matrix_mult(matrix *m, matrix *n){
/* code */
    for (i = 0; i < rows*cols; i++){
        rv = row_vec(m, i/cols);
        cv = col_vec(n, i%cols);
        new->entries[i] = dot_prod( rv, cv );
        matrix_free(rv);
        matrix_free(cv);
    }
return new;
}
</code>```

Having matrix_mult printf the entries of M now gives:

```<code>1.000000 0.000000 0.000000 0.000000 1.000000 0.000000 0.062500 0.500000 1.000000
</code>```

Thus changing (seemingly unrelated) code has somehow modified the value of the matrix entries! Any clue what's going on?

EDIT:
The dot_prod function is as follows:

```<code>/* takes the dot product of a row vector with a column vector;
   returns error if args are not row or column vectors;
   or if the size of the vectors are not equal */
double dot_prod(matrix *rv, matrix *cv){
  if ((rv->n_rows != 1) || (cv->n_cols != 1)){
    fprintf(stderr, "arg(s) are not row or column vectors\n");
    exit(1);
  } else if (rv->n_cols != cv->n_rows){
    fprintf(stderr, "dimension mismatch\n");
    exit(2);
  } else {
    double n = 0;
    int l = rv->n_cols;
    for (int i = 0; i < l; i++) n += rv->entries[i]*cv->entries[i];
    return n;
  }
}
</code>```

答:
new is a bad name for pointer

the main difference between both examples is dot_prod(),on the second example you removed that and it works.
what is that function?

Body:
Still need to get the hang of pointers in C so I wouldn't be surprised if this has a simple explanation...

I have code to perform matrix multiplication in C. To do this, I've defined a custom matrix struct which encodes the entire matrix in a row major 1D array to avoid passing double pointers:

typedef struct matrix matrix;

struct matrix {
  int n_rows;
  int n_cols;
  double *entries;
};

The problem is when I pass a pointer to this matrix struct as an arg to my matrix multiply function.

matrix *matrix_mult(matrix *m, matrix *n){
    if (m->n_cols != n->n_rows){
        fprintf(stderr, "dimension mismatch\n");
        exit(1);
    } else {
        int rows = m->n_rows;
        int cols = n->n_cols;
        matrix *new = (matrix*)malloc(8+rows*cols*sizeof(double));
        new->n_rows = rows;
        new->n_cols = cols;

        new->entries = (double*)malloc(rows*cols*sizeof(double));

        for (int i = 0; i < rows*cols; i++) new->entries[i] = dot_prod( row_vec(m, i/cols), col_vec(n, i%cols) );
    }
    return new;
}

Written this way, certain matrix elements get mysteriously zeroed out when the whole matrix is passed to matrix_mult! For instance, I have a 3x3 matrix *M whose entries are initialized as:

1.000000 0.000000 0.000000 0.250000 1.000000 0.000000 0.062500 0.500000 1.000000

When I pass *M to matrix_mult and ask matrix_mult to printf the entries I find that they are now (this is before the matrix mult is ever performed):

1.000000 0.000000 0.000000 0.000000 1.000000 0.000000 0.062500 0.500000 0.000000

However, when I modify matrix_mult as follows, explicitly defining a row and column vector to perform the dot product:

matrix *matrix_mult(matrix *m, matrix *n){
/* code */
    for (i = 0; i < rows*cols; i++){
        rv = row_vec(m, i/cols);
        cv = col_vec(n, i%cols);
        new->entries[i] = dot_prod( rv, cv );
        matrix_free(rv);
        matrix_free(cv);
    }
return new;
}

Having matrix_mult printf the entries of M now gives:

1.000000 0.000000 0.000000 0.000000 1.000000 0.000000 0.062500 0.500000 1.000000

Thus changing (seemingly unrelated) code has somehow modified the value of the matrix entries! Any clue what's going on?

EDIT:
The dot_prod function is as follows:

/* takes the dot product of a row vector with a column vector;
   returns error if args are not row or column vectors;
   or if the size of the vectors are not equal */
double dot_prod(matrix *rv, matrix *cv){
  if ((rv->n_rows != 1) || (cv->n_cols != 1)){
    fprintf(stderr, "arg(s) are not row or column vectors\n");
    exit(1);
  } else if (rv->n_cols != cv->n_rows){
    fprintf(stderr, "dimension mismatch\n");
    exit(2);
  } else {
    double n = 0;
    int l = rv->n_cols;
    for (int i = 0; i < l; i++) n += rv->entries[i]*cv->entries[i];
    return n;
  }
}


问:
Alfresco association
I am trying to understand the Alfresco associations. I have understood the concept behind peer association as well as parent child association with examples.

I am referring their official docs example (peer association) : http://docs.alfresco.com/5.2/tasks/dev-extensions-content-models-tutorials-add-association.html

Screenshot :

Question: I am not following how mandatory and many parameters can be used within source? Most of examples, I have seen, those are set to same as target. Can anybody explain the use-case where I can set many is true in source and false in target with real use-case/example?

答:
There are many scenarios where many is false in source and true in target.You can check existing alfresco content model for same.Below is link for same.

https://github.com/Alfresco/community-edition-old/blob/master/projects/repository/config/alfresco/model/contentModel.xml

Apart from that regarding association , you ccan find more details on below link.

https://docs.alfresco.com/4.0/concepts/metadata-model-assoc.html

Title: Alfresco association


问:
Create string - all listed element for multiple fields grouping using MS Access SQL
For MSACCESS query, I have a table with 3 fields as following:

```<code>ID1 ID2 ID3
101 1001 1
102 1001 1
101 1002 1
102 1003 2
102 1004 3
103 1004 3
104 1004 4
</code>```

I would like to create a string with all recorded ID1 for each ID2, my desired output is following:

```<code>ID2 ID3 output
1001 1 101-102
1002 1 101
1003 2 102
1004 3 102-103
1004 4 104
</code>```

There are 2 possible ID1 value for ID2=1001, which is 101 and 102. Thus the desired string is 101-102 (assume no duplication by considering both fields ID1, ID2)

My attempt
Based on @Erik suggestion, i tried below while have error message on type mismatch.

```<code>Select T.[ID2] + T.[ID3]
  , GetList("Select [ID 1] From tblCEPAlert As T1 Where T1.[ID2] + T1.[ID3]  = " & T.[ID2] + T.[ID3],"",", ") as output
From tblCEPAlert AS T
Group By T.[ID2] + T.[ID3];
</code>```

答:
Please check following SQL Concatenation query where I used FOR XML PATH to concatenate strings

```<code>SELECT
    distinct
    i.ID2,
  STUFF(
    (
    SELECT
      '-' + convert(varchar(3),ID1)
    FROM IDs
    where ID2 = i.ID2
    FOR XML PATH(''),TYPE
    ).value('.','VARCHAR(MAX)'
    ), 1, 1, ''
  ) As IDList
  from IDs i
</code>```

using the following metadata

```<code>create table IDs (ID1 int, ID2 int)
insert into IDs select 101, 1001
insert into IDs select 102, 1001
insert into IDs select 101, 1002
insert into IDs select 102, 1003
insert into IDs select 102, 1004
insert into IDs select 103, 1004
insert into IDs select 104, 1004
</code>```

Output is as follows

Body:
For MSACCESS query, I have a table with 3 fields as following:

ID1 ID2 ID3
101 1001 1
102 1001 1
101 1002 1
102 1003 2
102 1004 3
103 1004 3
104 1004 4

I would like to create a string with all recorded ID1 for each ID2, my desired output is following:

ID2 ID3 output
1001 1 101-102
1002 1 101
1003 2 102
1004 3 102-103
1004 4 104

There are 2 possible ID1 value for ID2=1001, which is 101 and 102. Thus the desired string is 101-102 (assume no duplication by considering both fields ID1, ID2)

My attempt
Based on @Erik suggestion, i tried below while have error message on type mismatch.

Select T.[ID2] + T.[ID3]
  , GetList("Select [ID 1] From tblCEPAlert As T1 Where T1.[ID2] + T1.[ID3]  = " & T.[ID2] + T.[ID3],"",", ") as output
From tblCEPAlert AS T
Group By T.[ID2] + T.[ID3];

Body:
Please check following SQL Concatenation query where I used FOR XML PATH to concatenate strings

SELECT
    distinct
    i.ID2,
  STUFF(
    (
    SELECT
      '-' + convert(varchar(3),ID1)
    FROM IDs
    where ID2 = i.ID2
    FOR XML PATH(''),TYPE
    ).value('.','VARCHAR(MAX)'
    ), 1, 1, ''
  ) As IDList
  from IDs i

using the following metadata

create table IDs (ID1 int, ID2 int)
insert into IDs select 101, 1001
insert into IDs select 102, 1001
insert into IDs select 101, 1002
insert into IDs select 102, 1003
insert into IDs select 102, 1004
insert into IDs select 103, 1004
insert into IDs select 104, 1004

Output is as follows


答:
Move the list creation and population to the main method, then pass it in:

```<code>public static void main(String[] args) {
    List<Integer> list = new ArrayList<>(); // create the list
    list.add(10); // populate it
    list.add(20);
    list.add(30);
    list.add(40);
    list.add(50);
    list.add(60);

    avgFor(list); // pass the list to your method
}
</code>```

And remove the calls to add() from the avgFor() method:

```<code>static double avgFor(List<Integer> list) {
    int max = list.get(0);

    for (int i : list) {
        max = max < i ? max : i;
    }

    return max;
}
</code>```

Note that you've reinvented the wheel:

```<code>int max = Collections.max(list);
</code>```

Body:
I am still learning Java and would appreciate some assistance with this current problem: I am trying to call this static method from the main() method, however everything I try comes up with an error message. Thanks for any help.

This is my code:

public class Statistics {

    static double avgFor(List<Integer> list) {

        list.add(10);
        list.add(20);
        list.add(30);
        list.add(40);
        list.add(50);
        list.add(60);

        int max = list.get(0);

        for (int i : list) {
            max = max < i ? max : i;
        }

        return max;

    }

    public static void main(String[] args) {

        avgFor();

    }

}

Body:
Move the list creation and population to the main method, then pass it in:

public static void main(String[] args) {
    List<Integer> list = new ArrayList<>(); // create the list
    list.add(10); // populate it
    list.add(20);
    list.add(30);
    list.add(40);
    list.add(50);
    list.add(60);

    avgFor(list); // pass the list to your method
}

And remove the calls to add() from the avgFor() method:

static double avgFor(List<Integer> list) {
    int max = list.get(0);

    for (int i : list) {
        max = max < i ? max : i;
    }

    return max;
}

Note that you've reinvented the wheel:

int max = Collections.max(list);


问:
*ngIf Angular directive
I need to move a project out of angular, and thus need to change many of the directives i've been using. I was wondering if anyone knew what I could change the *ngIf directive to in plain javascript?

example:

```<code><li *ngIf="currentLanguage !== 'en'"><a onClick="changeLanguage('en') "hreflang="en"><img class="flag" src="assets/languages/en.png" alt="">{{'NAVIGATION_EN'|translate}}</a></li>
</code>```

答:
You can maybe target elements with *ngIf attribute :

```<code>let conditionals = document.querySelectorAll('[*ngIf]');
</code>```

And then loop on each, getting the condition, and display the element or not ?

```<code>for (conditional in conditionals) {
  condition = conditional.attr('*ngIf');
  if (!condition) {
    conditional.className += ' hidden';
  }
}
</code>```

I didn't test this code, but it looks like an good way to do it.

Title: *ngIf Angular directive

Body:
I need to move a project out of angular, and thus need to change many of the directives i've been using. I was wondering if anyone knew what I could change the *ngIf directive to in plain javascript?

example:

{{'NAVIGATION_EN'|translate}}

Body:
You can maybe target elements with *ngIf attribute :

let conditionals = document.querySelectorAll('[*ngIf]');

And then loop on each, getting the condition, and display the element or not ?

for (conditional in conditionals) {
  condition = conditional.attr('*ngIf');
  if (!condition) {
    conditional.className += ' hidden';
  }
}

I didn't test this code, but it looks like an good way to do it.


问:
Select rows which do not have duplicates
I have following SQL table:

```<code>+--------------+
| Account      |
+--------------+
|    11100011  |
|    11100012  |
|    11100013  |
|    11100014  |
|    11100011  |
|    11100012  |
|    11100015  |
+--------------+
</code>```

What I need is to make a select query with rows that do not have any duplicates in this table (i.e. removing both duplicated rows), so query result will look like this

```<code>+--------------+
| Account      |
+--------------+
|    11100013  |
|    11100014  |
|    11100015  |
+--------------+
</code>```

How can I do this in tsql?

答:
```<code>SELECT DISTINCT Account
FROM table_name_in_your_database;
</code>```

<p>General this query is used for selecting distinct elements in the table. </p>

Body:
I have following SQL table:

+--------------+
| Account      |
+--------------+
|    11100011  |
|    11100012  |
|    11100013  |
|    11100014  |
|    11100011  |
|    11100012  |
|    11100015  |
+--------------+

What I need is to make a select query with rows that do not have any duplicates in this table (i.e. removing both duplicated rows), so query result will look like this

+--------------+
| Account      |
+--------------+
|    11100013  |
|    11100014  |
|    11100015  |
+--------------+

How can I do this in tsql?

Body:
SELECT DISTINCT Account
FROM table_name_in_your_database;

General this query is used for selecting distinct elements in the table.


答:
A workaround can be:

```<code><li id="myId" class="hide"><a onClick="changeLanguage('en') "hreflang="en"><img class="flag" src="assets/languages/en.png" alt="">{{'NAVIGATION_EN'|translate}}</a></li>
</code>```

on css:

```<code>.hide{
  display: none;
}
</code>```

on JS:

```<code>var ele = document.getElementById('myId');
if(currentLanguage !== 'en'){
  ele.style.display = "block";
}
</code>```

Title: *ngIf Angular directive

Body:
A workaround can be:

<li id="myId" class="hide"><a onClick="changeLanguage('en') "hreflang="en"><img class="flag" src="assets/languages/en.png" alt="">{{'NAVIGATION_EN'|translate}}</a></li>

on css:

.hide{
  display: none;
}

on JS:

var ele = document.getElementById('myId');
if(currentLanguage !== 'en'){
  ele.style.display = "block";
}


问:
How to dynamically define this.state based on props in reactjs
My reactjs opinion poll currently has this code:

```<code>//App.js
import React, { Component } from 'react';
import './App.css';

const PollOption = ({options,selected, onChange}) => {
   return (
    <div className="pollOption">
      {options.map((choice, index) => (
        <label key={index}>
        <input type="radio"
                name="vote"
                value={choice.value}
                key={index}
                checked={selected === choice.value}
                onChange={onChange}/>
                {choice.text}
        </label>
      ))}
    </div>
   );
};

const VoteCount = ({totalVotes, choiceOneVotes, choiceTwoVotes}) =>{
  return(
      <div className="VoteCount">
          <h2>Total Votes {totalVotes}</h2>
          <ul>
            <li>Yes: {choiceOneVotes}</li>
            <li>No: {choiceTwoVotes}</li>
          </ul>
      </div>
  );
}

class OpinionPoll extends Component{
  constructor(props) {
    super(props);
    this.state = {selectedOption: '',
                  totalVotes: 0,
                  choiceOneVotes: 0,
                  choiceTwoVotes: 0}
  }

  handleClick(){
    console.log('submitted option', this.state.selectedOption);
    this.setState(prevState => {
      return {totalVotes: prevState.totalVotes + 1}
    })
   if(this.state.selectedOption === "yes"){
    this.setState(prevState => {
      return {choiceOneVotes: prevState.choiceOneVotes + 1}
    })
   }else{
    this.setState(prevState => {
      return {choiceTwoVotes: prevState.choiceTwoVotes + 1}
    })
   }
  }

  handleOnChange(e){
    console.log('selected option', e.target.name);
    this.setState({ selectedOption: e.target.value});
  }

  render(){
    return (
      <div className="poll">
        {this.props.model.question}
        <PollOption
          options={this.props.model.choices}
          onChange={(e) => this.handleOnChange(e)}
          selected={this.state.selectedOption}/>

        <button onClick={() => this.handleClick()}>Vote!</button>
        <VoteCount
          totalVotes={this.state.totalVotes}
          choiceOneVotes={this.state.choiceOneVotes}
          choiceTwoVotes={this.state.choiceTwoVotes}/>
      </div>
    );
  }
}

export default OpinionPoll;

//index.js
import React from 'react';
import {render} from 'react-dom';
import './index.css';
import OpinionPoll from './App';

var json = {
        question: 'Do you support cookies in cakes?',
        choices:
        [
           {text: "Yes", value: "yes"},
           {text: "No", value: "no"}
        ]
    }
const root = document.getElementById("root");
render(<OpinionPoll model ={json} />, root)
</code>```

My handleClick() and VoteCount component code feels inelegant since if I add the number of choices to the poll then I'd have to go and modify the state object and add another setState call. How can I make this dynamic?

答:
I guess this is what you are looking for.  If you add a new option then add the particular object to choices.</p>

```<code> handleClick(){
   const { selectedOption, choiceOneVotes, choiceTwoVotes, totalVotes  } = this.state
   const choices = {
     yes: { state: 'choiceOneVotes', value: choiceOneVotes },
     no : { state: 'choiceTwoVotes', value: choiceTwoVotes }
   }

   this.setState({
     totalVotes: totalVotes + 1,
     [choices[selectedOption]['state']]: choices[selectedOption]['value'] + 1
   });
 }
</code>```

Body:
My reactjs opinion poll currently has this code:

//App.js
import React, { Component } from 'react';
import './App.css';

const PollOption = ({options,selected, onChange}) => {
   return (

      {options.map((choice, index) => (

        <input type="radio"
                name="vote"
                value={choice.value}
                key={index}
                checked={selected === choice.value}
                onChange={onChange}/>
                {choice.text}

      ))}

   );
};

const VoteCount = ({totalVotes, choiceOneVotes, choiceTwoVotes}) =>{
  return(

Total Votes {totalVotes}

Yes: {choiceOneVotes}

No: {choiceTwoVotes}

  );
}

class OpinionPoll extends Component{
  constructor(props) {
    super(props);
    this.state = {selectedOption: '',
                  totalVotes: 0,
                  choiceOneVotes: 0,
                  choiceTwoVotes: 0}
  }

  handleClick(){
    console.log('submitted option', this.state.selectedOption);
    this.setState(prevState => {
      return {totalVotes: prevState.totalVotes + 1}
    })
   if(this.state.selectedOption === "yes"){
    this.setState(prevState => {
      return {choiceOneVotes: prevState.choiceOneVotes + 1}
    })
   }else{
    this.setState(prevState => {
      return {choiceTwoVotes: prevState.choiceTwoVotes + 1}
    })
   }
  }

  handleOnChange(e){
    console.log('selected option', e.target.name);
    this.setState({ selectedOption: e.target.value});
  }

  render(){
    return (

        {this.props.model.question}
        <PollOption
          options={this.props.model.choices}
          onChange={(e) => this.handleOnChange(e)}
          selected={this.state.selectedOption}/>

        <button onClick={() => this.handleClick()}>Vote!</button>
        <VoteCount
          totalVotes={this.state.totalVotes}
          choiceOneVotes={this.state.choiceOneVotes}
          choiceTwoVotes={this.state.choiceTwoVotes}/>

    );
  }
}

export default OpinionPoll;

//index.js
import React from 'react';
import {render} from 'react-dom';
import './index.css';
import OpinionPoll from './App';

var json = {
        question: 'Do you support cookies in cakes?',
        choices:
        [
           {text: "Yes", value: "yes"},
           {text: "No", value: "no"}
        ]
    }
const root = document.getElementById("root");
render(<OpinionPoll model ={json} />, root)

My handleClick() and VoteCount component code feels inelegant since if I add the number of choices to the poll then I'd have to go and modify the state object and add another setState call. How can I make this dynamic?

Body:
I guess this is what you are looking for.  If you add a new option then add the particular object to choices.

 handleClick(){
   const { selectedOption, choiceOneVotes, choiceTwoVotes, totalVotes  } = this.state
   const choices = {
     yes: { state: 'choiceOneVotes', value: choiceOneVotes },
     no : { state: 'choiceTwoVotes', value: choiceTwoVotes }
   }

   this.setState({
     totalVotes: totalVotes + 1,
     [choices[selectedOption]['state']]: choices[selectedOption]['value'] + 1
   });
 }


答:
```<code>select account
from
table
group by account
having count(*)=1
</code>```

Title: Select rows which do not have duplicates