问:
Module has no exported member 'IonicNativePlugin', Ionic2
I am trying to get camera, file, filepath and transfer plugin working and I am getting this error for each of these,

```<code>Module 'node_modules/@ionic-native/core/index' has no exported member 'IonicNativePlugin'
</code>```

I got the latest Ionic2 version.

package.json file as requested

```<code>"dependencies": {
"@angular/common": "4.0.0",
"@angular/compiler": "4.0.0",
"@angular/compiler-cli": "4.0.0",
"@angular/core": "4.0.0",
"@angular/forms": "4.0.0",
"@angular/http": "4.0.0",
"@angular/platform-browser": "4.0.0",
"@angular/platform-browser-dynamic": "4.0.0",
"@ionic-native/camera": "^3.6.0",
"@ionic-native/core": "3.4.2",
"@ionic-native/file": "^3.6.0",
"@ionic-native/file-path": "^3.6.0",
"@ionic-native/splash-screen": "3.4.2",
"@ionic-native/status-bar": "3.4.2",
"@ionic-native/transfer": "^3.6.0",
"@ionic/storage": "2.0.1",
"crypto-js": "3.1.9-1",
"fast-sha256": "1.0.0",
"ionic-angular": "3.0.1",
"ionic-native": "^3.5.0",
"ionicons": "3.0.0",
"rxjs": "5.1.1",
"sha256": "0.2.0",
"sw-toolbox": "3.4.0",
"ts-md5": "1.2.0",
"zone.js": "^0.8.4"

devDependencies": {
    "@ionic/app-scripts": "1.3.0",
    "typescript": "~2.2.1"

"cordovaPlugins": [
    "cordova-plugin-whitelist",
    "cordova-plugin-console",
    "cordova-plugin-statusbar",
    "cordova-plugin-device",
    "ionic-plugin-keyboard",
    "cordova-plugin-splashscreen"

"cordovaPlatforms": [],
  "description": "Work: An Ionic project"
</code>```

am I missing something?

答:
Try this:</p>

```<code>npm uninstall --save @ionic-native/core
npm install --save @ionic-native/core@latest
</code>```

Body:
I am trying to get camera, file, filepath and transfer plugin working and I am getting this error for each of these,

Module 'node_modules/@ionic-native/core/index' has no exported member 'IonicNativePlugin'

I got the latest Ionic2 version.

package.json file as requested

"dependencies": {
"@angular/common": "4.0.0",
"@angular/compiler": "4.0.0",
"@angular/compiler-cli": "4.0.0",
"@angular/core": "4.0.0",
"@angular/forms": "4.0.0",
"@angular/http": "4.0.0",
"@angular/platform-browser": "4.0.0",
"@angular/platform-browser-dynamic": "4.0.0",
"@ionic-native/camera": "^3.6.0",
"@ionic-native/core": "3.4.2",
"@ionic-native/file": "^3.6.0",
"@ionic-native/file-path": "^3.6.0",
"@ionic-native/splash-screen": "3.4.2",
"@ionic-native/status-bar": "3.4.2",
"@ionic-native/transfer": "^3.6.0",
"@ionic/storage": "2.0.1",
"crypto-js": "3.1.9-1",
"fast-sha256": "1.0.0",
"ionic-angular": "3.0.1",
"ionic-native": "^3.5.0",
"ionicons": "3.0.0",
"rxjs": "5.1.1",
"sha256": "0.2.0",
"sw-toolbox": "3.4.0",
"ts-md5": "1.2.0",
"zone.js": "^0.8.4"

devDependencies": {
    "@ionic/app-scripts": "1.3.0",
    "typescript": "~2.2.1"

"cordovaPlugins": [
    "cordova-plugin-whitelist",
    "cordova-plugin-console",
    "cordova-plugin-statusbar",
    "cordova-plugin-device",
    "ionic-plugin-keyboard",
    "cordova-plugin-splashscreen"

"cordovaPlatforms": [],
  "description": "Work: An Ionic project"

am I missing something?

Body:
Try this:

npm uninstall --save @ionic-native/core
npm install --save @ionic-native/core@latest


来源: stackexchange

问:
How to combine 2 Sinks of a different type?
I want to upload file into S3 using Alpakka and at the same time parse it with Tika to obtain its MimeType.

I have 3 parts of graph at the moment:

```<code>val fileSource: Source[ByteString, Any] // comes from Akka-HTTP
val fileUpload: Sink[ByteString, Future[MultipartUploadResult]] // created by S3Client from Alpakka
val mimeTypeDetection: Sink[ByteString, Future[MediaType.Binary]] // my implementation using Apache Tika
</code>```

I would like to obtain both results at one place, something like:

```<code>Future[(MultipartUploadResult, MediaType.Binary)]
</code>```

I have no issue with broadcasting part:

```<code>val broadcast = builder.add(Broadcast[ByteString](2))

source ~> broadcast ~> fileUpload
          broadcast ~> mimeTypeDetection
</code>```

However I have a trouble composing Sinks. Methods I found in API and documentation assumes that either combined sinks are of the same type or that I am Zipping Flows, not Sinks.

What is suggested approach in such case?

答:
Two ways:

1) using alsoToMat (easier, no GraphDSL, enough for your example)

```<code>  val mat1: (Future[MultipartUploadResult], Future[Binary]) =
    fileSource
    .alsoToMat(fileUpload)(Keep.right)
    .toMat(mimeTypeDetection)(Keep.both)
    .run()
</code>```

2) using GraphDSL with custom materialized values (more verbose, more flexible). More info on this in the docs)

```<code>  val mat2: (Future[MultipartUploadResult], Future[Binary]) =
    RunnableGraph.fromGraph(GraphDSL.create(fileUpload, mimeTypeDetection)((_, _)) { implicit builder =>
      (fileUpload, mimeTypeDetection) =>
        import GraphDSL.Implicits._
        val broadcast = builder.add(Broadcast[ByteString](2))

        fileSource ~> broadcast ~> fileUpload
                      broadcast ~> mimeTypeDetection
        ClosedShape
    }).run()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to upload file into S3 using Alpakka and at the same time parse it with Tika to obtain its MimeType.

I have 3 parts of graph at the moment:

val fileSource: Source[ByteString, Any] // comes from Akka-HTTP
val fileUpload: Sink[ByteString, Future[MultipartUploadResult]] // created by S3Client from Alpakka
val mimeTypeDetection: Sink[ByteString, Future[MediaType.Binary]] // my implementation using Apache Tika

I would like to obtain both results at one place, something like:

Future[(MultipartUploadResult, MediaType.Binary)]

I have no issue with broadcasting part:

val broadcast = builder.add(Broadcast[ByteString](2))

source ~> broadcast ~> fileUpload
          broadcast ~> mimeTypeDetection

However I have a trouble composing Sinks. Methods I found in API and documentation assumes that either combined sinks are of the same type or that I am Zipping Flows, not Sinks.

What is suggested approach in such case?

Body:
Two ways:

1) using alsoToMat (easier, no GraphDSL, enough for your example)

  val mat1: (Future[MultipartUploadResult], Future[Binary]) =
    fileSource
    .alsoToMat(fileUpload)(Keep.right)
    .toMat(mimeTypeDetection)(Keep.both)
    .run()

2) using GraphDSL with custom materialized values (more verbose, more flexible). More info on this in the docs)

  val mat2: (Future[MultipartUploadResult], Future[Binary]) =
    RunnableGraph.fromGraph(GraphDSL.create(fileUpload, mimeTypeDetection)((_, _)) { implicit builder =>
      (fileUpload, mimeTypeDetection) =>
        import GraphDSL.Implicits._
        val broadcast = builder.add(Broadcast[ByteString](2))

        fileSource ~> broadcast ~> fileUpload
                      broadcast ~> mimeTypeDetection
        ClosedShape
    }).run()


Title: Split a list of timestamps by intervals of 2 seconds in python

Body:
I have a list of timestamps all converted to integers. How can I split them into separate lists of 2-second intervals?

d = [1499256400, 1499256400, 1499256400, 1499256400, 1499256400, 1499256400, 1499256400, 1499256400, 1499256400, 1499256401, 1499256401, 1499256401, 1499256401, 1499256402, 1499256402, 1499256403, 1499256403, 1499256404, 1499256404, 1499256405, 1499256405, 1499256405, 1499256405, 1499256406, 1499256406, 1499256407, 1499256407, 1499256408, 1499256408, 1499256408, 1499256408, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409]

I would like to split them into intervals of 2 seconds so that I am able to print out the results of each interval.

Intended output:

[1499256400, 1499256400, 1499256400, 1499256400, 1499256400, 1499256400, 1499256400, 1499256400, 1499256400, 1499256401, 1499256401, 1499256401, 1499256401, 1499256402, 1499256402]
[1499256403, 1499256403, 1499256404, 1499256404, 1499256405, 1499256405, 1499256405, 1499256405]
[1499256406, 1499256406, 1499256407, 1499256407, 1499256408, 1499256408, 1499256408, 1499256408]
[1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409]

Thanks.

Body:
You can use a simple for loop to group items spanning a maximum difference of 2:

lst = [[]]
start = d[0]
for x in d:
    if x-start <= 2:
        lst[-1].append(x)
    else:
        lst.append([x])
        start = x

If the elements are not sorted, you can call sorted to do a presort before grouping.

For code reuse (imports and all that), you can create a grouper class and then use itertools.groupby for grouping:

from itertools import groupby

class Grouper(object):
    def __init__(self, start=None, diff=2):
        self.diff = diff
        self.start = start
        self._count = 0

    def __call__(self, x):
        if x-self.start > self.diff:
            self._count += 1
            self.start = x
        return self._count

And then the grouping is now simplified to:

lst = [list(g) for _, g in groupby(d, Grouper(start=d[0]))]

[[1499256400, 1499256400, 1499256400, 1499256400, 1499256400, 1499256400, 1499256400, 1499256400, 1499256400, 1499256401, 1499256401, 1499256401, 1499256401, 1499256402, 1499256402],
 [1499256403, 1499256403, 1499256404, 1499256404, 1499256405, 1499256405, 1499256405, 1499256405],
 [1499256406, 1499256406, 1499256407, 1499256407, 1499256408, 1499256408, 1499256408, 1499256408],
 [1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409]]


问:
Restore dump on the remote machine
I've got my own machine with postgres dmp file, which I want to restore on the remote virtual machine (e.g. ip is 192.168.0.190 and postgres port is 5432) in my network. Is it possible to restore this dump using pg_restore without copying dump to remote machine? Because the size of dump about 12GB and the disk space on the virtual machine is 20GB.
Thanks</p>

答:
Alternatively, you can use psql:

psql -h 192.168.0.190 -p 5432 -d <dbname> -U <username> -W -f mydump.dump

Title: Restore dump on the remote machine


问:
What is the difference between $a = $(Read-Host) and $a = (Read-Host)?
I have to review some scripts what my Ex-Colleague left behind and I am very curious why he is using $a = $(Read-Host -Prompt "Write something") in the Parameters section rather than $a = (Read-Host -Prompt "Write something").

I have tested it in a single script but haven't seen any difference so far.
I have searched thru the google and StackOverFlow but haven't find any clue so far what could be the difference.
Maybe my searching methods are bad.

答:
Quoting from Keith Hill's blog:

What’s the difference between grouping expressions (), subexpressions $() and array subexpressions @()?  A grouping expression can contain just a single statement.  A subexpression can contain multiple semicolon separated statements.  The output of each statement contributes to the output of the subexpression.  An array subexpression behaves just like a subexpression except that it guarantees that the output will be an array.  The two cases where this makes a difference are 1) there is no output at all so the result will be an empy array and 2) the result is a scalar value so the result will be a single element array containg the scalar value.  If the output is already an array then the use of an array subexpession will have no affect on the output i.e. array subexpressions do not wrap arrays inside of another array.

Silly example:

```<code>$a = (Read-Host -Prompt 'something'; echo 'foo')
$b = $(Read-Host -Prompt 'something'; echo 'foo')
</code>```

The first statement (with the grouping expression) will throw an error, because you cannot have multiple statements in a grouping expression. The second statement will work and append a line "foo" to the text entered via Read-Host.

In your example scenario ($a = (Read-Host -Prompt 'something') vs. $a = $(Read-Host -Prompt 'something')) it doesn't make any difference. More precisely, you shouldn't use either grouping expression or subexpression operator in that scenario, because they have no purpose there.

Body:
Quoting from Keith Hill's blog:

What’s the difference between grouping expressions (), subexpressions $() and array subexpressions @()?  A grouping expression can contain just a single statement.  A subexpression can contain multiple semicolon separated statements.  The output of each statement contributes to the output of the subexpression.  An array subexpression behaves just like a subexpression except that it guarantees that the output will be an array.  The two cases where this makes a difference are 1) there is no output at all so the result will be an empy array and 2) the result is a scalar value so the result will be a single element array containg the scalar value.  If the output is already an array then the use of an array subexpession will have no affect on the output i.e. array subexpressions do not wrap arrays inside of another array.

Silly example:

$a = (Read-Host -Prompt 'something'; echo 'foo')
$b = $(Read-Host -Prompt 'something'; echo 'foo')

The first statement (with the grouping expression) will throw an error, because you cannot have multiple statements in a grouping expression. The second statement will work and append a line "foo" to the text entered via Read-Host.

In your example scenario ($a = (Read-Host -Prompt 'something') vs. $a = $(Read-Host -Prompt 'something')) it doesn't make any difference. More precisely, you shouldn't use either grouping expression or subexpression operator in that scenario, because they have no purpose there.


问:
Swap rows with columns (transposition) of a matrix in javascript
For instance I have a matrix like this:

```<code>|1 2 3|
|4 5 6|
|7 8 9|
</code>```

and I need it to convert into a matrix like this:

```<code>|1 4 7|
|2 5 8|
|3 6 9|
</code>```

What is the best and optimal way to achieve this goal?

答:
See article: Transpose An Array In JavaScript and jQuery

function transpose(a) {

  // Calculate the width and height of the Array
  var w = a.length || 0;
  var h = a[0] instanceof Array ? a[0].length : 0;

  // In case it is a zero matrix, no transpose routine needed.
  if(h === 0 || w === 0) { return []; }

  /**
   * @var {Number} i Counter
   * @var {Number} j Counter
   * @var {Array} t Transposed data is stored in this array.
   */
  var i, j, t = [];

  // Loop through every item in the outer array (height)
  for(i=0; i<h; i++) {

    // Insert a new row (array)
    t[i] = [];

    // Loop through every item per item in outer array (width)
    for(j=0; j<w; j++) {

      // Save transposed data.
      t[i][j] = a[j][i];
    }
  }

  return t;
}

console.log(transpose([[1,2,3],[4,5,6],[7,8,9]]));```

