问:
How to avoid manually turning on, sliding and unlocking screen each time I run Android app remotely
Using the standard Eclipse-based development environment to develop Android apps, you press Control-F11 to squirt your app down the USB cable to your phone.  This works great, but if you've done practically any work at all between tests the screen will have timed out and turned off.  You then have to press the power button, then slide the slider, then do the pattern unlock pattern, and only then can you see your app running.  This gets old pretty quickly.

It would be nice to be able to somehow have a message sent down with your app to do all this for you.

I accept that I could probably configure my phone to not turn the screen off, and disable the slider and pattern lock, but I don't really want to as I always want that behaviour when I'm not developing.

Any idea if the behaviour I'm after is possible?  I've looked unsuccessfully for any documentation describing how to customize whatever happens when you send data to the phone.  If possible the solution should be possible from within eclipse, but even having to send it via Terminal (I use Ubuntu to develop) or something would similar would be better than nothing.

答:
If you go into Settings > Applications > Development there is an option there named "Stay Awake" which means the screen never sleeps while charging.

There is also another useful option named "USB Debugging" which should also be turned on if you are developing and testing over USB.

Hope that helps,

Alan


来源: stackexchange

问:
PHP Warning: No such file or directory in Unknown on line 0
I'm using hosting in linux and configured subdomain in my website in Apache2 server. I'm using laravel but I didn't use apache2 service by default. I'm using laravel artisan commands.

php artisan serve --host 0.0.0.0

It will listen to port 8000. So in order to access my website, I'm used http://myipaddress:8000 to access it.

I tried to "chmod 755 or 777 public folder" but still didn't work. My .htaccess in laravel/public folder

.htaccess

```<code><IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews
</IfModule>

RewriteEngine On

# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</code>```

When I access my website with port 8000, below is my errors:

```<code>PHP Warning:  Unknown: failed to open stream: No such file or directory in Unknown on line 0

PHP Fatal error:  Unknown: Failed opening required 'server.php' (include_path='.:/usr/share/php:/usr/share/php/PEAR') in Unknown on line 0
</code>```

答:
I had the same issue, the real cause of the problem is this, somewhere along the line, the last parameter for the php -S built in server was changed to a flag, so you have to call it like this:

php -S 127.0.0.1:8000 -t public -f serve.php

Before php 7.0.26 you could omit the -f.

This is what happens under the hood when you call php artisan serve.

If you want to serve it with php artisan serve you will have to override the ServeCommand and add -f before the serve.php ont the last line of the fire() method, like this:

passthru('"'.PHP_BINARY.'"'." -S {$host}:{$port} -t \"{$public}\" -f server.php");

For more details look at this stackoverflow post.

ContentLicense: CC BY-SA 3.0

Body:
I'm using hosting in linux and configured subdomain in my website in Apache2 server. I'm using laravel but I didn't use apache2 service by default. I'm using laravel artisan commands.

php artisan serve --host 0.0.0.0

It will listen to port 8000. So in order to access my website, I'm used http://myipaddress:8000 to access it.

I tried to "chmod 755 or 777 public folder" but still didn't work. My .htaccess in laravel/public folder

.htaccess

<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews
</IfModule>

RewriteEngine On

# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

When I access my website with port 8000, below is my errors:

PHP Warning:  Unknown: failed to open stream: No such file or directory in Unknown on line 0

PHP Fatal error:  Unknown: Failed opening required 'server.php' (include_path='.:/usr/share/php:/usr/share/php/PEAR') in Unknown on line 0


问:
Sort Linked List based on dynamic field from user
My objective is to Dynamically insert values in to the Linked List. And thereafter, I want to perform sorting or search algorithms on the List.

In addition to it, I am creating class at runtime (based on user input) using Reflection.

Thereafter, I use data provided by the user in JSON Array, to create instances of the class, and then I insert the instances in to the GenericList.

Following is the code for the Generic Linked List.

```<code>public class LinkedListNode<T> implements Serializable {
    private T value;
    private LinkedListNode<T> next;

    public LinkedListNode(T value) {
        this.value = value;
    }
    public void setNext(LinkedListNode<T> next) {
        this.next = next;
    }
    public LinkedListNode<T> getNext() {
        return next;
    }
    public T getValue() {
        return value;
    }
}

public class GenericList<T>  implements Serializable {
    private LinkedListNode<T> first = null;
    public void insert(LinkedListNode<T> node) {
        node.setNext(first);
        first = node;
    }
    public void emptyList(){
        first = null;
    }
    public void remove(){
        if(first.getNext()!=null)
            first = first.getNext();
        else first = null;
    }
}
</code>```

And this is how I create instances of the class and insert it to the GenericList.

```<code>//dataToInsert => is the JSONArray. =>  [{field1:"value1",field2:"value1"},{field1:"value2",field2:"value2"},{field1:"value3",field2:"value3"}]
//classLoaded =>  package com.LinkedAnalyzerAdapter.saveTestClasses; public class order implements java.io.Serializable  {public String field1;public String field2;}
Class<?> classLoaded = classLoader.loadClass("com.LinkedAnalyzerAdapter.saveTestClasses.order");
GenericList<Object> list = new GenericList<Object>();
for (int i = 0; i < dataToInsert.length(); i++) {
    JSONObject jsonObj = new JSONObject();
    jsonObj = dataToInsert.getJSONObject(i);
    Object obj = classLoaded.newInstance();
    Field[] fs = classLoaded.getDeclaredFields();
    for (Field field : fs)
    {
        field.setAccessible(true);
        Object fieldValue = jsonObj.get(field.getName());
        field.set(obj, fieldValue);
    }
    list.insert(new LinkedListNode<Object>(obj));
}
</code>```

I am successfully able to insert data in to GenericList, but after inserting I later want to sort the data based on field1, in the ascending order.

I have spent hours to solve it but unable to successfully accomplish sorting.

答:
Used the following code to resolve the issue.</p>

```<code>public void sortLinkedList(final String fieldToCompare){

        Collections.sort(testList, new Comparator<LinkedListNode>() {
            @Override
            public int compare(LinkedListNode arg0, LinkedListNode arg1) {
                // TODO Auto-generated method stub
                Field[] fs = classtoLoad.getDeclaredFields();
                for (Field field : fs){
                    field.setAccessible(true);
                    Object fieldName = field.getName();
                     if(fieldToCompare.equalsIgnoreCase((String) fieldName)){
                         try {
                             String value1 = (String) field.get(arg0.getValue());
                             String value2 = (String) field.get(arg1.getValue());
                             return value1.compareToIgnoreCase(value2);

                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                         return 0;
                     }
                }
                return 0;
            }
        });
}
</code>```

Body:
My objective is to Dynamically insert values in to the Linked List. And thereafter, I want to perform sorting or search algorithms on the List.

In addition to it, I am creating class at runtime (based on user input) using Reflection.

Thereafter, I use data provided by the user in JSON Array, to create instances of the class, and then I insert the instances in to the GenericList.

Following is the code for the Generic Linked List.

public class LinkedListNode<T> implements Serializable {
    private T value;
    private LinkedListNode<T> next;

    public LinkedListNode(T value) {
        this.value = value;
    }
    public void setNext(LinkedListNode<T> next) {
        this.next = next;
    }
    public LinkedListNode<T> getNext() {
        return next;
    }
    public T getValue() {
        return value;
    }
}

public class GenericList<T>  implements Serializable {
    private LinkedListNode<T> first = null;
    public void insert(LinkedListNode<T> node) {
        node.setNext(first);
        first = node;
    }
    public void emptyList(){
        first = null;
    }
    public void remove(){
        if(first.getNext()!=null)
            first = first.getNext();
        else first = null;
    }
}

And this is how I create instances of the class and insert it to the GenericList.

//dataToInsert => is the JSONArray. =>  [{field1:"value1",field2:"value1"},{field1:"value2",field2:"value2"},{field1:"value3",field2:"value3"}]
//classLoaded =>  package com.LinkedAnalyzerAdapter.saveTestClasses; public class order implements java.io.Serializable  {public String field1;public String field2;}
Class<?> classLoaded = classLoader.loadClass("com.LinkedAnalyzerAdapter.saveTestClasses.order");
GenericList<Object> list = new GenericList<Object>();
for (int i = 0; i < dataToInsert.length(); i++) {
    JSONObject jsonObj = new JSONObject();
    jsonObj = dataToInsert.getJSONObject(i);
    Object obj = classLoaded.newInstance();
    Field[] fs = classLoaded.getDeclaredFields();
    for (Field field : fs)
    {
        field.setAccessible(true);
        Object fieldValue = jsonObj.get(field.getName());
        field.set(obj, fieldValue);
    }
    list.insert(new LinkedListNode<Object>(obj));
}

I am successfully able to insert data in to GenericList, but after inserting I later want to sort the data based on field1, in the ascending order.

I have spent hours to solve it but unable to successfully accomplish sorting.

Body:
Used the following code to resolve the issue.