Body:
For instance I have a matrix like this:

|1 2 3|
|4 5 6|
|7 8 9|

and I need it to convert into a matrix like this:

|1 4 7|
|2 5 8|
|3 6 9|

What is the best and optimal way to achieve this goal?


问:
retrieving number of observations with non missing values
I would like to compute the number of observations (Persons in my following example) that have non-missing values.

```<code>unbal <- data.frame(PERSON=c(rep('Frank',5),rep('Tony',5),rep('Edward',5)), YEAR=c(2001,2002,2003,2004,2005,2001,2002,2003,2004,2005,2001,2002,2003,2004,2005), Y=c(21,22,23,24,25,5,6,NA,7,8,31,32,33,34,35), X=c(1:15))
unbal

   PERSON YEAR  Y  X
1   Frank 2001 21  1
2   Frank 2002 22  2
3   Frank 2003 23  3
4   Frank 2004 24  4
5   Frank 2005 25  5
6    Tony 2001  5  6
7    Tony 2002  6  7
8    Tony 2003 NA  8
9    Tony 2004  7  9
10   Tony 2005  8 10
11 Edward 2001 31 11
12 Edward 2002 32 12
13 Edward 2003 33 13
14 Edward 2004 34 14
15 Edward 2005 35 15
</code>```

In this case will be 2, since only two persons (Frank and Edward) have all the data.

答:
We can use anyNA, which will can operate on data.frames together with by. Prepending the ! operator negates the results to return the desired values.

Using by,

```<code>!by(unbal, unbal["PERSON"], FUN=anyNA)
PERSON: Edward
[1] TRUE
----------------------------------------------------------------------------------
PERSON: Frank
[1] TRUE
----------------------------------------------------------------------------------
PERSON: Tony
[1] FALSE
</code>```

or to return a named vector, wrap it in c.

```<code>!c(by(unbal, unbal["PERSON"], FUN=anyNA))
Edward  Frank   Tony
  TRUE   TRUE  FALSE
</code>```

to calculate the number of persons with no missing values, wrap this in sum

```<code>sum(!c(by(unbal, unbal["PERSON"], FUN=anyNA)))
[1] 2
</code>```

A modification of sotos's method, we can use anyNA like this.

```<code>!sapply(split(unbal, unbal$PERSON), anyNA)
Edward  Frank   Tony
  TRUE   TRUE  FALSE
</code>```

Body:
I would like to compute the number of observations (Persons in my following example) that have non-missing values.

unbal <- data.frame(PERSON=c(rep('Frank',5),rep('Tony',5),rep('Edward',5)), YEAR=c(2001,2002,2003,2004,2005,2001,2002,2003,2004,2005,2001,2002,2003,2004,2005), Y=c(21,22,23,24,25,5,6,NA,7,8,31,32,33,34,35), X=c(1:15))
unbal

   PERSON YEAR  Y  X
1   Frank 2001 21  1
2   Frank 2002 22  2
3   Frank 2003 23  3
4   Frank 2004 24  4
5   Frank 2005 25  5
6    Tony 2001  5  6
7    Tony 2002  6  7
8    Tony 2003 NA  8
9    Tony 2004  7  9
10   Tony 2005  8 10
11 Edward 2001 31 11
12 Edward 2002 32 12
13 Edward 2003 33 13
14 Edward 2004 34 14
15 Edward 2005 35 15

In this case will be 2, since only two persons (Frank and Edward) have all the data.

Body:
We can use anyNA, which will can operate on data.frames together with by. Prepending the ! operator negates the results to return the desired values.

Using by,

!by(unbal, unbal["PERSON"], FUN=anyNA)
PERSON: Edward
[1] TRUE
----------------------------------------------------------------------------------
PERSON: Frank
[1] TRUE
----------------------------------------------------------------------------------
PERSON: Tony
[1] FALSE

or to return a named vector, wrap it in c.

!c(by(unbal, unbal["PERSON"], FUN=anyNA))
Edward  Frank   Tony
  TRUE   TRUE  FALSE

to calculate the number of persons with no missing values, wrap this in sum

sum(!c(by(unbal, unbal["PERSON"], FUN=anyNA)))
[1] 2

A modification of sotos's method, we can use anyNA like this.

!sapply(split(unbal, unbal$PERSON), anyNA)
Edward  Frank   Tony
  TRUE   TRUE  FALSE


问:
Hibernate Java Config Versus Xml
I am new to hibernate and I don't fully understand how to choose between java configuration and xml in hibernate config file? Tutorials that I have watched seem to be out of date. So my question is what is the best and most up to date way of configuring a model to hibernate.

The following is my current approach which seems to be the only one working for me:

```<code><hibernate-configuration>
<session-factory>

<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydatabase</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.pool_size">10</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL57InnoDBDialect</property>

<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.use_sql_comments">true</property>
<property name="hbm2ddl.auto">update</property>
<property name="current_session_context_class">thread</property>
<property name="hibernate.enable_lazy_load_no_trans">true</property>

<!-- <property name="hibernate.generate_statistics">true</property> -->
</code>```

I am configuring my model in a java file as shown below:

```<code>public class HibernateUtil {

private static SessionFactory sessionFactory = buildSessionFactory();

private static SessionFactory buildSessionFactory() {
    try {

        // Create your SessionFactory with mappings for every Entity in a specific package
        Configuration configuration = new Configuration();
        configuration.configure();
        configuration.addAnnotatedClass(PersonModel.class);

        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
        SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);

        //SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();

        return sessionFactory;

    } catch (Throwable ex) {
        // Make sure you log the exception, as it might be swallowed
        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}
</code>```

Is this the right way of doing it? or should it be done via XML file, if so can someone show me an example please?

Thanks in advance

答:
Look at the following docs for examples:

For annotation mapping:

https://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#entity-mapping

For xml mapping:

https://docs.jboss.org/hibernate/orm/3.3/reference/fr-FR/html/xml.html

Use of one of them it's up to you, for more details you can check this answer or this one

EDIT:  mapping example in hibernate configuration file

```<code><hibernate-configuration>
  <session-factory>
    <mapping package="test.animals"/>
    <mapping class="test.Flight"/>
    <mapping class="test.Sky"/>
    <mapping class="test.Person"/>
    <mapping class="test.animals.Dog"/>
    <mapping resource="test/animals/orm.xml"/>
  </session-factory>
</hibernate-configuration>
</code>```

Title: Hibernate Java Config Versus Xml

Body:
I am new to hibernate and I don't fully understand how to choose between java configuration and xml in hibernate config file? Tutorials that I have watched seem to be out of date. So my question is what is the best and most up to date way of configuring a model to hibernate.

The following is my current approach which seems to be the only one working for me:

<hibernate-configuration>
<session-factory>

<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydatabase</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.pool_size">10</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL57InnoDBDialect</property>

<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.use_sql_comments">true</property>
<property name="hbm2ddl.auto">update</property>
<property name="current_session_context_class">thread</property>
<property name="hibernate.enable_lazy_load_no_trans">true</property>

I am configuring my model in a java file as shown below:

public class HibernateUtil {

private static SessionFactory sessionFactory = buildSessionFactory();

private static SessionFactory buildSessionFactory() {
    try {

        // Create your SessionFactory with mappings for every Entity in a specific package
        Configuration configuration = new Configuration();
        configuration.configure();
        configuration.addAnnotatedClass(PersonModel.class);

        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
        SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);

        //SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();

        return sessionFactory;

    } catch (Throwable ex) {
        // Make sure you log the exception, as it might be swallowed
        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}

Is this the right way of doing it? or should it be done via XML file, if so can someone show me an example please?

Thanks in advance

Body:
Look at the following docs for examples:

For annotation mapping:

https://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#entity-mapping

For xml mapping:

https://docs.jboss.org/hibernate/orm/3.3/reference/fr-FR/html/xml.html

Use of one of them it's up to you, for more details you can check this answer or this one

EDIT:  mapping example in hibernate configuration file

<hibernate-configuration>
  <session-factory>
    <mapping package="test.animals"/>
    <mapping class="test.Flight"/>
    <mapping class="test.Sky"/>
    <mapping class="test.Person"/>
    <mapping class="test.animals.Dog"/>
    <mapping resource="test/animals/orm.xml"/>
  </session-factory>
</hibernate-configuration>


问:
ionic3 @ionic-native/camera don't show the picture
the camera works  but it's not showing the picture. I've followed some solutions but nothign seems work,
maybe is the ionic3 version?

Before i was able to take a picture,  now button launch on debug chrome 'Illegal Argument Exception'

UPDATE: The problem was when telephone is connect in mode USB, and
  debug mode, the sd card is not enable to save pictures.  So when you
  run:

ionic cordova run android

you must turn off the mode Debug

I can't solve to show  the picture,

here the files:

photo.ts

```<code>import { Component } from '@angular/core';
import { NavController, ToastController } from 'ionic-angular';
import { MainPage } from '../../pages/pages';
import { Vibration } from '@ionic-native/vibration';
import { AuthenticationService } from '../../providers/authentication.service';
import { Camera, CameraOptions } from '@ionic-native/camera';

import { TranslateService } from '@ngx-translate/core';

import {Observable} from 'rxjs/Rx';
@Component({
  selector: 'page-photo',
  templateUrl: 'photo.html'
})
export class PhotoPage {

  // imageData is a base64 encoded string
  public base64Image: string;

  constructor(public navCtrl: NavController,
    public toastCtrl: ToastController,
    private camera: Camera

  ) {

  }

  ngOnInit() {
  }

  takePicture(){
    let options = {
      quality: 100,
      destinationType: this.camera.DestinationType.DATA_URL,
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE
    };
    this.camera.getPicture(options)
      .then((imageData)=>{
        this.base64Image = "data:image/jpeg;base64," + imageData;

        let cameraImageSelector = document.getElementById('camera-image');
        cameraImageSelector.setAttribute('src', this.base64Image);

      })
      .catch(err=>{
        console.log(err);
      })
  }
}
</code>```

this is another file:
photo.html

```<code><ion-header>

  <ion-navbar>
    <ion-title>Photo</ion-title>
  </ion-navbar>

</ion-header>

<ion-content>

  <img [src]="base64Image" *ngIf="base64Image" />

  <ion-fab bottom right>
    <button ion-fab color="secondary" (click)="takePicture()"><ion-icon name="camera"></ion-icon></button>
  </ion-fab>
</ion-content>
</code>```

this is another file:

app.module.ts

```<code>...import { Camera } from '@ionic-native/camera';
...
@NgModule({
  ...
  providers: [
  ..
    Camera
</code>```

答:
I had similar issue. Below is my code . Hope it helps you

      Camera app

```<code>  <button (click)="takePicture()">Take a Picture</button>

  Latest Picture:
  <img [src]="base64Image" *ngIf="base64Image" />
</ion-card-content>
</code>```

Options:

```<code>const options: CameraOptions = {
     targetWidth: 300,
     targetHeight: 300,
     quality: 100,
     destinationType: this.camera.DestinationType.DATA_URL,
     encodingType: this.camera.EncodingType.JPEG,
     mediaType: this.camera.MediaType.PICTURE
}
</code>```

Body:
the camera works  but it's not showing the picture. I've followed some solutions but nothign seems work,
maybe is the ionic3 version?

Before i was able to take a picture,  now button launch on debug chrome 'Illegal Argument Exception'

UPDATE: The problem was when telephone is connect in mode USB, and
  debug mode, the sd card is not enable to save pictures.  So when you
  run:

ionic cordova run android

you must turn off the mode Debug

I can't solve to show  the picture,

here the files:

photo.ts

import { Component } from '@angular/core';
import { NavController, ToastController } from 'ionic-angular';
import { MainPage } from '../../pages/pages';
import { Vibration } from '@ionic-native/vibration';
import { AuthenticationService } from '../../providers/authentication.service';
import { Camera, CameraOptions } from '@ionic-native/camera';

import { TranslateService } from '@ngx-translate/core';

import {Observable} from 'rxjs/Rx';
@Component({
  selector: 'page-photo',
  templateUrl: 'photo.html'
})
export class PhotoPage {

  // imageData is a base64 encoded string
  public base64Image: string;

  constructor(public navCtrl: NavController,
    public toastCtrl: ToastController,
    private camera: Camera

  ) {

  }

  ngOnInit() {
  }

  takePicture(){
    let options = {
      quality: 100,
      destinationType: this.camera.DestinationType.DATA_URL,
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE
    };
    this.camera.getPicture(options)
      .then((imageData)=>{
        this.base64Image = "data:image/jpeg;base64," + imageData;

        let cameraImageSelector = document.getElementById('camera-image');
        cameraImageSelector.setAttribute('src', this.base64Image);

      })
      .catch(err=>{
        console.log(err);
      })
  }
}

this is another file:
photo.html

<ion-header>

  <ion-navbar>
    <ion-title>Photo</ion-title>
  </ion-navbar>

</ion-header>

<ion-content>