public void sortLinkedList(final String fieldToCompare){

        Collections.sort(testList, new Comparator<LinkedListNode>() {
            @Override
            public int compare(LinkedListNode arg0, LinkedListNode arg1) {
                // TODO Auto-generated method stub
                Field[] fs = classtoLoad.getDeclaredFields();
                for (Field field : fs){
                    field.setAccessible(true);
                    Object fieldName = field.getName();
                     if(fieldToCompare.equalsIgnoreCase((String) fieldName)){
                         try {
                             String value1 = (String) field.get(arg0.getValue());
                             String value2 = (String) field.get(arg1.getValue());
                             return value1.compareToIgnoreCase(value2);

                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                         return 0;
                     }
                }
                return 0;
            }
        });
}


问:
Laravel: performing some task on every insert/update when using Query Builder or Eloquent ORM

The Problem

I would like to automatically add created_by and modified_by fields to every insert/update to a database table in Laravel 4, regardless of whether I am using Eloquent or Query Builder. However, not all my tables have these fields so any solution will have to check these columns exist before adding.

Attempted Solution

I have extended the Illuminate\Database\Eloquent\Model class and written an overwrite method save() in order to add some additional meta data fields for every record that is saved.

This is fine except that if I perform an insert using the Query Builder then this is bypassed. Looking at the Model class it appears that the database operations are actually done using the query builder.

I have had a look at the Illuminate\Database\Query\Builder model and it looks like I could probably write overwrite methods for insert() and update().

Is this a sensible way to go about performing some task for every insert/update or will I run into trouble later down the line?

答:
You can use venturecraft revisionable package because in a table from this package  all info that you need is already stored, you just need this package to get them in an elegant way :
https://github.com/fico7489/laravel-revisionable-upgrade</p>


问:
Matching fixed-format numbers and optional string in regex
Regex newbie! I would like to validate a time string in the format HH:MM with an optional space and AM or PM suffix.

Example: 10:30 or 10:30 AM will both be valid.

Here's what I have so far which is failing:

```<code>  $test = '12:34';
  if(!preg_match("/^\d{2}:\d{2}?\s(AM|PM)$/", $test))
  {
      echo "bad format!";
  }
</code>```

In addition, is it possible to validate that the HH or MM values are <= 12 and <=60 respectively within the same regex?

Regards, Ben.

答:
Try this:

```<code>/^\d{2}:\d{2}(?:\s?[AP]M)?$/
</code>```

Here the last part (?:\s?[AP]M)? is an optional, non-capturing group that may start with an optional whitespace character and is then followed by either AM or PM.

For the number ranges replace the first \d{2} by (?:0\d|1[012]) and the second by (?:[0-5]\d|60).

ContentLicense: CC BY-SA 2.5

Body:
Regex newbie! I would like to validate a time string in the format HH:MM with an optional space and AM or PM suffix.

Example: 10:30 or 10:30 AM will both be valid.

Here's what I have so far which is failing:

  $test = '12:34';
  if(!preg_match("/^\d{2}:\d{2}?\s(AM|PM)$/", $test))
  {
      echo "bad format!";
  }

In addition, is it possible to validate that the HH or MM values are <= 12 and <=60 respectively within the same regex?

Regards, Ben.

Body:
Try this:

/^\d{2}:\d{2}(?:\s?[AP]M)?$/

Here the last part (?:\s?[AP]M)? is an optional, non-capturing group that may start with an optional whitespace character and is then followed by either AM or PM.

For the number ranges replace the first \d{2} by (?:0\d|1[012]) and the second by (?:[0-5]\d|60).


问:
How to move between MVC controllers using knockout.js?
I have an issue with moving from one MVC controller to another. I am new to MVC/Knockout combination and trying to find a best way.

I have a HomeController that does some login processes. The Login view, of the controller, contains knockout script that posts data it. After a certain select is chosen this code is executed by a button press with data-bind="clicked: SubmitLocation"

```<code>    self.SubmitLocation = function () {
        var jsonData = ko.toJSON(new LoginModel(self.Username, self.Password, self.isAuthenticated, self.UserId, self.SelectedLocId, self.SelectedLocDesc));
        alert(jsonData);
        $.ajax({
            ur: '@Url.Action("Login", "Home")',
            type: 'post',
            data: jsonData,
            contentType: 'application/json',
            success: function () { }
        });
</code>```

This brings it to the code inside MVC controller :

```<code>    [HttpPost]
    public ActionResult ....{
            return RedirectToAction("Products", "Product");
     ...}
</code>```

Debugging through the code, I see that it makes it over to the Product controller and even to the Products view, without exceptions. However the page on the browser itself remains on the original HomeController/Login view. Where am I going wrong?

I have also tried returning a different view from the same HOmeController instead of RedirectToAction, and it is still the same.

答:
You can't return RedirectToAction() or return View() to an ajax call. Upon successful login, return Json(true) from the controller and in the success callback of ajax, redirect to the Products action

```<code>[HttpPost]
public ActionResult Login(UserViewModel user)
{
     // authentication code here

     return Json(true);
}
</code>```

JS:

```<code>self.SubmitLocation = function() {
  var jsonData = ko.toJSON(new LoginModel(self.Username, self.Password, self.isAuthenticated, self.UserId, self.SelectedLocId, self.SelectedLocDesc));

  $.ajax({
    ur: '@Url.Action("Login", "Home")',
    type: 'post',
    data: jsonData,
    contentType: 'application/json',
    success: function(data) {
      if (data)
        location.href = '@Url.Action("Products", "Product")'; // redirect
    }
  });
}
</code>```

Body:
I have an issue with moving from one MVC controller to another. I am new to MVC/Knockout combination and trying to find a best way.

I have a HomeController that does some login processes. The Login view, of the controller, contains knockout script that posts data it. After a certain select is chosen this code is executed by a button press with data-bind="clicked: SubmitLocation"

    self.SubmitLocation = function () {
        var jsonData = ko.toJSON(new LoginModel(self.Username, self.Password, self.isAuthenticated, self.UserId, self.SelectedLocId, self.SelectedLocDesc));
        alert(jsonData);
        $.ajax({
            ur: '@Url.Action("Login", "Home")',
            type: 'post',
            data: jsonData,
            contentType: 'application/json',
            success: function () { }
        });

This brings it to the code inside MVC controller :

    [HttpPost]
    public ActionResult ....{
            return RedirectToAction("Products", "Product");
     ...}

Debugging through the code, I see that it makes it over to the Product controller and even to the Products view, without exceptions. However the page on the browser itself remains on the original HomeController/Login view. Where am I going wrong?

I have also tried returning a different view from the same HOmeController instead of RedirectToAction, and it is still the same.

Body:
You can't return RedirectToAction() or return View() to an ajax call. Upon successful login, return Json(true) from the controller and in the success callback of ajax, redirect to the Products action

[HttpPost]
public ActionResult Login(UserViewModel user)
{
     // authentication code here

     return Json(true);
}

JS:

self.SubmitLocation = function() {
  var jsonData = ko.toJSON(new LoginModel(self.Username, self.Password, self.isAuthenticated, self.UserId, self.SelectedLocId, self.SelectedLocDesc));

  $.ajax({
    ur: '@Url.Action("Login", "Home")',
    type: 'post',
    data: jsonData,
    contentType: 'application/json',
    success: function(data) {
      if (data)
        location.href = '@Url.Action("Products", "Product")'; // redirect
    }
  });
}


问:
Django model method to count method flag of foreignkeys
I have two models Assessment and Answer with a OnetoMany relationship.

models.py

```<code>class Assessment(models.Model):
    name = models.CharField(max_length=255, blank=False)
    def __str__(self):
        return "{}".format(self.name)

    def _all_answers_completed(self):
         pass
         #some how get all related answers
         #then see if "completed" = true
         #if all = true then return true
         #if any = false then return false
    completed = property(_all_answers_completed)

class Answer(models.Model):
    assessment = models.ForeignKey(Assessment, null=True, blank=True, on_delete=models.CASCADE)
    score_risk = models.IntegerField(default=0)
    score_impact = models.IntegerField(default=0)
    score_occurrance = models.IntegerField(default=0)
    def __str__(self):
        return "Answer to Question:{} for Assessment {}".format(self.question, self.assessment)

    def _is_answered(self):
        if self.score_risk > 0 and self.score_impact >0  and self.score_occurrance > 0:
            return True
        else:
            return False
    completed = property(_is_answered)
</code>```

I want to set the assessment method completed based on the related answers property answer.completed

I just don't know how to do this or do I have to do this in a view via looping through a queryset.

答: You can use backward-related-objects.</p>

Body:
I have two models Assessment and Answer with a OnetoMany relationship.

models.py

class Assessment(models.Model):
    name = models.CharField(max_length=255, blank=False)
    def __str__(self):
        return "{}".format(self.name)

    def _all_answers_completed(self):
         pass
         #some how get all related answers
         #then see if "completed" = true
         #if all = true then return true
         #if any = false then return false
    completed = property(_all_answers_completed)

class Answer(models.Model):
    assessment = models.ForeignKey(Assessment, null=True, blank=True, on_delete=models.CASCADE)
    score_risk = models.IntegerField(default=0)
    score_impact = models.IntegerField(default=0)
    score_occurrance = models.IntegerField(default=0)
    def __str__(self):
        return "Answer to Question:{} for Assessment {}".format(self.question, self.assessment)

    def _is_answered(self):
        if self.score_risk > 0 and self.score_impact >0  and self.score_occurrance > 0:
            return True
        else:
            return False
    completed = property(_is_answered)

I want to set the assessment method completed based on the related answers property answer.completed

I just don't know how to do this or do I have to do this in a view via looping through a queryset.

Body: You can use backward-related-objects.


问:
Transforming mLSTM - Run it on multiple GPUs
I'm running an mLSTM (multiplicative LSTM) transform (based on mLSTM by OpenAi (just the transform, it is already trained) but it takes a really long time to transform more than ~100,000 docs.

I want it to run on multiple GPUs. I saw some examples but I have no idea how to implement it on this mLSTM transform code.

The specific part that I want to run on multiple GPUs is:

        def transform(xs):
            tstart = time.time()
            xs = [preprocess(x) for x in xs]
            lens = np.asarray([len(x) for x in xs])
            sorted_idxs = np.argsort(lens)
            unsort_idxs = np.argsort(sorted_idxs)
            sorted_xs = [xs[i] for i in sorted_idxs]
            maxlen = np.max(lens)
            offset = 0
            n = len(xs)
            smb = np.zeros((2, n, hps.nhidden), dtype=np.float32)
            for step in range(0, ceil_round_step(maxlen, nsteps), nsteps):
                start = step
                end = step+nsteps
                xsubseq = [x[start:end] for x in sorted_xs]
                ndone = sum([x == b'' for x in xsubseq])
                offset += ndone
                xsubseq = xsubseq[ndone:]
                sorted_xs = sorted_xs[ndone:]
                nsubseq = len(xsubseq)
                xmb, mmb = batch_pad(xsubseq, nsubseq, nsteps)
                for batch in range(0, nsubseq, nbatch):
                    start = batch
                    end = batch+nbatch
                    batch_smb = seq_rep(
                        xmb[start:end], mmb[start:end],
                        smb[:, offset+start:offset+end, :])
                    smb[:, offset+start:offset+end, :] = batch_smb
            features = smb[0, unsort_idxs, :]
            print('%0.3f seconds to transform %d examples' %
                  (time.time() - tstart, n))
            return features
```

This is just a snippet of the full code (I don't think it's OK to copy the entire code here).

答:
The part you're referring to is not the place that splits the computation across GPUs, it only transforms the data (on a CPU!) and runs the session.

The correct place is one that defines the computational graph, e.g. mlstm method. There are many ways to split graph, e.g. place LSTM cells on different GPUs, so that the input sequence can be processed in parallel:

def mlstm(inputs, c, h, M, ndim, scope='lstm', wn=False):
  [...]
  for idx, x in enumerate(inputs):
    with tf.device('/gpu:' + str(i % GPU_COUNT)):
      m = tf.matmul(x, wmx) * tf.matmul(h, wmh)
      z = tf.matmul(x, wx) + tf.matmul(m, wh) + b
      [...]
```

<p>By the way, there is a useful config option in tensorflow <code>log_device_placement</code> that helps to see the execution details in the output. Here's an example:</p>

<pre class="lang-py prettyprint-override"><code>import tensorflow as tf

# Creates a graph.
with tf.device('/gpu:0'):
 a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], name='a')
 b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], name='b')
 c = tf.add(a, b)

# Creates a session with log_device_placement set to True.
with tf.Session(config=tf.ConfigProto(log_device_placement=True)) as sess:
  # Prints the following:
  # Device mapping:
  # /job:localhost/replica:0/task:0/device:GPU:0 -> device: 0, name: <GPU name>, pci bus id: 0000:01:00.0, compute capability: 6.1
  # Add: (Add): /job:localhost/replica:0/task:0/device:GPU:0
  # b: (Const): /job:localhost/replica:0/task:0/device:GPU:0
  # a: (Const): /job:localhost/replica:0/task:0/device:GPU:0
  print(sess.run(c))
</code>```

Body:
I'm running an mLSTM (multiplicative LSTM) transform (based on mLSTM by OpenAi (just the transform, it is already trained) but it takes a really long time to transform more than ~100,000 docs.

I want it to run on multiple GPUs. I saw some examples but I have no idea how to implement it on this mLSTM transform code.

The specific part that I want to run on multiple GPUs is:

        def transform(xs):
            tstart = time.time()
            xs = [preprocess(x) for x in xs]
            lens = np.asarray([len(x) for x in xs])
            sorted_idxs = np.argsort(lens)
            unsort_idxs = np.argsort(sorted_idxs)
            sorted_xs = [xs[i] for i in sorted_idxs]
            maxlen = np.max(lens)
            offset = 0
            n = len(xs)
            smb = np.zeros((2, n, hps.nhidden), dtype=np.float32)
            for step in range(0, ceil_round_step(maxlen, nsteps), nsteps):
                start = step
                end = step+nsteps
                xsubseq = [x[start:end] for x in sorted_xs]
                ndone = sum([x == b'' for x in xsubseq])
                offset += ndone
                xsubseq = xsubseq[ndone:]
                sorted_xs = sorted_xs[ndone:]
                nsubseq = len(xsubseq)
                xmb, mmb = batch_pad(xsubseq, nsubseq, nsteps)
                for batch in range(0, nsubseq, nbatch):
                    start = batch
                    end = batch+nbatch
                    batch_smb = seq_rep(
                        xmb[start:end], mmb[start:end],
                        smb[:, offset+start:offset+end, :])
                    smb[:, offset+start:offset+end, :] = batch_smb
            features = smb[0, unsort_idxs, :]
            print('%0.3f seconds to transform %d examples' %
                  (time.time() - tstart, n))
            return features

This is just a snippet of the full code (I don't think it's OK to copy the entire code here).

Body:
The part you're referring to is not the place that splits the computation across GPUs, it only transforms the data (on a CPU!) and runs the session.

The correct place is one that defines the computational graph, e.g. mlstm method. There are many ways to split graph, e.g. place LSTM cells on different GPUs, so that the input sequence can be processed in parallel:

def mlstm(inputs, c, h, M, ndim, scope='lstm', wn=False):
  [...]
  for idx, x in enumerate(inputs):
    with tf.device('/gpu:' + str(i % GPU_COUNT)):
      m = tf.matmul(x, wmx) * tf.matmul(h, wmh)
      z = tf.matmul(x, wx) + tf.matmul(m, wh) + b
      [...]

By the way, there is a useful config option in tensorflow log_device_placement that helps to see the execution details in the output. Here's an example:

import tensorflow as tf

# Creates a graph.
with tf.device('/gpu:0'):
 a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], name='a')
 b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], name='b')
 c = tf.add(a, b)

# Creates a session with log_device_placement set to True.
with tf.Session(config=tf.ConfigProto(log_device_placement=True)) as sess:
  # Prints the following:
  # Device mapping:
  # /job:localhost/replica:0/task:0/device:GPU:0 -> device: 0, name: <GPU name>, pci bus id: 0000:01:00.0, compute capability: 6.1
  # Add: (Add): /job:localhost/replica:0/task:0/device:GPU:0
  # b: (Const): /job:localhost/replica:0/task:0/device:GPU:0
  # a: (Const): /job:localhost/replica:0/task:0/device:GPU:0
  print(sess.run(c))


问:
Is it possible to generate new lat-lng using lat-lng & distance (Reverse to calculate distance between 2 lat-lng)
I am receiving data like below from BLE devices.

```<code>"payload": [
        {
            "r": -90,
            "t": "1970-01-18T10:30:17.823Z"
        },
        {
            "r": -80,
            "t": "1970-01-18T10:30:17.833Z"
        },
        {
            "r": -70,
            "t": "1970-01-18T10:30:17.843Z"
        }
    ]
</code>```

r is rssi. we will assuming a distance out of these numbers(rssi). I have lat-lng of BLE device.

We can calculate distance between two lat-lng using mathematical formula. I want reverse formula.

So if i have one lat-lng & a distance. Can i calculate next point(lat-lng) using distance & starting point(lat-lng). Direction does not matter.

So basically what i want is formula like lat2-lng2 = lat1-lng1 (some formula) distance like below

```<code>function(lat1, lng1, distance){
    /////some calculaitons to calculate lat2 & lng2
    return {'lat2' :lat2, 'lng2' : lng2};
}
</code>```

答:
with Google Maps JavaScript API, you could use the computeOffset function, which accepts an initial position, distance, and heading determining the direction of the displacement. For example

```<code>    var ret = google.maps.geometry.spherical.computeOffset(
        new google.maps.LatLng(0, 0), 1000, 0);

    console.log(ret.lat(), ret.lng());
</code>```

This should return a position with zero longitude and latitude corresponding to 1/R radians (R representing the radius of Earth within the spherical model)

Alternatively, you could implement the formula directly: http://www.edwilliams.org/avform.htm#LL

Body:
I am receiving data like below from BLE devices.

"payload": [
        {
            "r": -90,
            "t": "1970-01-18T10:30:17.823Z"
        },
        {
            "r": -80,
            "t": "1970-01-18T10:30:17.833Z"
        },
        {
            "r": -70,
            "t": "1970-01-18T10:30:17.843Z"
        }
    ]

r is rssi. we will assuming a distance out of these numbers(rssi). I have lat-lng of BLE device.

We can calculate distance between two lat-lng using mathematical formula. I want reverse formula.

So if i have one lat-lng & a distance. Can i calculate next point(lat-lng) using distance & starting point(lat-lng). Direction does not matter.

So basically what i want is formula like lat2-lng2 = lat1-lng1 (some formula) distance like below

function(lat1, lng1, distance){
    /////some calculaitons to calculate lat2 & lng2
    return {'lat2' :lat2, 'lng2' : lng2};
}

Body:
with Google Maps JavaScript API, you could use the computeOffset function, which accepts an initial position, distance, and heading determining the direction of the displacement. For example

    var ret = google.maps.geometry.spherical.computeOffset(
        new google.maps.LatLng(0, 0), 1000, 0);

    console.log(ret.lat(), ret.lng());

This should return a position with zero longitude and latitude corresponding to 1/R radians (R representing the radius of Earth within the spherical model)

Alternatively, you could implement the formula directly: http://www.edwilliams.org/avform.htm#LL


问:
highchart donut - click on slice opens page by searching from userService
I have a donut pie chart. on click of legend item it navigates to particular page which it retrieves from userSevice like given below -

pic of user service]1

legendItemClick:

```<code>function(e) { debugger;
    this.userService.search(e.target.id);
    return false;
}.bind(this)
</code>```

i am looking for same functionality when i click on the pie slices of the chart it should navigate to particular related page. i tried this below but was not successful -

```<code>point: {
    events: {
        click: function(e){
            this.userService.search(e.target.id);
            return false;
        }.bind(this)
    }
}
</code>```

any help where Iam going wrong ?

userService -

```<code>  search(id: any) {
        let headers = new Headers();

        let data = { "jql": id };
        let body = JSON.stringify(data);
        let http: Http
       var method = method || "post";
        var params;
        var path ;
        path = ' http://imptdg/IMR/Ticket/DashBoard';
                var form = document.createElement("form");
                form.setAttribute("method", method);
                form.setAttribute("action", path);
                        var hiddenField = document.createElement("input");
                        hiddenField.setAttribute("type", "hidden");
                        hiddenField.setAttribute("name", 'jql');
                        hiddenField.setAttribute("value", id);
                        form.appendChild(hiddenField);
                document.body.appendChild(form); debugger;
                form.submit();

    }