  <ion-fab bottom right>
    <button ion-fab color="secondary" (click)="takePicture()"><ion-icon name="camera"></ion-icon></button>
  </ion-fab>
</ion-content>

this is another file:

app.module.ts

...import { Camera } from '@ionic-native/camera';
...
@NgModule({
  ...
  providers: [
  ..
    Camera

Body:
I had similar issue. Below is my code . Hope it helps you

      Camera app

  <button (click)="takePicture()">Take a Picture</button>

  Latest Picture:
  <img [src]="base64Image" *ngIf="base64Image" />
</ion-card-content>

Options:

const options: CameraOptions = {
     targetWidth: 300,
     targetHeight: 300,
     quality: 100,
     destinationType: this.camera.DestinationType.DATA_URL,
     encodingType: this.camera.EncodingType.JPEG,
     mediaType: this.camera.MediaType.PICTURE
}

ContentLicense: CC BY-SA 4.0


问:
How to get integer values from array based on first digits java
I have int number value and int[] numberArray.

I want to get all values from numberArray that starts with number.

What I am trying to do is

```<code>for (int i=0;i<numbers.length;i++){
    if(numberArray[i] "starts with" number){
        System.out.print(numberArray[i]);
     }
}
</code>```

I also need to use 2 and 3 digit numbers.

Could you help me find a solution for that?

EDIT: Thanks for help, found a solution. At the end code look like that:

```<code>String num = String.valueOf(number);
for (int i =0; i< numberArray.size();i++) {
    String anumber = String.valueOf(numberArray[i]);
    if (anumber.startsWith(num)){
        System.out.print(numberArray[i])
    }
}
</code>```

答:
A method using streams :

So the method  :

creates a Stream from the array,

converts the int to String

to use the startsWith method by filtering and keeping only the element which match,

come back to int

return a List which contains theses values

```<code>public static List<Integer> intStartWidth(int[] values, int start) {
    return Arrays.stream(values)                 //Stream over the array
                 .mapToObj(Integer::toString)    //converts to String
                 .filter(element -> element.startsWith(Integer.toString(start)))  //keep only ones which match
                 .map(Integer::valueOf)          //converts to int
                 .collect(Collectors.toList());  //assembly on a List
 }

//--------------------------------------------------------------------------------

public static void main(String[] args) {
    int[] tab = new int[]{496781, 49872, 3, 49, 76};
    int start = 49;

    List<Integer> result = intStartWidth(tab, start);
    result.forEach(System.out::println);
}
</code>```

Here how to use it, get an array, a int, call the method and then print all to check if it works

It's clearly easier than iterate by hand over digits or and check each one, here is only existing method

Body:
I have int number value and int[] numberArray.

I want to get all values from numberArray that starts with number.

What I am trying to do is

for (int i=0;i<numbers.length;i++){
    if(numberArray[i] "starts with" number){
        System.out.print(numberArray[i]);
     }
}

I also need to use 2 and 3 digit numbers.

Could you help me find a solution for that?

EDIT: Thanks for help, found a solution. At the end code look like that:

String num = String.valueOf(number);
for (int i =0; i< numberArray.size();i++) {
    String anumber = String.valueOf(numberArray[i]);
    if (anumber.startsWith(num)){
        System.out.print(numberArray[i])
    }
}

Body:
A method using streams :

So the method  :

creates a Stream from the array,

converts the int to String

to use the startsWith method by filtering and keeping only the element which match,

come back to int

return a List which contains theses values

public static List<Integer> intStartWidth(int[] values, int start) {
    return Arrays.stream(values)                 //Stream over the array
                 .mapToObj(Integer::toString)    //converts to String
                 .filter(element -> element.startsWith(Integer.toString(start)))  //keep only ones which match
                 .map(Integer::valueOf)          //converts to int
                 .collect(Collectors.toList());  //assembly on a List
 }

//--------------------------------------------------------------------------------

public static void main(String[] args) {
    int[] tab = new int[]{496781, 49872, 3, 49, 76};
    int start = 49;

    List<Integer> result = intStartWidth(tab, start);
    result.forEach(System.out::println);
}

Here how to use it, get an array, a int, call the method and then print all to check if it works

It's clearly easier than iterate by hand over digits or and check each one, here is only existing method


问:
JSON format with index error
Error: Parse error on line 1:
{"Index":{"_id":1}}
{   "altitde": 11887.1,
"callsign": "ABX2040 ",
----------------------^
Expecting 'EOF', '}', ',', ']', got '{'</p>

答:
This piece of text: {"Index":{"_id":1}} is a complete JSON object. After the last "}" your parser is expecting the end of the file, but you are adding a new object, starting with a new "{"

Check http://www.json.org/ to see how correct JSON must be conformed

Title: JSON format with index error


问:
flexbox and google pagespeed insights image optimization have conflicts?
I tried to optimized images on page https://terma-pl.com.ua/polotentsesushiteli-v-vannuyu using page speed insights, currently there are 3 images that mast be optimized. but google provides some strange images. They change their form after optimization, even if i set image width and height atributes and styles... If i remove flex from parent block, google provides normal images, what issue is this?

Fo example in flex block i have a p and img:

```<code><div class="flexBlock">
<p>...</p>
<img src="/images/001Polotencesysh/colori-ral.jpg" width="250" height="250"
style="width: 250px; height:250px; flex-basis: 250px;">
</div>

.flexBlock {
display: flex;
align-items: center;
}
</code>```

The image before and after compression:

答:
An initial setting on flex items is flex-shrink: 1. This means that items are permitted to shrink.

To disable this feature, add flex-shrink: 0 to your inline style.

Body:
I tried to optimized images on page https://terma-pl.com.ua/polotentsesushiteli-v-vannuyu using page speed insights, currently there are 3 images that mast be optimized. but google provides some strange images. They change their form after optimization, even if i set image width and height atributes and styles... If i remove flex from parent block, google provides normal images, what issue is this?

Fo example in flex block i have a p and img:

...

.flexBlock {
display: flex;
align-items: center;
}

The image before and after compression:


问:
Trying to setup first app, but website not playing ball
I'm trying to setup Crashlytics on an existing Android app, which currently uses Firebase, but I'm having problems getting to certain parts of the site.

Going from the documentation page:
https://docs.fabric.io/android/fabric/settings/app.html

I click on the "settings" hyperlinks, and instead of taking me through to an organisation settings page, I'm directed to the Crashlytics Summary page: https://fabric.io/kits/android/crashlytics/summary

The problem is that I want to setup a new API Key, and the sample code has A key in it, but not MY key (because I haven't been able to generate one).

How am I able to create a new app and API Key for Crashlytics?

Any help in this direction would be greatly appreciated!

Thanks,
Phil

答: Mike from Fabric here. If you're logged in at https://fabric.io/kits/android/crashlytics/summary, then the API key present is your actual API key, not a sample key. If you've created a new organization and need to change the organization to get a different key, you can select that here.


问:
Cron job to invoke HTTP restful api
I am using J2EE with Jboss server. I am trying to finding a way to invoke sendEmail api in my code every month.

```<code>@GET
@Path("/sendEmail")
@Transactional
public String test(){
</code>```

I want to invoke this test api which can be accessed using web-browser http://localhost:8181/api/calc/sendEmail

I found some ways to do this:
https://cloud.google.com/appengine/docs/java/config/cron
https://www.mkyong.com/java/how-to-run-a-task-periodically-in-java/

Using cron job looks intuitive way to do this but I find it difficult to search resources to find a way to schedule invoking of the APIs using it.

Please point me to some resources where I can find a way to do so by just adding single dependency for this purpose in pom.xml

答:
When the application is deployed in multiple boxes or multiple pods(in case of kubernetes) then in each pods the cron expression gets set.

This results in the cron getting triggered n(number of pods) times which results in error case. Better option is to call the cron from external monolith configuration systems by calling through an api.

Applying on a method with the annotation is apt if application runs in only one box(pure monolith).

Title: Cron job to invoke HTTP restful api

Body:
I am using J2EE with Jboss server. I am trying to finding a way to invoke sendEmail api in my code every month.

@GET
@Path("/sendEmail")
@Transactional
public String test(){

I want to invoke this test api which can be accessed using web-browser http://localhost:8181/api/calc/sendEmail

I found some ways to do this:
https://cloud.google.com/appengine/docs/java/config/cron
https://www.mkyong.com/java/how-to-run-a-task-periodically-in-java/

Using cron job looks intuitive way to do this but I find it difficult to search resources to find a way to schedule invoking of the APIs using it.

Please point me to some resources where I can find a way to do so by just adding single dependency for this purpose in pom.xml


问:
How to add subarrays to itself? Ruby
I have an array containing of subarrays like this:

```<code>arr = [[{"big" => "2055", "small" => -"-10", "thin" => "i"},
        {"big" => "2785", "small" => "0", "thin" => "l"}],
       [{"big" => "7890", "small" => "3", "thin" => "t"},
        {"big" => "2669", "small" => "0,5", "thin" => "f"},
        {"big" => "9000", "small" => "2", "fat" => "O"}]]
</code>```

I want to add subarrays to itself to get an array like this:

```<code>arr = [{"big" => "2055", "small" => "-10", "thin" => "i"},
       {"big" => "2785", "small" => "0", "thin" => "l"},
       {"big" => "7890", "small" => "3", "thin" => "t"},
       {"big" => "2669", "small" => "0,5", "thin" => "f"},
       {"big" => "9000", "small" => "2", "fat" => "O"}]
</code>```

Doing like this:

```<code>arr.map! {|x| x+x}
</code>```

I get added subarrays but every hash appears twice. How to do it right?

答:
Do you just want to flatten the array?

```<code>arr.flatten
</code>```

It concatenates every sub-array into one big array, recursively if needed.

```<code>[[1,2], [3,4]].flatten
# => [1, 2, 3, 4]
</code>```

If you want to modify the array in place, you can use :

```<code>arr.flatten!
</code>```

It doesn't matter what the inner-elements look like (integers, strings, hashes), as long as they're not arrays, they won't be touched by flatten.

Title: How to add subarrays to itself? Ruby

Body:
I have an array containing of subarrays like this:

arr = [[{"big" => "2055", "small" => -"-10", "thin" => "i"},
        {"big" => "2785", "small" => "0", "thin" => "l"}],
       [{"big" => "7890", "small" => "3", "thin" => "t"},
        {"big" => "2669", "small" => "0,5", "thin" => "f"},
        {"big" => "9000", "small" => "2", "fat" => "O"}]]

I want to add subarrays to itself to get an array like this:

arr = [{"big" => "2055", "small" => "-10", "thin" => "i"},
       {"big" => "2785", "small" => "0", "thin" => "l"},
       {"big" => "7890", "small" => "3", "thin" => "t"},
       {"big" => "2669", "small" => "0,5", "thin" => "f"},
       {"big" => "9000", "small" => "2", "fat" => "O"}]

Doing like this:

arr.map! {|x| x+x}

I get added subarrays but every hash appears twice. How to do it right?

Body:
Do you just want to flatten the array?

arr.flatten

It concatenates every sub-array into one big array, recursively if needed.

[[1,2], [3,4]].flatten
# => [1, 2, 3, 4]

If you want to modify the array in place, you can use :

arr.flatten!

It doesn't matter what the inner-elements look like (integers, strings, hashes), as long as they're not arrays, they won't be touched by flatten.


答: Ruby have a built in method try use Array.flatten</p>

Title: How to add subarrays to itself? Ruby


问:
Mounting NFS volume in Google Container Engine with Container OS (COS)
After migrating the image type from container-vm to cos for the nodes of a GKE cluster, it seems no longer possible to mount a NFS volume for a pod.

The problem seems to be missing NFS client libraries, as a mount command from command line fails on all COS versions I tried (cos-stable-58-9334-62-0, cos-beta-59-9460-20-0, cos-dev-60-9540-0-0).

```<code>sudo mount -t nfs mynfsserver:/myshare /mnt
</code>```

fails with

```<code>mount: wrong fs type, bad option, bad superblock on mynfsserver:/myshare,
       missing codepage or helper program, or other error
       (for several filesystems (e.g. nfs, cifs) you might
       need a /sbin/mount.<type> helper program)
</code>```

But this contradicts the supported volume types listed here:
https://cloud.google.com/container-engine/docs/node-image-migration#storage_driver_support

Mounting a NFS volume in a pod works in a pool with image-type container-vm but not with cos.

With cos I get following messages with kubectl describe pod:

```<code>MountVolume.SetUp failed for volume "kubernetes.io/nfs/b6e6cf44-41e7-11e7-8b00-42010a840079-nfs-mandant1" (spec.Name: "nfs-mandant1") pod "b6e6cf44-41e7-11e7-8b00-42010a840079" (UID: "b6e6cf44-41e7-11e7-8b00-42010a840079") with: mount failed: exit status 1
Mounting command: /home/kubernetes/containerized_mounter/mounter
Mounting arguments: singlefs-1-vm:/data/mandant1 /var/lib/kubelet/pods/b6e6cf44-41e7-11e7-8b00-42010a840079/volumes/kubernetes.io~nfs/nfs-mandant1 nfs []
Output: Mount failed: Mount failed: exit status 32
Mounting command: chroot
Mounting arguments: [/home/kubernetes/containerized_mounter/rootfs mount -t nfs singlefs-1-vm:/data/mandant1 /var/lib/kubelet/pods/b6e6cf44-41e7-11e7-8b00-42010a840079/volumes/kubernetes.io~nfs/nfs-mandant1]
Output: mount.nfs: Failed to resolve server singlefs-1-vm: Temporary failure in name resolution
</code>```

答:
I've nicked the solution @saad-ali mentioned above, from the kubernetes project, to make this work.

To be concrete, I've added the following to my cloud-config:

```<code># This script creates a chroot environment containing the tools needed to mount an nfs drive
- path: /tmp/mount_config.sh
  permissions: 0755
  owner: root
  content: |
    #!/bin/sh
    set +x # For debugging

    export USER=root
    export HOME=/home/dockerrunner
    mkdir -p /tmp/mount_chroot
    chmod a+x /tmp/mount_chroot
    cd /tmp/
    echo "Sleeping for 30 seconds because toolbox pull fails otherwise"
    sleep 30
    toolbox --bind /tmp /google-cloud-sdk/bin/gsutil cp gs://<uploaded-file-bucket>/mounter.tar /tmp/mounter.tar
    tar xf /tmp/mounter.tar -C /tmp/mount_chroot/
    mount --bind /tmp/mount_chroot /tmp/mount_chroot
    mount -o remount, exec /tmp/mount_chroot
    mount --rbind /proc /tmp/mount_chroot/proc
    mount --rbind /dev /tmp/mount_chroot/dev
    mount --rbind /tmp /tmp/mount_chroot/tmp
    mount --rbind /mnt /tmp/mount_chroot/mnt
</code>```

The uploaded-file-bucket container the chroom image the kube team has created, downloaded from: https://storage.googleapis.com/kubernetes-release/gci-mounter/mounter.tar

Then, the runcmd for the cloud-config looks something like:

```<code>runcmd:
- /tmp/mount_config.sh
- mkdir -p /mnt/disks/nfs_mount
- chroot /tmp/mount_chroot /bin/mount -t nfs -o rw nfsserver:/sftp /mnt/disks/nfs_mount
</code>```

This works. Ugly as hell, but it'll have to do for now.

Body:
After migrating the image type from container-vm to cos for the nodes of a GKE cluster, it seems no longer possible to mount a NFS volume for a pod.

The problem seems to be missing NFS client libraries, as a mount command from command line fails on all COS versions I tried (cos-stable-58-9334-62-0, cos-beta-59-9460-20-0, cos-dev-60-9540-0-0).

sudo mount -t nfs mynfsserver:/myshare /mnt

fails with

mount: wrong fs type, bad option, bad superblock on mynfsserver:/myshare,
       missing codepage or helper program, or other error
       (for several filesystems (e.g. nfs, cifs) you might
       need a /sbin/mount.<type> helper program)

But this contradicts the supported volume types listed here:
https://cloud.google.com/container-engine/docs/node-image-migration#storage_driver_support

Mounting a NFS volume in a pod works in a pool with image-type container-vm but not with cos.

With cos I get following messages with kubectl describe pod:

MountVolume.SetUp failed for volume "kubernetes.io/nfs/b6e6cf44-41e7-11e7-8b00-42010a840079-nfs-mandant1" (spec.Name: "nfs-mandant1") pod "b6e6cf44-41e7-11e7-8b00-42010a840079" (UID: "b6e6cf44-41e7-11e7-8b00-42010a840079") with: mount failed: exit status 1
Mounting command: /home/kubernetes/containerized_mounter/mounter
Mounting arguments: singlefs-1-vm:/data/mandant1 /var/lib/kubelet/pods/b6e6cf44-41e7-11e7-8b00-42010a840079/volumes/kubernetes.io~nfs/nfs-mandant1 nfs []
Output: Mount failed: Mount failed: exit status 32
Mounting command: chroot
Mounting arguments: [/home/kubernetes/containerized_mounter/rootfs mount -t nfs singlefs-1-vm:/data/mandant1 /var/lib/kubelet/pods/b6e6cf44-41e7-11e7-8b00-42010a840079/volumes/kubernetes.io~nfs/nfs-mandant1]
Output: mount.nfs: Failed to resolve server singlefs-1-vm: Temporary failure in name resolution

Body:
I've nicked the solution @saad-ali mentioned above, from the kubernetes project, to make this work.

To be concrete, I've added the following to my cloud-config:

# This script creates a chroot environment containing the tools needed to mount an nfs drive
- path: /tmp/mount_config.sh
  permissions: 0755
  owner: root
  content: |
    #!/bin/sh
    set +x # For debugging

    export USER=root
    export HOME=/home/dockerrunner
    mkdir -p /tmp/mount_chroot
    chmod a+x /tmp/mount_chroot
    cd /tmp/
    echo "Sleeping for 30 seconds because toolbox pull fails otherwise"
    sleep 30
    toolbox --bind /tmp /google-cloud-sdk/bin/gsutil cp gs://<uploaded-file-bucket>/mounter.tar /tmp/mounter.tar
    tar xf /tmp/mounter.tar -C /tmp/mount_chroot/
    mount --bind /tmp/mount_chroot /tmp/mount_chroot
    mount -o remount, exec /tmp/mount_chroot
    mount --rbind /proc /tmp/mount_chroot/proc
    mount --rbind /dev /tmp/mount_chroot/dev
    mount --rbind /tmp /tmp/mount_chroot/tmp
    mount --rbind /mnt /tmp/mount_chroot/mnt

The uploaded-file-bucket container the chroom image the kube team has created, downloaded from: https://storage.googleapis.com/kubernetes-release/gci-mounter/mounter.tar

Then, the runcmd for the cloud-config looks something like:

runcmd:
- /tmp/mount_config.sh
- mkdir -p /mnt/disks/nfs_mount
- chroot /tmp/mount_chroot /bin/mount -t nfs -o rw nfsserver:/sftp /mnt/disks/nfs_mount

This works. Ugly as hell, but it'll have to do for now.


Title: How to add subarrays to itself? Ruby

Body:
You can use flatten!:

arr.flatten!

#=> [{"big"=>"2055", "small"=>"-10", "thin"=>"i"},
     {"big"=>"2785", "small"=>"0", "thin"=>"l"},
     {"big"=>"7890", "small"=>"3", "thin"=>"t"},
     {"big"=>"2669", "small"=>"0,5", "thin"=>"f"},
     {"big"=>"9000", "small"=>"2", "fat"=>"O"}]


问:
Java: Pattern behaves differently in Scanner
Came across a strange behavior of regex matching in Java. The first output command prints true as expected, but when the same string is packed into Scanner, the output is false. What am I doing wrong?

```<code>public static void main(String[] args) {
  Pattern p = Pattern.compile(" *\\[");
  System.out.println(p.asPredicate().test("[]")); //true

  Scanner s = new Scanner("[]");
  System.out.println(s.hasNext(" *\\[")); //false
}
</code>```

答:
From public boolean hasNext(String pattern) documentation:

Returns true if the next token matches the pattern constructed from the specified string.

Here next token is [] not just [ (since delimiter is one or more whitespace) but " *\\[" pattern doesn't match that token entirely (] is not matched) so you are informed about it by result false.

If you want to check if token starts with [ you can add .* at the end of your pattern to let it match rest of token. You can also remove * since whitespace is default delimiter so it can't be part of token.

In case of

```<code>Pattern p = Pattern.compile(" *\\[");
System.out.println(p.asPredicate().test("a[]")); //true
</code>```

If you take a look at code of asPredicate you will see it is implemented as:

```<code>public Predicate<String> asPredicate() {
    return s -> matcher(s).find();
}
</code>```

find() method doesn't check if whole string matches pattern, but tries to find even part of it which matches pattern. Since [] contains zero or more spaces followed by [ you are seeing true as result.

Body:
Came across a strange behavior of regex matching in Java. The first output command prints true as expected, but when the same string is packed into Scanner, the output is false. What am I doing wrong?

public static void main(String[] args) {
  Pattern p = Pattern.compile(" *\\[");
  System.out.println(p.asPredicate().test("[]")); //true

  Scanner s = new Scanner("[]");
  System.out.println(s.hasNext(" *\\[")); //false
}

Body:
From public boolean hasNext(String pattern) documentation:

Returns true if the next token matches the pattern constructed from the specified string.

Here next token is [] not just [ (since delimiter is one or more whitespace) but " *\\[" pattern doesn't match that token entirely (] is not matched) so you are informed about it by result false.

If you want to check if token starts with [ you can add .* at the end of your pattern to let it match rest of token. You can also remove * since whitespace is default delimiter so it can't be part of token.

In case of

Pattern p = Pattern.compile(" *\\[");
System.out.println(p.asPredicate().test("a[]")); //true

If you take a look at code of asPredicate you will see it is implemented as:

public Predicate<String> asPredicate() {
    return s -> matcher(s).find();
}

find() method doesn't check if whole string matches pattern, but tries to find even part of it which matches pattern. Since [] contains zero or more spaces followed by [ you are seeing true as result.


问:
Error while getting image from folder using Angularjs 1.5 and php
This error I am having;

```<code>GET http://localhost/~abhishek/Product/uploads/users/%7B%7Busers.image%7D%7D 404 (Not Found)
</code>```

... but the main reason to ask this question is; I am building product application and I have to store images in database and folder. so, I am getting that. images are loading in my web page but this errors are coming, please help me fix this.

答:
This is because, it is trying to search for this path.
PHP is not substituting the users.image string with proper values.

```<code>http://localhost/~abhishek/Product/uploads/users/{{users.image}}
</code>```

is the decoded form of URL in the above error.

```<code>http://localhost/~abhishek/Product/uploads/users/%7B%7Busers.image%7D%7D
</code>```

Body:
This error I am having;

GET http://localhost/~abhishek/Product/uploads/users/%7B%7Busers.image%7D%7D 404 (Not Found)

... but the main reason to ask this question is; I am building product application and I have to store images in database and folder. so, I am getting that. images are loading in my web page but this errors are coming, please help me fix this.

Body:
This is because, it is trying to search for this path.
PHP is not substituting the users.image string with proper values.

http://localhost/~abhishek/Product/uploads/users/{{users.image}}

is the decoded form of URL in the above error.

http://localhost/~abhishek/Product/uploads/users/%7B%7Busers.image%7D%7D


问:
how to set cron job from php script?
i am new to cron job . i studied some basics about cron job . i can able to call php using cron tab. By using following command in /etc/crontab

```<code>  10 *    * * *   root    /usr/bin/php /var/www/PATH TO SCRIPT/email.php
</code>```

In email.php i have following code

```<code> #!/usr/bin/php
 <?php
    mail ("examplemail@mail.com", "Cron Successful Public HTML!","Hello World from mycron.php!");
 ?>
</code>```

For every 10mins i am getting mail.
But i need to know is there any way to call cron job from php ( invoke cron from php)
i get some idea by surfing but i am not able to figure out the exact way to do my job .
Here is code which i used to add job by using php

```<code>   exec('echo -e "crontab -e \n2 * * * * /usr/bin/php /var/www/PATH TO THE SCRIPT/crontest1.php" ');
</code>```

Its not working for me. can anyone please guide me how to call or add cron from php. so tat i can send mail by executing php file & can able change time interval in php file itself.

答:
Many environments do not permit writing to a text file from a php page called from the web.  I agree that this is a security risk that one should not take.

I have a webpage save data to a MySQL table via a JQuery call to a php script.  In Cron, I schedule another php script to, every so often, check data in MySQL table and execute whatever jobs necessary.

Title: how to set cron job from php script?

Body:
i am new to cron job . i studied some basics about cron job . i can able to call php using cron tab. By using following command in /etc/crontab

  10 *    * * *   root    /usr/bin/php /var/www/PATH TO SCRIPT/email.php

In email.php i have following code

 #!/usr/bin/php
 <?php
    mail ("examplemail@mail.com", "Cron Successful Public HTML!","Hello World from mycron.php!");
 ?>

For every 10mins i am getting mail.
But i need to know is there any way to call cron job from php ( invoke cron from php)
i get some idea by surfing but i am not able to figure out the exact way to do my job .
Here is code which i used to add job by using php

   exec('echo -e "crontab -e \n2 * * * * /usr/bin/php /var/www/PATH TO THE SCRIPT/crontest1.php" ');

Its not working for me. can anyone please guide me how to call or add cron from php. so tat i can send mail by executing php file & can able change time interval in php file itself.


问:
Store the indexes of random elements correctly in an array
I got an array a which is filled by node objects. For example I got 200 nodes on my screen and all are saved inside this array. These nodes are labeled by individual indexes a[0], a[1], ect. Now, when I select a number of random nodes (for example with shortest path) and store them in a second array b which looks like b = [ object, object, object, object.....],
 is there a way to automatically return the position in array a? For example, when I click a random node, which is at the 3rd position in array a , that means at a[2], then I want that this position is returned or stored automatically, maybe in a third array c. And at the end, it could look like: c= [ a[2], a[6], a[18], a[7], a[0]  .....]. Hope someone can help me with my problem. Thanks so much!

答:
I'm not sure of the format of your arrays and what the objects contain. Using indexOf, https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf, may be a solution.

Using indexOf you can search the first array using the object that is clicked in the second array, you could then push this to a third array.


答:
You can try this </p>

```<code>arr = arr.flatten
</code>```

Title: How to add subarrays to itself? Ruby

Body:
You can try this

arr = arr.flatten


问:
How to hide Violations in Chrome 58+ while still showing console.debug?
As of Chrome 58

The Hide violations checkbox is gone. Set the logging level dropdown

  to Verbose to see violations.

This works, but I need to work on a project that is using console.debug as spammy level, while normal debug gets outputted with log/info/warn.

So when I actually need to read the debug, 99% of the console output is [Violation] clutter and I basicly need to open Firefox in order to debug properly.

Does anyone know of a workaround / extension / hack / whatever to just hide violations altogether while still showing console.debug?

答:
Welp, I guess the only way is to use RegEx: /^((?!\[Violation\]).)*$/ into filter box and you'll be able to show everything except violations.

Edit: This is no longer necessary, you can tick a checkbox to show "User Messages Only".


问:
Trash using memcpy
I'm using memcpy to copy a specific number of chars from a char array to a char *. But when I read the char * have always trash in the end.

I'm using libssh2 lib to send commands to my raspberry pi and receive the output.

libssh2_channel_read will return the number of chars of the output int x and the output text will be on the char buffer[32].

Code I'm using:

```<code>char buffer[32];
int x = libssh2_channel_read(channel, buffer, sizeof(buffer));
char * output = (char *)malloc(sizeof(char)*x);
memcpy(output, buffer, x-2); // x - 2 because of "\r\n"
libssh2_channel_free(channel);
channel = NULL;
cout << output << endl;
</code>```

Example of output:

```<code>0══²²²²
</code>```

I only want the 0

答:
Welcome to C++.

You are copying the values you care about but not the terminating '\0' character. Assuming x is valid (that is: x > 3 and x <= sizeof(buffer)) you can say:

```<code>output[x - 2] = '\0';
</code>```

after the call to memcpy() and you should get what you expect.

However: when you're dealing with communications and buffers like this you need to be careful and check everything.

Title: Trash using memcpy

Body:
I'm using memcpy to copy a specific number of chars from a char array to a char *. But when I read the char * have always trash in the end.

I'm using libssh2 lib to send commands to my raspberry pi and receive the output.

libssh2_channel_read will return the number of chars of the output int x and the output text will be on the char buffer[32].

Code I'm using:

char buffer[32];
int x = libssh2_channel_read(channel, buffer, sizeof(buffer));
char * output = (char *)malloc(sizeof(char)*x);
memcpy(output, buffer, x-2); // x - 2 because of "\r\n"
libssh2_channel_free(channel);
channel = NULL;
cout << output << endl;

Example of output:

0══²²²²

I only want the 0

Body:
Welcome to C++.

You are copying the values you care about but not the terminating '\0' character. Assuming x is valid (that is: x > 3 and x <= sizeof(buffer)) you can say:

output[x - 2] = '\0';

after the call to memcpy() and you should get what you expect.

However: when you're dealing with communications and buffers like this you need to be careful and check everything.


问:
String error when adding items from a listbox to an access database
I am trying to add the items in a list box to an access database. However at first, I was getting an error message saying the syntax was missing but now, I seem to get Conversion from string "" to type 'Double' is not valid ERROR. I've researched into this and it says it's because there may be a textbox empty but the listbox has many items in it which is what I'm not sure on.

Help will be appreciated, thanks.

```<code> Dim vari1 As String
        MyConn = New OleDbConnection
        MyConn.ConnectionString = connString
        MyConn.Open()
        Dim cmd1 As OleDbCommand = New OleDbCommand(str1, MyConn)
        Try
            For i As Integer = 0 To LstOrderItems.Items(i) - 1
                vari1 = LstOrderItems.Items.Item(i).ToString
                cmd1.CommandText = ("insert into RestaurantData ([Food Order]) VALUES(" + vari1 + ")")
                cmd1.ExecuteNonQuery()

            Next
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
        MyConn.Close()
    End If
</code>```

答:
It appears this line is your problem:

```<code>For i As Integer = 0 To LstOrderItems.Items(i) - 1
</code>```

You're trying to read the item at index i (which is currently 0) as a number to loop to.

I think what you meant to write was this:

```<code>For i As Integer = 0 To LstOrderItems.Items.Count - 1
</code>```

As for your database error you are missing two single quotes. When inserting data you must surround every value inside VALUES() with single quotes.

For instance:

INSERT INTO table_name (column1, column2, column3) VALUES('column1 value', 'column2 value', 'column3 value')
```

<p>So to fix your error you must add those single quotes as well:</p>

```cmd1.CommandText = ("insert into RestaurantData ([Food Order]) VALUES('" + vari1 + "')")
```

Though you should really look into Parameterized queries (aka Prepared statements) since your code is vulnerable to SQL Injection.

See How do I create a parameterized SQL query? Why Should I? for more info.

Body:
I am trying to add the items in a list box to an access database. However at first, I was getting an error message saying the syntax was missing but now, I seem to get Conversion from string "" to type 'Double' is not valid ERROR. I've researched into this and it says it's because there may be a textbox empty but the listbox has many items in it which is what I'm not sure on.

Help will be appreciated, thanks.

 Dim vari1 As String
        MyConn = New OleDbConnection
        MyConn.ConnectionString = connString
        MyConn.Open()
        Dim cmd1 As OleDbCommand = New OleDbCommand(str1, MyConn)
        Try
            For i As Integer = 0 To LstOrderItems.Items(i) - 1
                vari1 = LstOrderItems.Items.Item(i).ToString
                cmd1.CommandText = ("insert into RestaurantData ([Food Order]) VALUES(" + vari1 + ")")
                cmd1.ExecuteNonQuery()

            Next
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
        MyConn.Close()
    End If

Body:
It appears this line is your problem:

For i As Integer = 0 To LstOrderItems.Items(i) - 1

You're trying to read the item at index i (which is currently 0) as a number to loop to.

I think what you meant to write was this:

For i As Integer = 0 To LstOrderItems.Items.Count - 1

As for your database error you are missing two single quotes. When inserting data you must surround every value inside VALUES() with single quotes.

For instance:

INSERT INTO table_name (column1, column2, column3) VALUES('column1 value', 'column2 value', 'column3 value')

So to fix your error you must add those single quotes as well:

cmd1.CommandText = ("insert into RestaurantData ([Food Order]) VALUES('" + vari1 + "')")

Though you should really look into Parameterized queries (aka Prepared statements) since your code is vulnerable to SQL Injection.

See How do I create a parameterized SQL query? Why Should I? for more info.


问:
CSS: margin/padding on IE cause floats to be placed incorrectly
I'm having trouble getting IE7 to float my elements correctly (FF and Chrome work as expected). I'd like to have the "Delete" buttons (here a span with class "sbutton") to be floated all the way to the right. On IE the sbutton no the first line floats all the way to right as expected, but the subsequent lines float just to the left of the sbutton above them:

```<code>Something some other text ----------------------------------[Delete]
Something Else some other text ---------------------[Delete]--------
</code>```

This is related to paddings and margins on the sbutton:

```<code>.sbutton {
    background-color: #2E3239; color: white; border: 1px solid gray;
    font-family: "Trebuchet MS"; font-size: 90%; padding: 1px 3px; margin: 2px;
    -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px;
}
</code>```

If I remove the padding and margin they all float as expected.

Here's the HMTL:

```<code><li>
     <span class="left"><b>Something</b> (#1102) some other text</span>
     <span class="right"><a href="#" class="sbutton">Delete</a></span>
</li>
<li>
     <span class="left"><b>Something Else</b> (#1103) some other text</span>
     <span class="right"><a href="#" class="sbutton">Delete</a></span>
</li>
</code>```

I get similar behavior on FF and Chrome if I remove the outer span (the one with class "right").

Why is this happening, and what's the right way to do this?

答:
You need to clear your floats. Here's one way of doing it:</p>

```<code>.clear {
    clear:both;
    font-size:0;
}

<li>
     <span class="left"><b>Something</b> (#1102) some other text</span>
     <span class="right"><a href="#" class="sbutton">Delete</a></span>
     <span class='clear'></span>
</li>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm having trouble getting IE7 to float my elements correctly (FF and Chrome work as expected). I'd like to have the "Delete" buttons (here a span with class "sbutton") to be floated all the way to the right. On IE the sbutton no the first line floats all the way to right as expected, but the subsequent lines float just to the left of the sbutton above them:

Something some other text ----------------------------------[Delete]
Something Else some other text ---------------------[Delete]--------

This is related to paddings and margins on the sbutton:

.sbutton {
    background-color: #2E3239; color: white; border: 1px solid gray;
    font-family: "Trebuchet MS"; font-size: 90%; padding: 1px 3px; margin: 2px;
    -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px;
}

If I remove the padding and margin they all float as expected.

Here's the HMTL:

     Something (#1102) some other text
     Delete

     Something Else (#1103) some other text
     Delete

I get similar behavior on FF and Chrome if I remove the outer span (the one with class "right").

Why is this happening, and what's the right way to do this?

Body:
You need to clear your floats. Here's one way of doing it:

.clear {
    clear:both;
    font-size:0;
}

<li>
     <span class="left"><b>Something</b> (#1102) some other text</span>
     <span class="right"><a href="#" class="sbutton">Delete</a></span>
     <span class='clear'></span>
</li>


问:
.axd files generate a 404 error
Why do all of my .axd files generate a 404 error when on our production server?</p>

答: If this will help anyone, I had the same problem, few of us spent 2 days on. On 3 servers everything worked ok and allso on development but on this server 404 non stop. The solution, I changed poold from integrated to classic and that worked</p>

Title: .axd files generate a 404 error


问:
How to Get/Check The Internet Connection Strength in Android Studio
How to get/check internet connection strength in android studio?We can check whether internet is there or not ? But because of less internet strength developed android apps may crash

Thanks in advance

答:
Here's a snippet </p>

```<code>    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    int numberOfLevels = 5;
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    int level = WifiManager.calculateSignalLevel(wifiInfo.getRssi(), numberOfLevels);

    switch (level)
    {
        case 0:
            Log.d("LEVEL","None");
            break;

        case 1:
            Log.d("LEVEL","None");
            break;

        case 2:
            Log.d("LEVEL","Poor");
            break;

        case 3:
            Log.d("LEVEL","Moderate");
            break;

        case 4:
            Log.d("LEVEL","Good");
            break;

        case 5:
            Log.d("LEVEL","Excellent");
            break;
    }
</code>```

Body:
Here's a snippet

    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    int numberOfLevels = 5;
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    int level = WifiManager.calculateSignalLevel(wifiInfo.getRssi(), numberOfLevels);

    switch (level)
    {
        case 0:
            Log.d("LEVEL","None");
            break;

        case 1:
            Log.d("LEVEL","None");
            break;

        case 2:
            Log.d("LEVEL","Poor");
            break;

        case 3:
            Log.d("LEVEL","Moderate");
            break;

        case 4:
            Log.d("LEVEL","Good");
            break;

        case 5:
            Log.d("LEVEL","Excellent");
            break;
    }


问:
Replace bookmarks content without removing the bookmark
I want to replace the text content of bookmarks without loosing the bookmark.

```<code>foreach(Bookmark b in document.Bookmarks)
{
    b.Range.Text = "newtext";  // text is set in document but bookmark is gone
}
</code>```

I tried to set the new Range of the bookmark before the Text setting but I still have the same problem.

I also tried to re-add the bookmark with document.Bookmarks.Add(name, range); but I can't create an instance of range.

答:
I had to readd the bookmarks and save the range temporarily. I also had to add a list of processed items to evade an endless loop.</p>

```<code>List<string> bookmarksProcessed = new List<string>();

foreach (Bookmark b in document.Bookmarks)
{
    if (!bookmarksProcessed.Contains(b.Name))
    {
        string text = getTextFromBookmarkName(b.Name);
        var newend = b.Range.Start + text.Length;
        var name = b.Name;
        Range rng = b.Range;
        b.Range.Text = text;
        rng.End = newend;
        document.Bookmarks.Add(name, rng);
        bookmarksProcessed.Add(name);
    }
}
</code>```

Body:
I want to replace the text content of bookmarks without loosing the bookmark.

foreach(Bookmark b in document.Bookmarks)
{
    b.Range.Text = "newtext";  // text is set in document but bookmark is gone
}

I tried to set the new Range of the bookmark before the Text setting but I still have the same problem.

I also tried to re-add the bookmark with document.Bookmarks.Add(name, range); but I can't create an instance of range.

Body:
I had to readd the bookmarks and save the range temporarily. I also had to add a list of processed items to evade an endless loop.

List<string> bookmarksProcessed = new List<string>();

foreach (Bookmark b in document.Bookmarks)
{
    if (!bookmarksProcessed.Contains(b.Name))
    {
        string text = getTextFromBookmarkName(b.Name);
        var newend = b.Range.Start + text.Length;
        var name = b.Name;
        Range rng = b.Range;
        b.Range.Text = text;
        rng.End = newend;
        document.Bookmarks.Add(name, rng);
        bookmarksProcessed.Add(name);
    }
}


问:
How to navigate one page to another page with $scope value parameter in data-ui-sref in Angular Js?
I am using angular js for the web application. So I want to navigate one page to another page with some parameter in data-ui-sref. When I use static parameter then it will navigate with parameter.

Example:

click

Module.js

```<code>    .state('app.admin', {
        url: '/travlers?startFrom&endTo',
        data: {
          title: 'travelers'
        },
        params :
        {
           startFrom: null,
           endTo:null

         },
       views: {
      "content@app": {
        templateUrl: 'app/admin.html',
        controller: 'admin'
      }
    }
    });
</code>```

If I used static parameter in data-ui-sref then it will work. But If I take from scope value in parameter then it is not working.

When I use scope value in data-ui-sref parameter

example.html

```<code> <a data-ui-sref="app.admin({startFrom:'{{dateFrom}}',endTo:'{{dateTo}}'})">click</a>
</code>```

example.js

```<code>angular.module('app.admin').controller('example', function () {
      $scope.dateFrom="07-05-17";
      $scope.dateTo="07-05-17"
});
</code>```

When I see in console then scope value is append in data-ui-sref parameter

When I see in console then it is looks like this

```<code><a data-ui-sref="app.systemAdmin.travelers({startFrom:'07-05-17',endTo:'07-05-17'})" class="fa fa-external-link-square" aria-hidden="true" style="font-size:18px;color:#fff" href="#/systemadmin/travlers">click</a>
</code>```

After click the link then parameter is not going to module.js. URL is form without parameter and parameter(dateFrom,dateTo) is not going in state url.
I have seen one link. But it is for dynamic value Dynamically set the value of ui-sref Angularjs but my query is not for scope value in as parameter in data-ui-sref.

答: ui-sref value is a scope expression. Therefore, you don't have to interpolate the scope value but pass it as if it was javascript with direct access to your scope like: click.

Body:
I am using angular js for the web application. So I want to navigate one page to another page with some parameter in data-ui-sref. When I use static parameter then it will navigate with parameter.

Example:

click

Module.js

    .state('app.admin', {
        url: '/travlers?startFrom&endTo',
        data: {
          title: 'travelers'
        },
        params :
        {
           startFrom: null,
           endTo:null

         },
       views: {
      "content@app": {
        templateUrl: 'app/admin.html',
        controller: 'admin'
      }
    }
    });

If I used static parameter in data-ui-sref then it will work. But If I take from scope value in parameter then it is not working.

When I use scope value in data-ui-sref parameter

example.html

 click

example.js

angular.module('app.admin').controller('example', function () {
      $scope.dateFrom="07-05-17";
      $scope.dateTo="07-05-17"
});

When I see in console then scope value is append in data-ui-sref parameter

When I see in console then it is looks like this

click

After click the link then parameter is not going to module.js. URL is form without parameter and parameter(dateFrom,dateTo) is not going in state url.
I have seen one link. But it is for dynamic value Dynamically set the value of ui-sref Angularjs but my query is not for scope value in as parameter in data-ui-sref.

Body: ui-sref value is a scope expression. Therefore, you don't have to interpolate the scope value but pass it as if it was javascript with direct access to your scope like: <a data-ui-sref="app.admin({ startFrom: dateFrom, endTo: dateTo })">click</a>.


问:
Python pandas - Numeric column in dataframe is in exponent number
I've recently started facing this problem where in a column few values are in Exponential form and rest are regular numbers.

I want to merge two columns but it is not yielding any result for the one in exponent form. I would like to how can I overcome this problem to merge 2 dataframes.

example

```<code>df1
2780989
2780749
2816256

df2
2780989
2780749
2.81625e+06

pd.merge(df1,df2, on = 'column1')
2780989
2780749
</code>```

I tried changing both columns in strings then it is either showing

```<code>2780989.0
2780749.0
2816256.0
</code>```

I have a workaround which is keeping the column I want to merge as the very first column in my df but if it is on 2nd position it will start showing values as I mentioned above.

Body:
I've recently started facing this problem where in a column few values are in Exponential form and rest are regular numbers.

I want to merge two columns but it is not yielding any result for the one in exponent form. I would like to how can I overcome this problem to merge 2 dataframes.

example

df1
2780989
2780749
2816256

df2
2780989
2780749
2.81625e+06

pd.merge(df1,df2, on = 'column1')
2780989
2780749

I tried changing both columns in strings then it is either showing

2780989.0
2780749.0
2816256.0

I have a workaround which is keeping the column I want to merge as the very first column in my df but if it is on 2nd position it will start showing values as I mentioned above.

Body:
Let's convert both dataframes to float:

df1 = pd.DataFrame({'Col1':[2780989,2780749,2816250]}, dtype='int')

df2 = pd.DataFrame({'Col1':['2780989','2780749','2.81625e+06']})

pd.merge(df1.astype(float),df2.astype(float), on='Col1')

Output:

        Col1
0  2780989.0
1  2780749.0
2  2816250.0


问:
Intellitrace display's unknown for variables - c#
So I'm testing out intellitrace with some basic code and when I come to view the itrace file I can see the exception but not the variables around it, they all show as unknown. I don't know if it's something I haven't checked correctly but I can't get them to appear.

```<code>public partial class MainWindow : Window
{
    public List<User> items = new List<User>();

    public MainWindow()
    {
        InitializeComponent();
    }

    public void Button_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            click("sndafh");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString() + " " + txtName.Text);
        }
    }
    public void click(string name)
    {
        items.Add(new User() { Name = txtName.Text, Age = txtAge.Text });
        string pName = name;

        Users.Items.Clear();
        Users.ItemsSource = items;
        Users.Items.Refresh();
    }
}

public class User
{
    public string Name { get; set; }

    public string Age { get; set; }
}
</code>```

Snippet of VS 2015 with unknown variables

答:
Make sure that you have selected the "IntelliTrace events and call information" option under Tools->Options->IntelliTrace->IntelliTrace Events.

Please refer to the following MSDN article for more information.

Visual Studio 2015 - Use IntelliTrace to Diagnose Issues Faster: https://msdn.microsoft.com/en-us/magazine/dn973014.aspx

Body:
So I'm testing out intellitrace with some basic code and when I come to view the itrace file I can see the exception but not the variables around it, they all show as unknown. I don't know if it's something I haven't checked correctly but I can't get them to appear.

public partial class MainWindow : Window
{
    public List<User> items = new List<User>();

    public MainWindow()
    {
        InitializeComponent();
    }

    public void Button_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            click("sndafh");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString() + " " + txtName.Text);
        }
    }
    public void click(string name)
    {
        items.Add(new User() { Name = txtName.Text, Age = txtAge.Text });
        string pName = name;

        Users.Items.Clear();
        Users.ItemsSource = items;
        Users.Items.Refresh();
    }
}

public class User
{
    public string Name { get; set; }

    public string Age { get; set; }
}

Snippet of VS 2015 with unknown variables


问:
Git LPass: Could not find specified account
I'm trying to use lastpass-cli on fedora 24 to log git without entering password every push/pull.
But I received this error below:

Error: Could not find specified account(s).

Error: Could not find specified account(s).

Couldn't find host in lastpass DB.
  error: unable to read askpass response from '/usr/libexec/openssh/gnome-ssh-askpass'

Into lastpass vault I have tried both configuration:

1) code.xyz.com/project/example.git (more specific)

2) Just code.xyz.com

I'm using this script: https://raw.githubusercontent.com/lastpass/lastpass-cli/master/contrib/examples/git-credential-lastpass

And then the configuration:

```<code>git config --global credential.helper './git-credential-lastpass'
</code>```

Any clue, please?

Thank you.

答:
After tinkering with the script I found a solution:
Use the hostname of the repo (without protocol and with port if it's not set to default default) as the Name property of the LastPass credential.

For example if your remote origin url is:

```<code>url = https://username@repo.example.com:12345/reponame
</code>```

then set the name of the LastPass credential to:

```<code>repo.example.com:12345
</code>```

Body:
I'm trying to use lastpass-cli on fedora 24 to log git without entering password every push/pull.
But I received this error below:

Error: Could not find specified account(s).

Error: Could not find specified account(s).

Couldn't find host in lastpass DB.
  error: unable to read askpass response from '/usr/libexec/openssh/gnome-ssh-askpass'

Into lastpass vault I have tried both configuration:

1) code.xyz.com/project/example.git (more specific)

2) Just code.xyz.com

I'm using this script: https://raw.githubusercontent.com/lastpass/lastpass-cli/master/contrib/examples/git-credential-lastpass

And then the configuration:

git config --global credential.helper './git-credential-lastpass'

Any clue, please?

Thank you.

Body:
After tinkering with the script I found a solution:
Use the hostname of the repo (without protocol and with port if it's not set to default default) as the Name property of the LastPass credential.

For example if your remote origin url is:

url = https://username@repo.example.com:12345/reponame

then set the name of the LastPass credential to:

repo.example.com:12345


问:
Unable to update time in datePicker on button click in tableview swift
I am trying to display a date picker and update its time on button click.

I have a table view which shows business hours as shown in the below figure 1.

Figure 1

On clicking the timings cell or the time button inside the cell, I am expanding the cell to show date picker, I am unable to update the time in the date picker to the time on the time button.

For example when 9:00 AM is clicked, I would like to show 9:00 AM in the date picker as shown in below figure 2 or when 5:00 PM is clicked I would like to show 5:00 PM in date picker.

Also when the user changes the time in the date picker, I would like to update its corresponding time button in the tableview cell.

Figure 2

Below is the code, see code below comment //Updating the date picker

Since I am trying to update the date picker time inside a closure, it doesn't seem to work. Can someone please advice how I can fix this ?

```<code>    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        tableView.setEditing(true, animated: true)      // This displays the delete button infront of the cell
        tableView.allowsSelectionDuringEditing = true   // Allows the table view cells to be selected during editing mode

        if indexPath.section == 0 {

            let cell = Bundle.main.loadNibNamed("DailyTimesTableViewCell", owner: self, options: nil)?.first as! DailyTimesTableViewCell

            // Configure the cell...
            cell.selectionStyle             = UITableViewCellSelectionStyle.none; // Ensuring that there is no background for the selected cell
            cell.datePicker.datePickerMode  = .time         // Setting start and time
            cell.datePicker.minuteInterval = 5
            cell.datePicker.addTarget(self, action: #selector(datePickerChanged), for: .valueChanged)

            let startTime   = timesArray[indexPath.row]["startTime"]
            cell.startTime.setTitle(startTime as! String?, for: .normal)
            cell.startTime.setTitleColor(UIColor.black, for: .normal)

            let endTime     = timesArray[indexPath.row]["endTime"]

            cell.endTime.setTitle(endTime as! String?, for: .normal)
            cell.endTime.setTitleColor(UIColor.black, for: .normal)

            // Closure
            cell.startTimeTapped = { (button  : UIButton) -> Void in

                // Updating the date picker
                cell.datePicker.date = self.convertToDateObject(timeString: startTime as! String)
                tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic)

                // Expanding the cell to show date picker
                if self.selectedCellIndexPath != nil && self.selectedCellIndexPath == indexPath {
                    tableView.cellForRow(at: indexPath)?.setEditing(true, animated: true)   // This displays the delete button infront of the cell
                    self.selectedCellIndexPath = nil
                } else {
                    self.selectedCellIndexPath = indexPath
                }

            }

            // Closure
            cell.endTimeTapped = { (button) -> Void in
                // Updating the date picker
                cell.datePicker.date = self.convertToDateObject(timeString: endTime as! String)
                tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic)

                // Expanding the cell to show date picker
                if self.selectedCellIndexPath != nil && self.selectedCellIndexPath == indexPath{
                    tableView.cellForRow(at: indexPath)?.setEditing(true, animated: true)
                    self.selectedCellIndexPath = nil
                }else{
                    self.selectedCellIndexPath = indexPath
                }
            }
            return cell
      }
}
</code>```

DailyTimesTableViewCell code:

```<code>import UIKit

class DailyTimesTableViewCell: UITableViewCell, UITableViewDelegate {
    typealias  buttonTappedBlock = (_ button:UIButton) -> Void
    var startTimeTapped : buttonTappedBlock!
    var endTimeTapped : buttonTappedBlock!

    @IBAction func startTimeClicked(_ sender: subclassedUIButton) {
        if startTimeTapped != nil {
            startTimeTapped(sender as UIButton)
        }
    }

    @IBAction func endTimeClicked(_ sender: UIButton) {
        if endTimeTapped != nil{
            endTimeTapped(sender as UIButton)
        }
    }
}
</code>```

答:
To set date for your UIDatePicker, simply use this piece of code to convert string formed time to a date

```<code>let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat =  "HH:mm"
let date = dateFormatter.dateFromString("17:00")//Put textfield.text! here

datePicker.date = date
</code>```

For your second part of the question, since you may have multiple date pickers, what you need to do is to add selection change listener to all of them, then figure out which one is changed and also which label is clicked. Finally set the label to correct value.

You can use section number to find out which data picker is clicked. In your cellForRow, add section as tag and then add the listener

```<code>datePicker.tag = indexPath.section
textView.tag = indexPath.section
datePicker.addTarget(self, action: Selector("dataPickerChanged:"), forControlEvents: UIControlEvents.ValueChanged)
</code>```

Then in the listener function, find out  which data picker has changed value

```<code>func datePickerChanged(datePicker:UIDatePicker) {
    var dateFormatter = NSDateFormatter()
    dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
    dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle

    if datePicker.tag == 0 {
        textView.text = dateFormatter.stringFromDate(datePicker.date)
    }
    // keep going

}
</code>```

Body:
I am trying to display a date picker and update its time on button click.

I have a table view which shows business hours as shown in the below figure 1.

Figure 1

On clicking the timings cell or the time button inside the cell, I am expanding the cell to show date picker, I am unable to update the time in the date picker to the time on the time button.

For example when 9:00 AM is clicked, I would like to show 9:00 AM in the date picker as shown in below figure 2 or when 5:00 PM is clicked I would like to show 5:00 PM in date picker.

Also when the user changes the time in the date picker, I would like to update its corresponding time button in the tableview cell.

Figure 2

Below is the code, see code below comment //Updating the date picker

Since I am trying to update the date picker time inside a closure, it doesn't seem to work. Can someone please advice how I can fix this ?

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        tableView.setEditing(true, animated: true)      // This displays the delete button infront of the cell
        tableView.allowsSelectionDuringEditing = true   // Allows the table view cells to be selected during editing mode

        if indexPath.section == 0 {

            let cell = Bundle.main.loadNibNamed("DailyTimesTableViewCell", owner: self, options: nil)?.first as! DailyTimesTableViewCell

            // Configure the cell...
            cell.selectionStyle             = UITableViewCellSelectionStyle.none; // Ensuring that there is no background for the selected cell
            cell.datePicker.datePickerMode  = .time         // Setting start and time
            cell.datePicker.minuteInterval = 5
            cell.datePicker.addTarget(self, action: #selector(datePickerChanged), for: .valueChanged)

            let startTime   = timesArray[indexPath.row]["startTime"]
            cell.startTime.setTitle(startTime as! String?, for: .normal)
            cell.startTime.setTitleColor(UIColor.black, for: .normal)

            let endTime     = timesArray[indexPath.row]["endTime"]

            cell.endTime.setTitle(endTime as! String?, for: .normal)
            cell.endTime.setTitleColor(UIColor.black, for: .normal)

            // Closure
            cell.startTimeTapped = { (button  : UIButton) -> Void in

                // Updating the date picker
                cell.datePicker.date = self.convertToDateObject(timeString: startTime as! String)
                tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic)

                // Expanding the cell to show date picker
                if self.selectedCellIndexPath != nil && self.selectedCellIndexPath == indexPath {
                    tableView.cellForRow(at: indexPath)?.setEditing(true, animated: true)   // This displays the delete button infront of the cell
                    self.selectedCellIndexPath = nil
                } else {
                    self.selectedCellIndexPath = indexPath
                }

            }

            // Closure
            cell.endTimeTapped = { (button) -> Void in
                // Updating the date picker
                cell.datePicker.date = self.convertToDateObject(timeString: endTime as! String)
                tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic)

                // Expanding the cell to show date picker
                if self.selectedCellIndexPath != nil && self.selectedCellIndexPath == indexPath{
                    tableView.cellForRow(at: indexPath)?.setEditing(true, animated: true)
                    self.selectedCellIndexPath = nil
                }else{
                    self.selectedCellIndexPath = indexPath
                }
            }
            return cell
      }
}

DailyTimesTableViewCell code:

import UIKit

class DailyTimesTableViewCell: UITableViewCell, UITableViewDelegate {
    typealias  buttonTappedBlock = (_ button:UIButton) -> Void
    var startTimeTapped : buttonTappedBlock!
    var endTimeTapped : buttonTappedBlock!

    @IBAction func startTimeClicked(_ sender: subclassedUIButton) {
        if startTimeTapped != nil {
            startTimeTapped(sender as UIButton)
        }
    }

    @IBAction func endTimeClicked(_ sender: UIButton) {
        if endTimeTapped != nil{
            endTimeTapped(sender as UIButton)
        }
    }
}

Body:
To set date for your UIDatePicker, simply use this piece of code to convert string formed time to a date

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat =  "HH:mm"
let date = dateFormatter.dateFromString("17:00")//Put textfield.text! here

datePicker.date = date

For your second part of the question, since you may have multiple date pickers, what you need to do is to add selection change listener to all of them, then figure out which one is changed and also which label is clicked. Finally set the label to correct value.

You can use section number to find out which data picker is clicked. In your cellForRow, add section as tag and then add the listener

datePicker.tag = indexPath.section
textView.tag = indexPath.section
datePicker.addTarget(self, action: Selector("dataPickerChanged:"), forControlEvents: UIControlEvents.ValueChanged)

Then in the listener function, find out  which data picker has changed value

func datePickerChanged(datePicker:UIDatePicker) {
    var dateFormatter = NSDateFormatter()
    dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
    dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle

    if datePicker.tag == 0 {
        textView.text = dateFormatter.stringFromDate(datePicker.date)
    }
    // keep going

}


问:
How do you account for server-side redirects in an app shell?
I am working on implementing a service worker which caches and serves an app shell to certain routes on my site.

I am running into a problem in that the route can sometimes (based on a query parameter, say) cause a redirect on the server side. However, once the user is being served an app shell, they never actually hit the server again, and the redirects aren't happening.

This seems like a problem inherent to app shells. Looking for thoughts and guidance on handling cases like these.

Additional details for clarity:

User hits https://www.example.com

Service worker is installed, subsequently serving an app shell for the / route

Some time later, the user hits the site again, but their account has been flagged for a security review. Normally, the server would handle this redirection, redirecting the user to, for example, https://www.example.com/account/security

However, due to the presence of the app shell, the server has no opportunity to perform such a redirect.

答:
(Promoting this from the comment section. It's not the only possible approach, but depending on how comfortable you are with running the redirect logic via client-side JavaScript, it should accomplish what you describe.)

In that scenario, it sounds like you'd need to have the client ask the server periodically (perhaps every time there's a History API navigation), via a lightweight fetch(), whether there's a reason to go to a special page. And then if the server responds yes, and you need to redirect, you can explicitly set location to the security checkup URL, which should be blacklisted from App Shell navigation.


问:
How to install an app in system/app while developing from android studio
Is there a way to make an app install directly in the system/app folder while developing on Android Studio (the device is rooted)?

Meaning, when I press on the 'Run app' button, I want the apk to be placed in system/app.

If this is not possible, what is the recommended most convenient way to work on building and testing a system app?

答:
To bypass reboot issue from the @paschalis answer reinstall application with a help of package manager before remounting system to read only:

```<code># Reinstall app
$ADB_SH "pm install -r $apk_target_sys"

# Unmount system
$ADB_SH "mount -o remount,ro /"
</code>```

Package manager will invoke dex2oat by itself.

Body:
To bypass reboot issue from the @paschalis answer reinstall application with a help of package manager before remounting system to read only:

# Reinstall app
$ADB_SH "pm install -r $apk_target_sys"

# Unmount system
$ADB_SH "mount -o remount,ro /"

Package manager will invoke dex2oat by itself.