defaults() {
    this.options = {

        title: { text: ' ' },
        colors: ['rgba(79, 162, 189, 1)', 'rgba(84, 135, 201, 1)', 'rgba(143, 185, 91, 1)', 'rgba(90, 183, 130, 1)', 'rgba(71, 195, 185, 1)', 'rgba(190, 120, 203, 1)', 'rgba(228, 211, 84, 1)', 'rgba(43, 144, 143, 1)', 'rgba(145, 232, 225, 1)'],
        chart: {
            type: 'pie',
            animation: true
        },
        credits: {
            enabled: false
        },
        responsive: {
            rules: [{
                condition: {
                    maxWidth: 300
                },
                chartOptions: {
                    legend: {
                        align: 'center',
                        verticalAlign: 'bottom',
                        layout: 'vertical',
                        labelFormatter: function () {
                            return '<div style="width:180px"><span class="pull-left" style= "font-weight: 500; padding-bottom: 5px; font-family:Helvetica ">' + this.name +
                                '</span><span class="pull-right" style= "font-weight: 500" >' + this.value +
                                '</span></div> ';
                        }
                    },
                    pie: {
                        size: 50,
                        innerSize: 20
                    }
                }
            }]
        },

        plotOptions: {
            pie: {
                innerSize: '40%',
                allowPointSelect: true,
                slicedOffset: 0,
                cursor: 'pointer',
                dataLabels: {
                    enabled: false
                },

                showInLegend: true,
                 point: {
                    events: {
                        click:function(e){
                            this.userService.search(e.target.id); // this part not working
                            return false;
                        }.bind(this),

                        legendItemClick: function (e) {

                            this.userService.search(e.target.id);
                            return false;
                        }.bind(this),

                    }

                    },
                states: {
                    hover: {
                        halo: {
                            size: 0
                        },
                        enabled : true
                    }
                }
            },

            series: {
                animation: false,

                }

                },

        },

        legend: {
            useHTML: true,
            enabled: true,
            align: 'right',
            verticalAlign: 'top',
            layout: 'vertical',
            symbolHeight: 12,
            itemMarginBottom: 1,
            symbolWidth: 25,
            symbolRadius: 1,
            labelFormatter: function () {
                return '<div style="width:180px;"><div class="pull-left" style= "font-weight: 500; padding-bottom: 3px;padding-top:3px;  width: 130px; font-family:Helvetica; white-space: normal; word-break:break-word ">' + this.name

            },

            },
        },

        series: [{
            data: this.donutchartData,
            allowPointSelect: true
        }]
    };

}
</code>```

}

答:
it is working now, i have gone through the api documentation of highchart donut - https://api.highcharts.com/highcharts/plotOptions.pie.events.click. now it is navigating and taing me to proper page that i was looking for.     </p>

```<code>point: {
                            events: {
                                click:function(e){

                                    this.userService.search(e.point.id);

                                }.bind(this)
</code>```

Body:
I have a donut pie chart. on click of legend item it navigates to particular page which it retrieves from userSevice like given below -

pic of user service]1

legendItemClick:

function(e) { debugger;
    this.userService.search(e.target.id);
    return false;
}.bind(this)

i am looking for same functionality when i click on the pie slices of the chart it should navigate to particular related page. i tried this below but was not successful -

point: {
    events: {
        click: function(e){
            this.userService.search(e.target.id);
            return false;
        }.bind(this)
    }
}

any help where Iam going wrong ?

userService -

  search(id: any) {
        let headers = new Headers();

        let data = { "jql": id };
        let body = JSON.stringify(data);
        let http: Http
       var method = method || "post";
        var params;
        var path ;
        path = ' http://imptdg/IMR/Ticket/DashBoard';
                var form = document.createElement("form");
                form.setAttribute("method", method);
                form.setAttribute("action", path);
                        var hiddenField = document.createElement("input");
                        hiddenField.setAttribute("type", "hidden");
                        hiddenField.setAttribute("name", 'jql');
                        hiddenField.setAttribute("value", id);
                        form.appendChild(hiddenField);
                document.body.appendChild(form); debugger;
                form.submit();

    }

defaults() {
    this.options = {

        title: { text: ' ' },
        colors: ['rgba(79, 162, 189, 1)', 'rgba(84, 135, 201, 1)', 'rgba(143, 185, 91, 1)', 'rgba(90, 183, 130, 1)', 'rgba(71, 195, 185, 1)', 'rgba(190, 120, 203, 1)', 'rgba(228, 211, 84, 1)', 'rgba(43, 144, 143, 1)', 'rgba(145, 232, 225, 1)'],
        chart: {
            type: 'pie',
            animation: true
        },
        credits: {
            enabled: false
        },
        responsive: {
            rules: [{
                condition: {
                    maxWidth: 300
                },
                chartOptions: {
                    legend: {
                        align: 'center',
                        verticalAlign: 'bottom',
                        layout: 'vertical',
                        labelFormatter: function () {
                            return '
' + this.name +
                                '' + this.value +
                                '
 ';
                        }
                    },
                    pie: {
                        size: 50,
                        innerSize: 20
                    }
                }
            }]
        },

        plotOptions: {
            pie: {
                innerSize: '40%',
                allowPointSelect: true,
                slicedOffset: 0,
                cursor: 'pointer',
                dataLabels: {
                    enabled: false
                },

                showInLegend: true,
                 point: {
                    events: {
                        click:function(e){
                            this.userService.search(e.target.id); // this part not working
                            return false;
                        }.bind(this),

                        legendItemClick: function (e) {

                            this.userService.search(e.target.id);
                            return false;
                        }.bind(this),

                    }

                    },
                states: {
                    hover: {
                        halo: {
                            size: 0
                        },
                        enabled : true
                    }
                }
            },

            series: {
                animation: false,

                }

                },

        },

        legend: {
            useHTML: true,
            enabled: true,
            align: 'right',
            verticalAlign: 'top',
            layout: 'vertical',
            symbolHeight: 12,
            itemMarginBottom: 1,
            symbolWidth: 25,
            symbolRadius: 1,
            labelFormatter: function () {
                return '

' + this.name

            },

            },
        },

        series: [{
            data: this.donutchartData,
            allowPointSelect: true
        }]
    };

}

}

Body:
it is working now, i have gone through the api documentation of highchart donut - https://api.highcharts.com/highcharts/plotOptions.pie.events.click. now it is navigating and taing me to proper page that i was looking for.

point: {
                            events: {
                                click:function(e){

                                    this.userService.search(e.point.id);

                                }.bind(this)


问:
processing a file after a string has been matched in it
I have a json file I am doing some processing on, I had to pause the operation and I want to start the processing again where I left, this is the code I am using, the problem is the If condition still executes even if the While loops condition isn't met, from my understanding the code should be unreachable until the While loop doesn't meet it's condition. Where am I going wrong?</p>

```<code>row_counter = 0
start_now = 0
Finished = 0
with open('jsonfile') as f:
    for row in f:
        row_counter += 1
        if row_counter > start_now:
            try:
                row = json.loads(row)
                comment_id = row['id']

                while Finished == 0:
                    if (comment_id != 'The_String_I_Wanna_Match'):
                        Finished = True
                        break

                if (condition):
                    print('code i want to execute')
            except Exception as e:
                print(e)
        if (row_counter % 100000 == 0):
            print('no. of rows gone by {}'.format(row_counter))
</code>```

答:
So I'm not exactly sure what you're trying to do here since you posted mostly pseudo code but you definitely don't want to use a while loop. A while loop there will lock your program if the first line happens to match the string you're looking for forever (unless you're running multi-threaded but you don't seem to be). I also think you're using the wrong conditional operator there but as I said, not 100% sure what you're going for here.

This is what I think you're going to need:

```<code>import json

row_counter = 0
start_now = 0

with open('file.json') as f:
  for row in f:
    row_counter += 1
    if row_counter > start_now:
      try:
        # check to ensure we're not messing with a blank row
        if not row: continue

        # load the row. This line might throw an exception if the
        # line isn't perfect json
        row = json.loads(row)
        print(row)
        comment_id = row['id']

        if(comment_id == 'The_String_I_Wanna_Match'):
          print('Execute code here')

      except Exception as e:
        import traceback
        print(traceback.print_exc())
    if (row_counter % 100000 == 0):
      print('no. of rows gone by {}'.format(row_counter))
</code>```

Body:
I have a json file I am doing some processing on, I had to pause the operation and I want to start the processing again where I left, this is the code I am using, the problem is the If condition still executes even if the While loops condition isn't met, from my understanding the code should be unreachable until the While loop doesn't meet it's condition. Where am I going wrong?

row_counter = 0
start_now = 0
Finished = 0
with open('jsonfile') as f:
    for row in f:
        row_counter += 1
        if row_counter > start_now:
            try:
                row = json.loads(row)
                comment_id = row['id']

                while Finished == 0:
                    if (comment_id != 'The_String_I_Wanna_Match'):
                        Finished = True
                        break

                if (condition):
                    print('code i want to execute')
            except Exception as e:
                print(e)
        if (row_counter % 100000 == 0):
            print('no. of rows gone by {}'.format(row_counter))

Body:
So I'm not exactly sure what you're trying to do here since you posted mostly pseudo code but you definitely don't want to use a while loop. A while loop there will lock your program if the first line happens to match the string you're looking for forever (unless you're running multi-threaded but you don't seem to be). I also think you're using the wrong conditional operator there but as I said, not 100% sure what you're going for here.

This is what I think you're going to need:

import json

row_counter = 0
start_now = 0

with open('file.json') as f:
  for row in f:
    row_counter += 1
    if row_counter > start_now:
      try:
        # check to ensure we're not messing with a blank row
        if not row: continue

        # load the row. This line might throw an exception if the
        # line isn't perfect json
        row = json.loads(row)
        print(row)
        comment_id = row['id']

        if(comment_id == 'The_String_I_Wanna_Match'):
          print('Execute code here')

      except Exception as e:
        import traceback
        print(traceback.print_exc())
    if (row_counter % 100000 == 0):
      print('no. of rows gone by {}'.format(row_counter))


问:
Is there a way to execute this code using a For Loop, just curious?
This code removes the space between names and inserts a comma. I am curious to know if there is a way to execute the same code using a For Loop in replace of "Split". I remember doing something similar but not enough to actually do it.

function cutName (name) {
    return name.split(' ');
}

alert(cutName("Amjad Ali"));```

答:
Agree with the comments that what you are asking seems a bit weird, but here you go:

function cutName(name) {
  let result = "";
  for (let i = 0; i < name.length; i++) {
    if (name[i] === " ") result += ",";
    else result += name[i];
  }
  return result;
}

alert(cutName("Amjad Ali"));```
</div>
</div>
</p>

<p>This doesn't return an array as <code>split()</code> does, but the stringified result is the same (which appears to be what you are after).</p>

<hr>

<p>If you <em>do</em> want an array, just like <code>split()</code>, try this instead:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function cutName (name) {
    let result = [];
    let lastIndex = 0;
    for(let i=0; i<name.length; i++) {
     if(name[i] === " ") {
       result.push(name.substring(lastIndex, i));
        lastIndex = i+1;
      }
    }
    result.push(name.substring(lastIndex, name.length))
    return result;
}

console.log(cutName("Amjad Ali"));</code>```

Body:
Agree with the comments that what you are asking seems a bit weird, but here you go:

function cutName(name) {
  let result = "";
  for (let i = 0; i < name.length; i++) {
    if (name[i] === " ") result += ",";
    else result += name[i];
  }
  return result;
}

alert(cutName("Amjad Ali"));

This doesn't return an array as split() does, but the stringified result is the same (which appears to be what you are after).

If you do want an array, just like split(), try this instead:

function cutName (name) {
    let result = [];
    let lastIndex = 0;
    for(let i=0; i<name.length; i++) {
     if(name[i] === " ") {
       result.push(name.substring(lastIndex, i));
        lastIndex = i+1;
      }
    }
    result.push(name.substring(lastIndex, name.length))
    return result;
}

console.log(cutName("Amjad Ali"));


问:
PyTorch ValueError: Target and input must have the same number of elements
I am kinda new to PyTorch, but I am trying to understand how the sizes of target and input work in torch.nn.BCELoss() when computing loss function.

```<code>import torch
import torch.nn as nn
from torch.autograd import Variable

time_steps = 15
batch_size = 3
embeddings_size = 100
num_classes = 2

model = nn.LSTM(embeddings_size, num_classes)
input_seq = Variable(torch.randn(time_steps, batch_size, embeddings_size))
lstm_out, _ = model(input_seq)
last_out = lstm_out[-1]
print(last_out)

loss = nn.BCELoss()
target = Variable(torch.LongTensor(batch_size).random_(0, num_classes))
print(target)
err = loss(last_out.long(), target)
err.backward()
</code>```

I received the following error:

```<code>Warning (from warnings module):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/torch/nn/functional.py", line 767
"Please ensure they have the same size.".format(target.size(), input.size()))

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/torch/nn/functional.py", line 770, in binary_cross_entropy
"!= input nelement ({})".format(target.nelement(), input.nelement()))
ValueError: Target and input must have the same number of elements. target nelement (3) != input nelement (6)
</code>```

This error definitely comes from the different sizes of last_out (size 3x2) and target (size 3). So my question is how can I convert last_out into something like target (of size 3 and containing just 0s and 1s) to compute loss function?

答:
The idea of nn.BCELoss() is to implement the following formula:

Both o and tare tensors of arbitrary (but same!) size and i simply indexes each element of the two tensor to compute the sum above.

Typically, nn.BCELoss() is used in a classification setting: o and i will be matrices of dimensions N x D. N will be the number of observations in your dataset or minibatch. D will be 1 if you are only trying to classify a single property, and larger than 1 if you are trying to classify multiple properties. t, the target matrix, will only hold 0 and 1, as for every property, there are only two classes (that's where the binary in binary cross entropy loss comes from). o will hold the probability with which you assign every property of every observation to class 1.

Now in your setting above, it is not clear how many classes you are considering and how many properties there are for you. If there is only one property as suggested by the shape of your target, you should only output a single quantity, namely the probability of being in class 1 from your model. If there are two properties, your targets are incomplete! If there are multiple classes, you should work with torch.nn.CrossEntropyLossinstead of torch.nn.BCELoss().

As an aside, often it is desirable for the sake of numerical stability to use torch.nn.BCEWithLogitsLossinstead of torch.nn.BCELoss() following nn.Sigmoid() on some outputs.

Body:
I am kinda new to PyTorch, but I am trying to understand how the sizes of target and input work in torch.nn.BCELoss() when computing loss function.

import torch
import torch.nn as nn
from torch.autograd import Variable

time_steps = 15
batch_size = 3
embeddings_size = 100
num_classes = 2

model = nn.LSTM(embeddings_size, num_classes)
input_seq = Variable(torch.randn(time_steps, batch_size, embeddings_size))
lstm_out, _ = model(input_seq)
last_out = lstm_out[-1]
print(last_out)

loss = nn.BCELoss()
target = Variable(torch.LongTensor(batch_size).random_(0, num_classes))
print(target)
err = loss(last_out.long(), target)
err.backward()

I received the following error:

Warning (from warnings module):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/torch/nn/functional.py", line 767
"Please ensure they have the same size.".format(target.size(), input.size()))

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/torch/nn/functional.py", line 770, in binary_cross_entropy
"!= input nelement ({})".format(target.nelement(), input.nelement()))
ValueError: Target and input must have the same number of elements. target nelement (3) != input nelement (6)

This error definitely comes from the different sizes of last_out (size 3x2) and target (size 3). So my question is how can I convert last_out into something like target (of size 3 and containing just 0s and 1s) to compute loss function?


问:
Wordpress, how to start with an empty theme?
I have been working on Wordpress for a month creating themes. Otherwise, when I'm starting a new project, I'm always starting with an existing theme that I am modifying.

What I want, is to clean perfectly a theme and add to it what I need for the website.

But, my Wordpress knowledge aren't enough to do it. So, I'm asking you if you know a great book, website etc, where they are explaining simply how to create a new theme (understand every features of Wordpress, explaining every functions in the functions.php file, how to add  correctly Wordpress post content).

Thanks

答:
You can make WordPress themes from the scratch by following some methods

By using Youtube, but that'll be not very professional

By using Google, yes you will find many sites that will show you the process and this is efficient and free

By using Udemy or Lynda, you will learn about the whole process with the necessary knowledge like the hierarchy of wordpress, tools & standards for wordpress etc.

By using wordpress.org, this is most desirable and professional way of learning wordpress as this is the main place for all the things happening around the WordPress.


问:
PHP Session string limit
Is there a length limit to a string that can be placed into $_SESSION with PHP?

Thanks

答:
It depends on the session_save_handler used. For the default one, there is in theory no limit (or a very, very high one, dictated by the file system), because session data is saved in files.

Seeing as session data is imported on every request, however, there is an effective limit imposed by the maximum amount of memory the script is allowed to occupy. It is wise not to store more than a few kilobytes in there.

If you need to save large chunks of data, store it in temporary files (named after the current session) instead.

Title: PHP Session string limit


问:
Paging in Cassandra with spring-boot-data
How is it possible to page through retrieved rows with spring-boot-data? I am aware of the documentation from Datastax:

https://docs.datastax.com/en/developer/java-driver/3.1/manual/paging/

My repository interface:

```<code>public interface DeviceRepository extends CassandraRepository<Device> {
    Device findByFieldDeviceId(String fieldDeviceId);
}
</code>```

My Service class:

```<code>public Device findByFieldDeviceId(final String fieldDeviceId) {
    return deviceRepository.findByFieldDeviceId(fieldDeviceId);
}
</code>```

My Pom:

```<code>    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-cassandra</artifactId>
        <version>1.5.8.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-cassandra</artifactId>
        <version>1.5.8.RELEASE</version>
    </dependency>
</code>```

I dont see how i can extract and set the paging state from the result.

答:
Spring-data-cassandra 2.0 GA (Kay) release supports for pagination with Cassandra.

check the PR for sample code https://github.com/spring-projects/spring-data-cassandra/pull/114

Body:
How is it possible to page through retrieved rows with spring-boot-data? I am aware of the documentation from Datastax:

https://docs.datastax.com/en/developer/java-driver/3.1/manual/paging/

My repository interface:

public interface DeviceRepository extends CassandraRepository<Device> {
    Device findByFieldDeviceId(String fieldDeviceId);
}

My Service class:

public Device findByFieldDeviceId(final String fieldDeviceId) {
    return deviceRepository.findByFieldDeviceId(fieldDeviceId);
}

My Pom:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-cassandra</artifactId>
        <version>1.5.8.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-cassandra</artifactId>
        <version>1.5.8.RELEASE</version>
    </dependency>

I dont see how i can extract and set the paging state from the result.


问:
Update an email with ContactsContract when the contact doesn't have
I want to update the mail address of a contact, it seem working but I the case who the contact have not a mail address it's not working and I have this error :

```<code>#################################################################
W/System.err: Error Code : 0 (SQLITE_OK)
W/System.err: Caused By : unknown error (code 0): Unable to convert BLOB to string
#################################################################
</code>```

This is my function updateMail() :

```<code>public static boolean updateMail(Context context, String id, String email){
        ContentProviderOperation.Builder builder = ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI);
        ArrayList<ContentProviderOperation> ops = new ArrayList<>();

        builder.withSelection(ContactsContract.Data.CONTACT_ID + "=? " + "AND "
                        + ContactsContract.CommonDataKinds.Organization.TYPE + "=?"
                , new String[]{id,
                        String.valueOf(ContactsContract.CommonDataKinds.Email.TYPE_HOME)});
        builder.withValue(ContactsContract.CommonDataKinds.Email.ADDRESS, email);
        ops.add(builder.build());

        return (applyBatch(context, ops));
    }
</code>```

Maybe I have to make an insert and not an update when the contact doesn't have mail address, what do you think ?

EDIT :

I try this but it's not working... Maybe I don't make a correct selection using the insert :

```<code>public static boolean updateMail(Context context, String id, String email){
        ContentProviderOperation.Builder builder;
        ArrayList<ContentProviderOperation> ops = new ArrayList<>();

        if (getMailById(context, id).isEmpty()){

            builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);

            builder.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, Integer.valueOf(id));
            builder.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
            builder.withValue(ContactsContract.CommonDataKinds.Email.ADDRESS, email);
            builder.withValue(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_HOME);
            ops.add(builder.build());

        } else {

            builder = ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI);

            builder.withSelection(ContactsContract.Data.CONTACT_ID + "=? " + "AND "
                            + ContactsContract.CommonDataKinds.Organization.TYPE + "=?"
                    , new String[]{id,
                            String.valueOf(ContactsContract.CommonDataKinds.Email.TYPE_HOME)});
            builder.withValue(ContactsContract.CommonDataKinds.Email.ADDRESS, email);
            ops.add(builder.build());

        }

        return (applyBatch(context, ops));
    }
</code>```

答:
I found a solution, I have to use ContactsContract.Data.RAW_CONTACT_ID :

```<code>public static boolean updateMail(Context context, String id, String email){
        ContentProviderOperation.Builder builder;
        ArrayList<ContentProviderOperation> ops = new ArrayList<>();

        if (getMailById(context, id).isEmpty()){
            builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
            builder.withValue(ContactsContract.Data.RAW_CONTACT_ID, getRawId(context, Long.parseLong(id)));
            builder.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
            builder.withValue(ContactsContract.CommonDataKinds.Email.ADDRESS, email);
            ops.add(builder.build());
        } else {
            builder = ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI);

            builder.withSelection(ContactsContract.Data.CONTACT_ID + "=? " + "AND "
                            + ContactsContract.CommonDataKinds.Organization.TYPE + "=?"
                    , new String[]{id,
                            String.valueOf(ContactsContract.CommonDataKinds.Email.TYPE_HOME)});
            builder.withValue(ContactsContract.CommonDataKinds.Email.ADDRESS, email);
            ops.add(builder.build());

        }

        return (applyBatch(context, ops));
    }
</code>```

And the method getRawId() :

```<code>private static long getRawId(Context context, long contactId) {
        String selection = ContactsContract.RawContacts.CONTACT_ID + "='" + contactId + "'";
        try (Cursor cur = context.getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI, new String[]{ContactsContract.RawContacts._ID}, selection, null, null)) {
            assert cur != null;
            if (cur.moveToNext()) { return cur.getLong(0);}
        }
        return 0;
    }
</code>```

Body:
I want to update the mail address of a contact, it seem working but I the case who the contact have not a mail address it's not working and I have this error :

#################################################################
W/System.err: Error Code : 0 (SQLITE_OK)
W/System.err: Caused By : unknown error (code 0): Unable to convert BLOB to string
#################################################################

This is my function updateMail() :

public static boolean updateMail(Context context, String id, String email){
        ContentProviderOperation.Builder builder = ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI);
        ArrayList<ContentProviderOperation> ops = new ArrayList<>();

        builder.withSelection(ContactsContract.Data.CONTACT_ID + "=? " + "AND "
                        + ContactsContract.CommonDataKinds.Organization.TYPE + "=?"
                , new String[]{id,
                        String.valueOf(ContactsContract.CommonDataKinds.Email.TYPE_HOME)});
        builder.withValue(ContactsContract.CommonDataKinds.Email.ADDRESS, email);
        ops.add(builder.build());

        return (applyBatch(context, ops));
    }

Maybe I have to make an insert and not an update when the contact doesn't have mail address, what do you think ?

EDIT :

I try this but it's not working... Maybe I don't make a correct selection using the insert :

public static boolean updateMail(Context context, String id, String email){
        ContentProviderOperation.Builder builder;
        ArrayList<ContentProviderOperation> ops = new ArrayList<>();

        if (getMailById(context, id).isEmpty()){

            builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);

            builder.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, Integer.valueOf(id));
            builder.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
            builder.withValue(ContactsContract.CommonDataKinds.Email.ADDRESS, email);
            builder.withValue(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_HOME);
            ops.add(builder.build());

        } else {

            builder = ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI);

            builder.withSelection(ContactsContract.Data.CONTACT_ID + "=? " + "AND "
                            + ContactsContract.CommonDataKinds.Organization.TYPE + "=?"
                    , new String[]{id,
                            String.valueOf(ContactsContract.CommonDataKinds.Email.TYPE_HOME)});
            builder.withValue(ContactsContract.CommonDataKinds.Email.ADDRESS, email);
            ops.add(builder.build());

        }

        return (applyBatch(context, ops));
    }

Body:
I found a solution, I have to use ContactsContract.Data.RAW_CONTACT_ID :

public static boolean updateMail(Context context, String id, String email){
        ContentProviderOperation.Builder builder;
        ArrayList<ContentProviderOperation> ops = new ArrayList<>();

        if (getMailById(context, id).isEmpty()){
            builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
            builder.withValue(ContactsContract.Data.RAW_CONTACT_ID, getRawId(context, Long.parseLong(id)));
            builder.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
            builder.withValue(ContactsContract.CommonDataKinds.Email.ADDRESS, email);
            ops.add(builder.build());
        } else {
            builder = ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI);

            builder.withSelection(ContactsContract.Data.CONTACT_ID + "=? " + "AND "
                            + ContactsContract.CommonDataKinds.Organization.TYPE + "=?"
                    , new String[]{id,
                            String.valueOf(ContactsContract.CommonDataKinds.Email.TYPE_HOME)});
            builder.withValue(ContactsContract.CommonDataKinds.Email.ADDRESS, email);
            ops.add(builder.build());

        }

        return (applyBatch(context, ops));
    }

And the method getRawId() :

private static long getRawId(Context context, long contactId) {
        String selection = ContactsContract.RawContacts.CONTACT_ID + "='" + contactId + "'";
        try (Cursor cur = context.getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI, new String[]{ContactsContract.RawContacts._ID}, selection, null, null)) {
            assert cur != null;
            if (cur.moveToNext()) { return cur.getLong(0);}
        }
        return 0;
    }


问:
ViewPager and ListView Cache
I have a ViewPager with 4 ListViews.The list views all download unique Images and I want to cache them but there is an error and the app works very slow. Is there a way to  cache all images in 1 LruCache or something like that?
This is my code so far
first list Adapter

```<code>public class TwitchAdapter extends ArrayAdapter<Twitch>{
private Context context;
private int resourceId;
private ArrayList<Twitch> twitchList;
LruCache<Integer,Bitmap> logoCache;
LruCache<Integer,Bitmap> iconCache;
public TwitchAdapter(Context c, int resId, ArrayList<Twitch> objects){
    super(c, resId, objects);
    this.context = c;
    this.resourceId = resId;
    this.twitchList = objects;
    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
    iconCache = new LruCache<Integer, Bitmap>( maxMemory / 16);
    logoCache = new LruCache<Integer, Bitmap>( maxMemory / 64);
}
public View getView(final int position, View convertView, final ViewGroup parent){
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(resourceId, parent, false);
    final Twitch twitch = twitchList.get(position);

    TextView viewrs = (TextView) view.findViewById(R.id.viewers);
    TextView language = (TextView) view.findViewById(R.id.language);
    TextView status = (TextView) view.findViewById(R.id.streamer_status);
    TextView name = (TextView) view.findViewById(R.id.streamer_name);
    ImageView profile = (ImageView) view.findViewById(R.id.logo);
    CircleImageView imageView = (CircleImageView) view.findViewById(R.id.twitch_icon);
    int id = twitch.getId();
    status.setText(twitch.getStatus());
    language.setText(twitch.getLanguage());
    name.setText(twitch.getName());
    viewrs.setText(twitch.getViewrs()+"");
    Bitmap bitmapIcon = iconCache.get(id+1);
    if (bitmapIcon != null){

        imageView.setImageBitmap(bitmapIcon);
    }else {
        LoadImageTask(twitch,imageView);
    }
    Bitmap bitmapLogo = logoCache.get(twitch.getId());
    if (bitmapLogo != null){
        profile.setImageBitmap(bitmapLogo);
    }else {
        LoadIconTast(twitch,profile);
    }

    return view;
}

public void LoadImageTask(final Twitch twitch, final ImageView iconView){

        ImageRequest request  =new ImageRequest(twitch.getIconUrl(), new Response.Listener<Bitmap>() {
        @Override
        public void onResponse(Bitmap response) {
           iconView.setImageBitmap(response);
            iconCache.put(twitch.getId()+1,response);
        }
    }, 0, 0, null, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });
    RequestQueue quew = Volley.newRequestQueue(context);
    quew.add(request);

}
private void LoadIconTast(final Twitch twitch, final ImageView profileView) {
    ImageRequest request  =new ImageRequest(twitch.getLogoUrl(), new Response.Listener<Bitmap>() {
        @Override
        public void onResponse(Bitmap response) {
            profileView.setImageBitmap(response);
            iconCache.put(twitch.getId(),response);
            notifyDataSetChanged();
        }
    }, 0, 0, null, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });
    RequestQueue quew = Volley.newRequestQueue(context);
    quew.add(request);
}
</code>```

}

And another one exactly like this
and this is error

```<code>12-06 19:15:24.392 31970-2219/app.mma.introsliderproject E/AndroidRuntime: FATAL EXCEPTION: Thread-100374
                                                                       Process: app.mma.introsliderproject, PID: 31970
                                                                       java.lang.OutOfMemoryError: Failed to allocate a 17 byte allocation with 27048 free bytes and 26KB until OOM
                                                                           at com.android.volley.toolbox.DiskBasedCache.streamToBytes(DiskBasedCache.java:323)
                                                                           at com.android.volley.toolbox.DiskBasedCache.readString(DiskBasedCache.java:541)
                                                                           at com.android.volley.toolbox.DiskBasedCache.readStringStringMap(DiskBasedCache.java:564)
                                                                           at com.android.volley.toolbox.DiskBasedCache$CacheHeader.readHeader(DiskBasedCache.java:404)
                                                                           at com.android.volley.toolbox.DiskBasedCache.initialize(DiskBasedCache.java:157)
                                                                           at com.android.volley.CacheDispatcher.run(CacheDispatcher.java:84)
</code>```

答:
i wrote this and its working </p>

```<code>public class Cache  {
LruCache<Integer,Bitmap> logoCache = new LruCache<>((int) (Runtime.getRuntime().maxMemory()/1024/8));

public void setCache(int key, Bitmap bitmap){

    logoCache.put(key,bitmap);
}
public Bitmap getCache(int key){

    Bitmap bitmap = logoCache.get(key);
    return bitmap;
}
</code>```

Title: ViewPager and ListView Cache

Body:
I have a ViewPager with 4 ListViews.The list views all download unique Images and I want to cache them but there is an error and the app works very slow. Is there a way to  cache all images in 1 LruCache or something like that?
This is my code so far
first list Adapter

public class TwitchAdapter extends ArrayAdapter<Twitch>{
private Context context;
private int resourceId;
private ArrayList<Twitch> twitchList;
LruCache<Integer,Bitmap> logoCache;
LruCache<Integer,Bitmap> iconCache;
public TwitchAdapter(Context c, int resId, ArrayList<Twitch> objects){
    super(c, resId, objects);
    this.context = c;
    this.resourceId = resId;
    this.twitchList = objects;
    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
    iconCache = new LruCache<Integer, Bitmap>( maxMemory / 16);
    logoCache = new LruCache<Integer, Bitmap>( maxMemory / 64);
}
public View getView(final int position, View convertView, final ViewGroup parent){
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(resourceId, parent, false);
    final Twitch twitch = twitchList.get(position);

    TextView viewrs = (TextView) view.findViewById(R.id.viewers);
    TextView language = (TextView) view.findViewById(R.id.language);
    TextView status = (TextView) view.findViewById(R.id.streamer_status);
    TextView name = (TextView) view.findViewById(R.id.streamer_name);
    ImageView profile = (ImageView) view.findViewById(R.id.logo);
    CircleImageView imageView = (CircleImageView) view.findViewById(R.id.twitch_icon);
    int id = twitch.getId();
    status.setText(twitch.getStatus());
    language.setText(twitch.getLanguage());
    name.setText(twitch.getName());
    viewrs.setText(twitch.getViewrs()+"");
    Bitmap bitmapIcon = iconCache.get(id+1);
    if (bitmapIcon != null){

        imageView.setImageBitmap(bitmapIcon);
    }else {
        LoadImageTask(twitch,imageView);
    }
    Bitmap bitmapLogo = logoCache.get(twitch.getId());
    if (bitmapLogo != null){
        profile.setImageBitmap(bitmapLogo);
    }else {
        LoadIconTast(twitch,profile);
    }

    return view;
}

public void LoadImageTask(final Twitch twitch, final ImageView iconView){

        ImageRequest request  =new ImageRequest(twitch.getIconUrl(), new Response.Listener<Bitmap>() {
        @Override
        public void onResponse(Bitmap response) {
           iconView.setImageBitmap(response);
            iconCache.put(twitch.getId()+1,response);
        }
    }, 0, 0, null, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });
    RequestQueue quew = Volley.newRequestQueue(context);
    quew.add(request);

}
private void LoadIconTast(final Twitch twitch, final ImageView profileView) {
    ImageRequest request  =new ImageRequest(twitch.getLogoUrl(), new Response.Listener<Bitmap>() {
        @Override
        public void onResponse(Bitmap response) {
            profileView.setImageBitmap(response);
            iconCache.put(twitch.getId(),response);
            notifyDataSetChanged();
        }
    }, 0, 0, null, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });
    RequestQueue quew = Volley.newRequestQueue(context);
    quew.add(request);
}

}

And another one exactly like this
and this is error

12-06 19:15:24.392 31970-2219/app.mma.introsliderproject E/AndroidRuntime: FATAL EXCEPTION: Thread-100374
                                                                       Process: app.mma.introsliderproject, PID: 31970
                                                                       java.lang.OutOfMemoryError: Failed to allocate a 17 byte allocation with 27048 free bytes and 26KB until OOM
                                                                           at com.android.volley.toolbox.DiskBasedCache.streamToBytes(DiskBasedCache.java:323)
                                                                           at com.android.volley.toolbox.DiskBasedCache.readString(DiskBasedCache.java:541)
                                                                           at com.android.volley.toolbox.DiskBasedCache.readStringStringMap(DiskBasedCache.java:564)
                                                                           at com.android.volley.toolbox.DiskBasedCache$CacheHeader.readHeader(DiskBasedCache.java:404)
                                                                           at com.android.volley.toolbox.DiskBasedCache.initialize(DiskBasedCache.java:157)
                                                                           at com.android.volley.CacheDispatcher.run(CacheDispatcher.java:84)

Body:
i wrote this and its working

public class Cache  {
LruCache<Integer,Bitmap> logoCache = new LruCache<>((int) (Runtime.getRuntime().maxMemory()/1024/8));

public void setCache(int key, Bitmap bitmap){

    logoCache.put(key,bitmap);
}
public Bitmap getCache(int key){

    Bitmap bitmap = logoCache.get(key);
    return bitmap;
}


问:
Control the number of intermediate points between two vertices - Extension of Bresenham's algorithm
I have the following working Bresenham's algorithm,which finds intermediate points between two vertices.But this is for a pixel of size 1.

```<code>void Bresenham(int x1,
    int y1,
    int const x2,
    int const y2)
{
    int delta_x(x2 - x1);
    // if x1 == x2, then it does not matter what we set here
    signed char const ix((delta_x > 0) - (delta_x < 0));
    delta_x = std::abs(delta_x) << 1;

    int delta_y(y2 - y1);
    // if y1 == y2, then it does not matter what we set here
    signed char const iy((delta_y > 0) - (delta_y < 0));
    delta_y = std::abs(delta_y) << 1;

    cout << "(" << x1 << "," << y1 << ")\n";
    //plot(x1, y1);

    if (delta_x >= delta_y)
    {
        // error may go below zero
        int error(delta_y - (delta_x >> 1));

        while (x1 != x2)
        {
            // reduce error, while taking into account the corner case of error == 0
            if ((error > 0) || (!error && (ix > 0)))
            {
                error -= delta_x;
                y1 += iy;
            }
            // else do nothing

            error += delta_y;
            x1 += ix;

            cout << "(" << x1 << "," << y1 << ")\n";
            //plot(x1, y1);
        }
    }
    else
    {
        // error may go below zero
        int error(delta_x - (delta_y >> 1));

        while (y1 != y2)
        {
            // reduce error, while taking into account the corner case of error == 0
            if ((error > 0) || (!error && (iy > 0)))
            {
                error -= delta_y;
                x1 += ix;
            }
            // else do nothing

            error += delta_x;
            y1 += iy;

            cout << "(" << x1 << "," << y1 << ")\n";
            //plot(x1, y1);
        }
    }
}
</code>```

I want to control the number of intermediate points formed between the two given vertices.In the code above,I am not able to control it currently.

For e.g: If I have vertices (0,0) and (3,3); if I want 2 points in between,it would be (1,1) and (2,2).

Could you please suggest the changes to be done in my code so that I can control the number of intermediate points between given two vertices and also ,please let me know the way to determine the length of each pixel(as currently,the pixel size is fixed to be 1)

I want my overall function to look like : void Bresenham(int x1,
    int y1,
    int const x2,
    int const y2, int TotalIntermediatePoints)

Thanks in Advance!

答:
Seems you don't need Bresenham algo at all.

And intermediate points might have non-integer coordinates.

Just use linear interpolation

```<code> x[i] = x0 + (x1-x0) * i / (N + 1)
</code>```

Body:
I have the following working Bresenham's algorithm,which finds intermediate points between two vertices.But this is for a pixel of size 1.

void Bresenham(int x1,
    int y1,
    int const x2,
    int const y2)
{
    int delta_x(x2 - x1);
    // if x1 == x2, then it does not matter what we set here
    signed char const ix((delta_x > 0) - (delta_x < 0));
    delta_x = std::abs(delta_x) << 1;

    int delta_y(y2 - y1);
    // if y1 == y2, then it does not matter what we set here
    signed char const iy((delta_y > 0) - (delta_y < 0));
    delta_y = std::abs(delta_y) << 1;

    cout << "(" << x1 << "," << y1 << ")\n";
    //plot(x1, y1);

    if (delta_x >= delta_y)
    {
        // error may go below zero
        int error(delta_y - (delta_x >> 1));

        while (x1 != x2)
        {
            // reduce error, while taking into account the corner case of error == 0
            if ((error > 0) || (!error && (ix > 0)))
            {
                error -= delta_x;
                y1 += iy;
            }
            // else do nothing

            error += delta_y;
            x1 += ix;

            cout << "(" << x1 << "," << y1 << ")\n";
            //plot(x1, y1);
        }
    }
    else
    {
        // error may go below zero
        int error(delta_x - (delta_y >> 1));

        while (y1 != y2)
        {
            // reduce error, while taking into account the corner case of error == 0
            if ((error > 0) || (!error && (iy > 0)))
            {
                error -= delta_y;
                x1 += ix;
            }
            // else do nothing

            error += delta_x;
            y1 += iy;

            cout << "(" << x1 << "," << y1 << ")\n";
            //plot(x1, y1);
        }
    }
}

I want to control the number of intermediate points formed between the two given vertices.In the code above,I am not able to control it currently.

For e.g: If I have vertices (0,0) and (3,3); if I want 2 points in between,it would be (1,1) and (2,2).

Could you please suggest the changes to be done in my code so that I can control the number of intermediate points between given two vertices and also ,please let me know the way to determine the length of each pixel(as currently,the pixel size is fixed to be 1)

I want my overall function to look like : void Bresenham(int x1,
    int y1,
    int const x2,
    int const y2, int TotalIntermediatePoints)

Thanks in Advance!

Body:
Seems you don't need Bresenham algo at all.

And intermediate points might have non-integer coordinates.

Just use linear interpolation

 x[i] = x0 + (x1-x0) * i / (N + 1)


问:
convert orderdate of format m/d/yy to YYYY-MM-DD in R
My orderdate is in factor and i want to convert it into from mm/dd/yy format to YYYY-MM-DD format.

```<code> orderdate : Factor w/ 155932 levels "1/1/2017 1:05:00 AM",..: 41 1 1 89 100 102 106 107 119 122 ...
</code>```

I tried couple of things:

```<code>orders2017$newdate <- (factor(orders2017$orderdate))
orders2017$newdate1 <- as.Date(orders2017$newdate,format="%Y-%m-%d")
</code>```

but nothing is working out and giving me new columns as empty. Any help is appreciated

答:
You were really close with as.Date(orders2017$newdate,format="%Y-%m-%d"), you just need to make the format string match your actual format.

Your actual format is mm/dd/YYYY, so use %m/%d/%Y as the format string:

```<code>as.Date("1/1/2017 1:05:00 AM", format = "%m/%d/%Y")
# [1] "2017-01-01"
</code>```

Then the default printing of Date format objects is what you want.

So for your data,

```<code>orders2017$newdate1 <- as.Date(orders2017$newdate,format="%Y/%m/%d")
</code>```

The time part will just be ignored.

Body:
My orderdate is in factor and i want to convert it into from mm/dd/yy format to YYYY-MM-DD format.

 orderdate : Factor w/ 155932 levels "1/1/2017 1:05:00 AM",..: 41 1 1 89 100 102 106 107 119 122 ...

I tried couple of things:

orders2017$newdate <- (factor(orders2017$orderdate))
orders2017$newdate1 <- as.Date(orders2017$newdate,format="%Y-%m-%d")

but nothing is working out and giving me new columns as empty. Any help is appreciated

Body:
You were really close with as.Date(orders2017$newdate,format="%Y-%m-%d"), you just need to make the format string match your actual format.

Your actual format is mm/dd/YYYY, so use %m/%d/%Y as the format string:

as.Date("1/1/2017 1:05:00 AM", format = "%m/%d/%Y")
# [1] "2017-01-01"

Then the default printing of Date format objects is what you want.

So for your data,

orders2017$newdate1 <- as.Date(orders2017$newdate,format="%Y/%m/%d")

The time part will just be ignored.


问:
Mixed Language Programming, VB and C++, Understanding API and pointers
My problem is with understanding the finer point of mixed langage programming
and accessing API's in external libraries. My skills at C++ are nonexistent
and at VB, mediocre.

I have a c++ dll compiled (portaudio library), and am trying to access it from VB
(Visual Studio 2005).
I am getting MarshallDirectiveException errors when calling a function, I believe because
I am interacting incorrectly with the dll.

the C++ function and structures are defined as follows:

header info:

```<code>typedef int PaHostApiIndex;
...
typedef double PaTime;
...
typedef struct PaDeviceInfo
 {
     int structVersion;  /* this is struct version 2 */
     const char *name;
     PaHostApiIndex hostApi; /* note this is a host API index, not a type id*/
     int maxInputChannels;
     int maxOutputChannels;
     PaTime defaultLowInputLatency;
     PaTime defaultLowOutputLatency;
     PaTime defaultHighInputLatency;
     PaTime defaultHighOutputLatency;
     double defaultSampleRate;
 } PaDeviceInfo;
 ...
 const PaDeviceInfo* Pa_GetDeviceInfo( PaDeviceIndex device );
</code>```

program usage from docs:

```<code>const PaDeviceInfo* Pa_GetDeviceInfo    (   PaDeviceIndex   device   )
</code>```

Retrieve a pointer to a PaDeviceInfo structure containing information about the specified
device.

Returns:
A pointer to an immutable PaDeviceInfo structure. If the device parameter is out of range
the function returns NULL.

Parameters:
device  A valid device index in the range 0 to (Pa_GetDeviceCount()-1)

In the VB program I have:

```<code>Private Declare Function Pa_GetDeviceInfo Lib "portaudio_x86.dll" (ByVal dindex As Integer) As PaDeviceInfo
...
Private Structure PaDeviceInfo
        Dim structVersion As Integer
        <MarshalAs(Runtime.InteropServices.UnmanagedType.LPStr)> Dim name As String
        Dim hostapi As Integer
        Dim maxInputChannels As Integer
        Dim maxOutputChannels As Integer
        Dim defaultLowInputLatency As Double
        Dim defaultLowOutputLatency As Double
        Dim defaultHighInputLatency As Double
        Dim defaultHighOutputLatency As Double
        Dim defaultSampleRate As Double
End Structure
...
        Dim di As New PaDeviceInfo
        di = Pa_GetDeviceInfo(outputParameters.device)
</code>```

This feels wrong as docs state Pa_GetDeviceInfo returns a POINTER to a structure containing info
about the structure, implying function creates the structure initially.

I am completely new to mixed language programming, a c++ utter noob, and a poor VB programmer.
Can anyone guide me in the correct way to attack this problem ?
My feeling is that I need to understand how to get VB to reference a struct in memry created in
the dll, so I need to get vb to understand 'pointer to thing' as a function return.

Much appreciation for any assistance rendered. Please don't just say rtfm, I'm up to my eyes in FM's at
the minute, I just don't know where to look.

Many thanks,
David

答:
Your API function declaration is wrong. The function returns a pointer which is not reflected in your code. The signature translates to VB as follows:

```<code>Private Declare Function Pa_GetDeviceInfo Lib "portaudio_x86.dll" ( _
    ByVal dindex As Integer _
) As IntPtr
</code>```

Of course, using an IntPtr directly is not easy. In fact, quite some marshalling is involved:

```<code>Dim obj As PaDeviceInfo = _
    DirectCast(Marshal.PtrToStructure(ptr, GetType(PaDeviceInfo)), PaDeviceInfo)
</code>```

(More or less important) side note: since your DLL apparently creates a new object in memory, it also needs to release/destroy it. Be sure to call the appropriate function after using the structure.

OwnerDisplayName: WaveyDavey

Body:
My problem is with understanding the finer point of mixed langage programming
and accessing API's in external libraries. My skills at C++ are nonexistent
and at VB, mediocre.

I have a c++ dll compiled (portaudio library), and am trying to access it from VB
(Visual Studio 2005).
I am getting MarshallDirectiveException errors when calling a function, I believe because
I am interacting incorrectly with the dll.

the C++ function and structures are defined as follows:

header info:

typedef int PaHostApiIndex;
...
typedef double PaTime;
...
typedef struct PaDeviceInfo
 {
     int structVersion;  /* this is struct version 2 */
     const char *name;
     PaHostApiIndex hostApi; /* note this is a host API index, not a type id*/
     int maxInputChannels;
     int maxOutputChannels;
     PaTime defaultLowInputLatency;
     PaTime defaultLowOutputLatency;
     PaTime defaultHighInputLatency;
     PaTime defaultHighOutputLatency;
     double defaultSampleRate;
 } PaDeviceInfo;
 ...
 const PaDeviceInfo* Pa_GetDeviceInfo( PaDeviceIndex device );

program usage from docs:

const PaDeviceInfo* Pa_GetDeviceInfo    (   PaDeviceIndex   device   )

Retrieve a pointer to a PaDeviceInfo structure containing information about the specified
device.

Returns:
A pointer to an immutable PaDeviceInfo structure. If the device parameter is out of range
the function returns NULL.

Parameters:
device  A valid device index in the range 0 to (Pa_GetDeviceCount()-1)

In the VB program I have:

Private Declare Function Pa_GetDeviceInfo Lib "portaudio_x86.dll" (ByVal dindex As Integer) As PaDeviceInfo
...
Private Structure PaDeviceInfo
        Dim structVersion As Integer
        <MarshalAs(Runtime.InteropServices.UnmanagedType.LPStr)> Dim name As String
        Dim hostapi As Integer
        Dim maxInputChannels As Integer
        Dim maxOutputChannels As Integer
        Dim defaultLowInputLatency As Double
        Dim defaultLowOutputLatency As Double
        Dim defaultHighInputLatency As Double
        Dim defaultHighOutputLatency As Double
        Dim defaultSampleRate As Double
End Structure
...
        Dim di As New PaDeviceInfo
        di = Pa_GetDeviceInfo(outputParameters.device)

This feels wrong as docs state Pa_GetDeviceInfo returns a POINTER to a structure containing info
about the structure, implying function creates the structure initially.

I am completely new to mixed language programming, a c++ utter noob, and a poor VB programmer.
Can anyone guide me in the correct way to attack this problem ?
My feeling is that I need to understand how to get VB to reference a struct in memry created in
the dll, so I need to get vb to understand 'pointer to thing' as a function return.

Much appreciation for any assistance rendered. Please don't just say rtfm, I'm up to my eyes in FM's at
the minute, I just don't know where to look.

Many thanks,
David

Body:
Your API function declaration is wrong. The function returns a pointer which is not reflected in your code. The signature translates to VB as follows:

Private Declare Function Pa_GetDeviceInfo Lib "portaudio_x86.dll" ( _
    ByVal dindex As Integer _
) As IntPtr

Of course, using an IntPtr directly is not easy. In fact, quite some marshalling is involved:

Dim obj As PaDeviceInfo = _
    DirectCast(Marshal.PtrToStructure(ptr, GetType(PaDeviceInfo)), PaDeviceInfo)

(More or less important) side note: since your DLL apparently creates a new object in memory, it also needs to release/destroy it. Be sure to call the appropriate function after using the structure.

OwnerDisplayName: Konrad Rudolph