问:
Sortable UUID v1 for multi-platform application
We are looking for a solution to generate a unique id for messages/signals that are exchanged between clients on the Web, iOS, and Android and later persisted on the backend.

Solution have to be standardized

available on multiple platforms

sortable by created time, indexable by the database

The UUID v1 have these properties except one small thing that sorting and indexing require rearranging of string identifier.

UUID documentation explains that order of time blocks is reversed(starts from milliseconds) (link).

```<code>  UUID                   = time-low "-" time-mid "-"
                           time-high-and-version "-"
                           clock-seq-and-reserved
                           clock-seq-low "-" node
  time-low               = 4hexOctet
  time-mid               = 2hexOctet
  time-high-and-version  = 2hexOctet
  clock-seq-and-reserved = hexOctet
  clock-seq-low          = hexOctet
  node                   = 6hexOctet
</code>```

Because of the UUID representation, we can not sort IDs simply by the string representation of the IDs, and we have to use compare function.

```<code>const toSortableUUID = uuidV1 =>
  uuidV1.replace(/^(.{8})-(.{4})-(.{4})/, '$3-$2-$1');

const uuidCompare = (uuidV1A, uuidV1B) => {
  if (uuidV1A === uuidV1B) {
    return 0;
  }
  const a = toSortableUUID(uuidV1A);
  const b = toSortableUUID(uuidV1B);
  return a < b ? -1 : 1;
};

const sortedArrayOfUUIDV1 = arrayOfUUIDV1.concat().sort(uuidCompare);
</code>```

Do you know another standardized approach that will not have this issue?

Would it be correct to use UUID v1 but exchange it between clients rearranged so clients can sort by string representation and do not have to use compare function every time for sorting?

Live test: https://codesandbox.io/s/q5oRxgnp

答:
If you rearrange the bits of a UUID, you no longer have a UUID.

Also note that one of the purposes of the UUID standard is to allow the mixing of values of the different versions of UUID. In other words, generally you should not assume your UUIDs are all entirely of one version.

UUIDs were never intended to be torn apart, never to be considered as a container. Clever programmers who conceive of doing so are being too clever for their own good.

Nevertheless, some people do alter the structure or content of their UUID.  I do not recommend that.

Instead I suggest you identify and separate your concerns.

Identifier
If you need to uniquely identify your entities across time and space without coordinating with a centralized server, then use a UUID proper.

Sort
 If you also want to sort, then add another field for the sort value. For example, if you want to sort chronologically, store a timestamp value if supported by your database or data sink. If not supported, store a textual representation of a date-time value in UTC in standard ISO 8601 format. This format is wisely designed so that when sorted alphabetically it is also chronological.

2017-01-23T01:23:45.123Z

Body:
We are looking for a solution to generate a unique id for messages/signals that are exchanged between clients on the Web, iOS, and Android and later persisted on the backend.

Solution have to be standardized

available on multiple platforms

sortable by created time, indexable by the database

The UUID v1 have these properties except one small thing that sorting and indexing require rearranging of string identifier.

UUID documentation explains that order of time blocks is reversed(starts from milliseconds) (link).

  UUID                   = time-low "-" time-mid "-"
                           time-high-and-version "-"
                           clock-seq-and-reserved
                           clock-seq-low "-" node
  time-low               = 4hexOctet
  time-mid               = 2hexOctet
  time-high-and-version  = 2hexOctet
  clock-seq-and-reserved = hexOctet
  clock-seq-low          = hexOctet
  node                   = 6hexOctet

Because of the UUID representation, we can not sort IDs simply by the string representation of the IDs, and we have to use compare function.

const toSortableUUID = uuidV1 =>
  uuidV1.replace(/^(.{8})-(.{4})-(.{4})/, '$3-$2-$1');

const uuidCompare = (uuidV1A, uuidV1B) => {
  if (uuidV1A === uuidV1B) {
    return 0;
  }
  const a = toSortableUUID(uuidV1A);
  const b = toSortableUUID(uuidV1B);
  return a < b ? -1 : 1;
};

const sortedArrayOfUUIDV1 = arrayOfUUIDV1.concat().sort(uuidCompare);

Do you know another standardized approach that will not have this issue?

Would it be correct to use UUID v1 but exchange it between clients rearranged so clients can sort by string representation and do not have to use compare function every time for sorting?

Live test: https://codesandbox.io/s/q5oRxgnp


来源: stackexchange

问:
Jupyter: XSRF cookie does not match POST
I am trying to transfert files using a python program running on a local Anaconda to a local Jupyter within a docker container using the Jupyter rest API.

I managed already to execute a requests.get() succesfully after muddling-through a bit on how to input the token.

Now I would like now to execute a requests.post() command to transfert the files.

Configuration:

local docker container running on docker toolbox for windows

docker version 17.04.0-ce, build 4845c56

tensorflow/tensorflow incl. Jupyter latest version install

jupyter_kernel_gateway==0.3.1

local Anaconda v. 4.3.14 running on a windows 10 machine

Code:

```<code>token = token_code_provided_by_jupyter_at_startup
api_url = "http://192.168.99.100:8888/api/contents"
# getting the file's data from disk and converting into a json file
cwd = os.getcwd()
file_location = cwd+r'\Resources\Test\test_post.py'
payload = open(file_location, 'r').read()
b64payload = base64.encodestring(payload)
body = json.dumps({
            'content':b64payload,
            'name': 'test_post.py',
            'path': '/api/contents/',
            'format': 'base64',
            'type':'file'
        })
# getting the xsrf cookie
client = requests.session()
client.get('http://192.168.99.100:8888/')
csrftoken = client.cookies['_xsrf']
headers ={'Content-type': 'application/json', 'X-CSRFToken':csrftoken, 'Referer':'http://192.168.99.100:8888/api/contents', 'token':token}
response = requests.post(api_url, data=body, headers=headers, verify=True)
</code>```

Error returned

[W 12:22:36.710 NotebookApp] 403 POST /api/contents (192.168.99.1): XSRF cookie does not match POST argument
  [W 12:22:36.713 NotebookApp] 403 POST /api/contents (192.168.99.1) 4.17ms referer=http://192.168.99.100:8888/api/contents

答:
Actually there is no need for xsrf cookie when using header token for authentification.

```<code>headers = {'Authorization': 'token ' + token}
</code>```

Reference is made to the Jupyter notebook documentation.

http://jupyter-notebook.readthedocs.io/en/latest/security.html

ContentLicense: CC BY-SA 3.0

Body:
I am trying to transfert files using a python program running on a local Anaconda to a local Jupyter within a docker container using the Jupyter rest API.

I managed already to execute a requests.get() succesfully after muddling-through a bit on how to input the token.

Now I would like now to execute a requests.post() command to transfert the files.

Configuration:

local docker container running on docker toolbox for windows

docker version 17.04.0-ce, build 4845c56

tensorflow/tensorflow incl. Jupyter latest version install

jupyter_kernel_gateway==0.3.1

local Anaconda v. 4.3.14 running on a windows 10 machine

Code:

token = token_code_provided_by_jupyter_at_startup
api_url = "http://192.168.99.100:8888/api/contents"
# getting the file's data from disk and converting into a json file
cwd = os.getcwd()
file_location = cwd+r'\Resources\Test\test_post.py'
payload = open(file_location, 'r').read()
b64payload = base64.encodestring(payload)
body = json.dumps({
            'content':b64payload,
            'name': 'test_post.py',
            'path': '/api/contents/',
            'format': 'base64',
            'type':'file'
        })
# getting the xsrf cookie
client = requests.session()
client.get('http://192.168.99.100:8888/')
csrftoken = client.cookies['_xsrf']
headers ={'Content-type': 'application/json', 'X-CSRFToken':csrftoken, 'Referer':'http://192.168.99.100:8888/api/contents', 'token':token}
response = requests.post(api_url, data=body, headers=headers, verify=True)

Error returned

[W 12:22:36.710 NotebookApp] 403 POST /api/contents (192.168.99.1): XSRF cookie does not match POST argument
  [W 12:22:36.713 NotebookApp] 403 POST /api/contents (192.168.99.1) 4.17ms referer=http://192.168.99.100:8888/api/contents

Body:
Actually there is no need for xsrf cookie when using header token for authentification.

headers = {'Authorization': 'token ' + token}

Reference is made to the Jupyter notebook documentation.

http://jupyter-notebook.readthedocs.io/en/latest/security.html


问:
Simple AJAX/jQuery application to show files in real time during copy
While studying Ajax/jQuery, I am trying to setup this test environment:

the server recursively copy a full folder form one location to
another;

the client should display the list of copied files, one
by one, in real time until the copy ends;

in the client thereshould be a button to abort the copy operation.

Can you pls point me to a simple skeleton of this problem, or give me any clue?
Thanks, I appreciate.

答:
Some general ideas for the client:

It needs to establish a session. This is both so that it can see the file copy progress of the files it is copying and no other (possibly malicious) third party can see it. This can be done with some sort of a token. This can be stored as a cookie and the server can read this to see what session the request is from.

You need the client to keep requesting the state at a steady interval. This is called polling.

So, all your client has to do is request to establish a session, request which folder needs to be copied (Possibly needing to request a directory tree), and then make a request for which folder needs to be copied where, and keep making requests for the progress every few seconds or minutes until it is done. In the mean time, if the user wishes to cancel it, send a cancel request to some endpoint.

On the server side, there are many technologies to do this. django is the most popular, but this seems like a smaller project, so might I recommended flask.

As for the actual task, shutil.copytree() is what you are looking for. It takes a custom copy function, which you can specify to update a sessions "currently copying" file when a new file needs to be copied:

import shutil

def copy_dir(session_id, source, destination):
    def copy_fn(src, dest):
        if sessions[session_id]['data'].aborted:
            return  # Stop copying once requested.
        # Or however your session data is structured
        sessions[session_id]['data'].current_copy = [src, dest]
        shutil.copy2(src, dest)  # Actual copy work
    shutil.copytree(source, destination, copy_function=copy_fn)
```

To get the percentage of how much of the file has been copied, compare the size of the file that is being copied to to the file it is being copied from.

Another way to get the percentage of copying, os.walk on a directory to generate all the file names, then open the files and copy it in chunks. Update the progress every few chunks. Note that this is very error prone.

Body:
Some general ideas for the client:

It needs to establish a session. This is both so that it can see the file copy progress of the files it is copying and no other (possibly malicious) third party can see it. This can be done with some sort of a token. This can be stored as a cookie and the server can read this to see what session the request is from.

You need the client to keep requesting the state at a steady interval. This is called polling.

So, all your client has to do is request to establish a session, request which folder needs to be copied (Possibly needing to request a directory tree), and then make a request for which folder needs to be copied where, and keep making requests for the progress every few seconds or minutes until it is done. In the mean time, if the user wishes to cancel it, send a cancel request to some endpoint.

On the server side, there are many technologies to do this. django is the most popular, but this seems like a smaller project, so might I recommended flask.

As for the actual task, shutil.copytree() is what you are looking for. It takes a custom copy function, which you can specify to update a sessions "currently copying" file when a new file needs to be copied:

import shutil

def copy_dir(session_id, source, destination):
    def copy_fn(src, dest):
        if sessions[session_id]['data'].aborted:
            return  # Stop copying once requested.
        # Or however your session data is structured
        sessions[session_id]['data'].current_copy = [src, dest]
        shutil.copy2(src, dest)  # Actual copy work
    shutil.copytree(source, destination, copy_function=copy_fn)

To get the percentage of how much of the file has been copied, compare the size of the file that is being copied to to the file it is being copied from.

Another way to get the percentage of copying, os.walk on a directory to generate all the file names, then open the files and copy it in chunks. Update the progress every few chunks. Note that this is very error prone.


问:
fedpkg local error: conflict
When I execute the command "fedpkg local" I get this error message

```<code>[root@localhost kernel]# fedpkg local
/usr/lib/python2.7/site-packages/fedora/client/bodhi.py:48: DeprecationWarning: fedora.client.bodhi has been deprecated. Please use bodhi.client.bindings instead.
  DeprecationWarning)
error: Failed build dependencies:
    rpm < 4.13.0.1-19 conflicts with kernel-4.12.0-0.rc3.git3.2.fc27.x86_64
</code>```

How can I solve the conflict so that I can run fedpkg local?

答: If you did just fedpkg clone, you are building Fedora Rawhide (27) kernel, not your kernel (Fedora 25). Run git checkout f25 to change to Fedora 25 branch and now you will be able to build your kernel using fedpkg local. The Rawhide can be already incompatible with some of your userspace you have installed.

Title: fedpkg local error: conflict

Body:
When I execute the command "fedpkg local" I get this error message

[root@localhost kernel]# fedpkg local
/usr/lib/python2.7/site-packages/fedora/client/bodhi.py:48: DeprecationWarning: fedora.client.bodhi has been deprecated. Please use bodhi.client.bindings instead.
  DeprecationWarning)
error: Failed build dependencies:
    rpm < 4.13.0.1-19 conflicts with kernel-4.12.0-0.rc3.git3.2.fc27.x86_64

How can I solve the conflict so that I can run fedpkg local?


问:
How to generate a set of random points within a given (x,y) coordinates in an x-y plane?
Suppose I want to take 4 clusters of points. Each cluster can be within a given set of x-y co ordinates. Each point within a cluster is a random generated point.

These clusters will be acting as input for my K-Means clustering problem.
How do I do it using Python?

答:
This might give you some ideas:

```<code>from random import random
import math

def rand_cluster(n,c,r):
    """returns n random points in disk of radius r centered at c"""
    x,y = c
    points = []
    for i in range(n):
        theta = 2*math.pi*random()
        s = r*random()
        points.append((x+s*math.cos(theta), y+s*math.sin(theta)))
    return points
</code>```

This function can be used in various ways, for example:

```<code>def rand_clusters(k,n,r, a,b,c,d):
    """return k clusters of n points each in random disks of radius r
where the centers of the disk are chosen randomly in [a,b]x[c,d]"""
    clusters = []
    for _ in range(k):
        x = a + (b-a)*random()
        y = c + (d-c)*random()
        clusters.extend(rand_cluster(n,(x,y),r))
    return clusters
</code>```

A typical all would look like

```<code>clusters = rand_clusters(4,50,0.3,0,1,0,1)
</code>```

This generates 4 clusters of size 50 of radius 0.3 with centers chosen at random in the unit square. Points from a typical run:

Body:
This might give you some ideas:

from random import random
import math

def rand_cluster(n,c,r):
    """returns n random points in disk of radius r centered at c"""
    x,y = c
    points = []
    for i in range(n):
        theta = 2*math.pi*random()
        s = r*random()
        points.append((x+s*math.cos(theta), y+s*math.sin(theta)))
    return points

This function can be used in various ways, for example:

def rand_clusters(k,n,r, a,b,c,d):
    """return k clusters of n points each in random disks of radius r
where the centers of the disk are chosen randomly in [a,b]x[c,d]"""
    clusters = []
    for _ in range(k):
        x = a + (b-a)*random()
        y = c + (d-c)*random()
        clusters.extend(rand_cluster(n,(x,y),r))
    return clusters

A typical all would look like

clusters = rand_clusters(4,50,0.3,0,1,0,1)

This generates 4 clusters of size 50 of radius 0.3 with centers chosen at random in the unit square. Points from a typical run:


问:
C# Range to specific rating
What is the best way to associate a range of numbers with a value, so that if the user inputs a number I can look up the value based on the range the number belongs to?

For example, I have the following Rating enum:

```<code>enum Rating
{
    A, B, C, D, E
}
</code>```

And I want to assign a range of integers to each value, such that the numbers 1, 2, 3 are associated with Rating.A, numbers 4, 5, 6 are associated with Rating.B, numbers 7, 8, 9 are associated with Rating.C, etc...

Then, given some user input, I will return the appropriate enum value. For example, if the user enters 6 I will return Rating.B, or if they enter 10 I will return Rating.D.

I will have a lot of ranges (up to 100), so I do not want to write a bunch of if / else if statements to test all possible inputs. And it should be easy to add a new range / value into the collection.

答:
Use a Dictionary<int, string> where the key is the number and the value is the rating letter. Alternatively, the value could be an enum.

```<code>Dictionary<int, string> ratings = new Dictionary<int, string>();
ratings.Add(1, "A");
ratings.Add(2, "A");
ratings.Add(3, "B"); // etc..

// Get a rating by number:
var test = ratings[1]; // returns "A"
</code>```

Adding your entries to the dictionary could also easily be done in a loop, if the pairs of values exist elsewhere.

ADictionary has the benefit that it will not allow duplicate keys to be added and getting a rating is, basically, an O(1) operation. If there is the possibility that the number supplied may not be a valid key, Dictionary also includes methods to check that the key exists such as ContainsKey(TKey) and TryGetValue(TKey, TValue).

Title: C# Range to specific rating

Body:
What is the best way to associate a range of numbers with a value, so that if the user inputs a number I can look up the value based on the range the number belongs to?

For example, I have the following Rating enum:

enum Rating
{
    A, B, C, D, E
}

And I want to assign a range of integers to each value, such that the numbers 1, 2, 3 are associated with Rating.A, numbers 4, 5, 6 are associated with Rating.B, numbers 7, 8, 9 are associated with Rating.C, etc...

Then, given some user input, I will return the appropriate enum value. For example, if the user enters 6 I will return Rating.B, or if they enter 10 I will return Rating.D.

I will have a lot of ranges (up to 100), so I do not want to write a bunch of if / else if statements to test all possible inputs. And it should be easy to add a new range / value into the collection.

Body:
Use a Dictionary<int, string> where the key is the number and the value is the rating letter. Alternatively, the value could be an enum.

Dictionary<int, string> ratings = new Dictionary<int, string>();
ratings.Add(1, "A");
ratings.Add(2, "A");
ratings.Add(3, "B"); // etc..

// Get a rating by number:
var test = ratings[1]; // returns "A"

Adding your entries to the dictionary could also easily be done in a loop, if the pairs of values exist elsewhere.

ADictionary has the benefit that it will not allow duplicate keys to be added and getting a rating is, basically, an O(1) operation. If there is the possibility that the number supplied may not be a valid key, Dictionary also includes methods to check that the key exists such as ContainsKey(TKey) and TryGetValue(TKey, TValue).


问:
function prototype variable scope C++
Are variables in function prototype declaration in C++ considered global in scope?

E.g. In the script below, we declare a function prototype of readArray that takes an array integerArray and integer maxNumElements as input and returns the number of elements the user has provided. Of course, the readArray function is called from main. My question is if displayArray can print the array edited in readArray by being provided the maximum number of elements the user has inserted. In short, are integerArray and numElements global?

```<code>/* prototype declaration*/
int readArray (int integerArray [], int maxNumElements);
void displayArray(int integerArray[], int numElements);

int main()
{
    int inputValues[128]; /*the array to be read*/
    int numberOfValues = readArray(inputValues, 128);
    displayArray(inputValues, numberOfValues);
    return 0;
}

int readArray(int integerArray[], int maxNumElements)
{
    int numberOfValues;
    for (numberOfValues = 0; numberOfValues < maxNumElements; numberOfValues++)
    { /*take integers as input from user and insert into array */
       /*return the number of elements the user as provided*/
    }
    return numberOfValues;
}

void displayArray(int integerArray[], int numElements)
{ /*print the array*/
    for (int = 0; i < numElements; i++)
    {
        cout << i << ":" << integerArray[i] << endl;
    }
    cout << endl;
}
</code>```

答: No, they are not global. Functions create a local copy while receiving a parameter. You can verify this in C++ by creating your own class with a cout inside the copy constructor. Pass object of that class to a function(by value) and you will see the copy constructor being invoked. In C++, better way is to use std::array and std::vector. Also passing by value is not a wise idea for non-primitive types and huge data chunks. Always pass parameters by "address" (pointers) or by "reference" (you may want to read about std::ref)</p>

Title: function prototype variable scope C++

Body:
Are variables in function prototype declaration in C++ considered global in scope?

E.g. In the script below, we declare a function prototype of readArray that takes an array integerArray and integer maxNumElements as input and returns the number of elements the user has provided. Of course, the readArray function is called from main. My question is if displayArray can print the array edited in readArray by being provided the maximum number of elements the user has inserted. In short, are integerArray and numElements global?

/* prototype declaration*/
int readArray (int integerArray [], int maxNumElements);
void displayArray(int integerArray[], int numElements);

int main()
{
    int inputValues[128]; /*the array to be read*/
    int numberOfValues = readArray(inputValues, 128);
    displayArray(inputValues, numberOfValues);
    return 0;
}

int readArray(int integerArray[], int maxNumElements)
{
    int numberOfValues;
    for (numberOfValues = 0; numberOfValues < maxNumElements; numberOfValues++)
    { /*take integers as input from user and insert into array */
       /*return the number of elements the user as provided*/
    }
    return numberOfValues;
}

void displayArray(int integerArray[], int numElements)
{ /*print the array*/
    for (int = 0; i < numElements; i++)
    {
        cout << i << ":" << integerArray[i] << endl;
    }
    cout << endl;
}


问:
Group records by day including days in between that contain no records in MySQL
I have to display how many votes were issued on each day (from the first vote, until the last vote) users voted for poll 2.

My current query works fine; but I'm having trouble when a specific day doesn't have any votes in it. For example, for poll 2, this should be the result:

May, 11 2017 = 1

May, 12 2017 = 0

May, 13 2017 = 0

May, 14 2017 = 0

May, 15 2017 = 0

May, 16 2017 = 0

May, 17 2017 = 1

May, 18 2017 = 0

May, 19 2017 = 0

May, 20 2017 = 2

...but instead I'm getting this:

May, 11 2017 = 1

May, 17 2017 = 1

May, 20 2017 = 2

So, what I need is that all days that contain no records (between the first and last vote) also appear in the results. This is my current query:

```<code>SELECT DATE(poll_vote.date_insert) AS date_insert,
COUNT(poll_vote.id_vote) AS q
FROM poll_vote WHERE poll_vote.id_poll = 2
GROUP BY DATE(date_insert) ORDER BY date_insert
</code>```

Here's the SQL Fiddle with the example data. Thanks!

答:
As suggested by @Strawberry, I ended up writing a solution in php instead of mysql. For anyone interested, here's the code.

This solution only returns 0 in 1 day in between blank dates because that's what I needed. Example:

May, 11 2017 = 1

May, 16 2017 = 0

May, 17 2017 = 1

May, 19 2017 = 0

May, 20 2017 = 2

That allows me to display a trending line chart just like this one:

```<code>$sql = 'SELECT DATE(poll_vote.date_insert) AS date_insert, COUNT(poll_vote.id_vote) AS q FROM poll_vote WHERE poll_vote.id_poll = :id_poll GROUP BY DATE(date_insert) ORDER BY date_insert';

$stmt = cnn()->prepare($sql);
if($id_poll) $stmt->bindValue(':id_poll', $id_poll, PDO::PARAM_INT);
$stmt->execute();
$data = $stmt->fetchAll();

# insert blank dates between existing dates
$hotness = array();
foreach($data as $item) {
    if(!$temp) {
        $temp = $item['date_insert'];
    } else {
        $date_past = new DateTime($temp);
        $date_now = new DateTime($item['date_insert']);
        $diff = $date_now->diff($date_past)->format("%a");
        if($diff > 1) {
            $date_new = new DateTime($item['date_insert']);
            $date_new->modify('-1 day');
            $hotness[] = array(
                'date_insert' => $date_new->format('Y-m-d'),
                'q' => 0
            );
        }
    }
    $hotness[] = array(
        'date_insert' => $item['date_insert'],
        'q' => $item['q']
    );
}

# final result
print_r($hotness);
</code>```

Body:
I have to display how many votes were issued on each day (from the first vote, until the last vote) users voted for poll 2.

My current query works fine; but I'm having trouble when a specific day doesn't have any votes in it. For example, for poll 2, this should be the result:

May, 11 2017 = 1

May, 12 2017 = 0

May, 13 2017 = 0

May, 14 2017 = 0

May, 15 2017 = 0

May, 16 2017 = 0

May, 17 2017 = 1

May, 18 2017 = 0

May, 19 2017 = 0

May, 20 2017 = 2

...but instead I'm getting this:

May, 11 2017 = 1

May, 17 2017 = 1

May, 20 2017 = 2

So, what I need is that all days that contain no records (between the first and last vote) also appear in the results. This is my current query:

SELECT DATE(poll_vote.date_insert) AS date_insert,
COUNT(poll_vote.id_vote) AS q
FROM poll_vote WHERE poll_vote.id_poll = 2
GROUP BY DATE(date_insert) ORDER BY date_insert

Here's the SQL Fiddle with the example data. Thanks!

Body:
As suggested by @Strawberry, I ended up writing a solution in php instead of mysql. For anyone interested, here's the code.

This solution only returns 0 in 1 day in between blank dates because that's what I needed. Example:

May, 11 2017 = 1

May, 16 2017 = 0

May, 17 2017 = 1

May, 19 2017 = 0

May, 20 2017 = 2

That allows me to display a trending line chart just like this one:

$sql = 'SELECT DATE(poll_vote.date_insert) AS date_insert, COUNT(poll_vote.id_vote) AS q FROM poll_vote WHERE poll_vote.id_poll = :id_poll GROUP BY DATE(date_insert) ORDER BY date_insert';

$stmt = cnn()->prepare($sql);
if($id_poll) $stmt->bindValue(':id_poll', $id_poll, PDO::PARAM_INT);
$stmt->execute();
$data = $stmt->fetchAll();

# insert blank dates between existing dates
$hotness = array();
foreach($data as $item) {
    if(!$temp) {
        $temp = $item['date_insert'];
    } else {
        $date_past = new DateTime($temp);
        $date_now = new DateTime($item['date_insert']);
        $diff = $date_now->diff($date_past)->format("%a");
        if($diff > 1) {
            $date_new = new DateTime($item['date_insert']);
            $date_new->modify('-1 day');
            $hotness[] = array(
                'date_insert' => $date_new->format('Y-m-d'),
                'q' => 0
            );
        }
    }
    $hotness[] = array(
        'date_insert' => $item['date_insert'],
        'q' => $item['q']
    );
}

# final result
print_r($hotness);


问:
Can xslt be emdedded with Open XML format in styling the dynamically generated xml file?
I have an xml file generated dynamically using the Open XML SDK which dispays some metadata about a docx file. Is it possible to use xslt to add style sheets to this dynamically generated xml file using the Open XML SDK?</p>

答: Open XML is supposed to be used with Word, Excel or PowerPoint documents.  Each one of these have a specific section for styles where you specify how certain elements will look throughout the document. If you know how the XML will look in these style sections then you could load up the style.xml and use xslt to add styles, but you wouldn't do that with the Open XML SDK, but with basic C# code that would read and transform XML. I would recommend just using the Open XML SDK to add the styles dynamically since it should take away from some of the complexity of having to know the style.xml schema.</p>

ContentLicense: CC BY-SA 2.5


问:
np.roots() causing 'float() argument must be a string or a number' with mp.mpc type problems
I was getting this error:

> float() argument must be a string or a number

So, why does this happen?(I tried commands like np.asarray() but it keeps failing).

mp.mpc(cmath.rect(a,b)))

答:
The items in raizes are actually mpmath.mpc instances rather than native Python complex floats. numpy doesn't know how to deal with mpmath types, hence the TypeError.

You didn't mention mpmath at all in your original question. The problem would still have been easy to diagnose if you had posted the full traceback, rather than cutting off the most important part at the end:

```<code>In [10]: np.roots(Q)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-10-f3a270c7e8c0> in <module>()
----> 1 np.roots(Q)

/home/alistair/.venvs/mpmath/lib/python3.6/site-packages/numpy/lib/polynomial.py in roots(p)
    220     # casting: if incoming array isn't floating point, make it floating point.
    221     if not issubclass(p.dtype.type, (NX.floating, NX.complexfloating)):
--> 222         p = p.astype(float)
    223
    224     N = len(p)

TypeError: float() argument must be a string or a number, not 'mpc'
</code>```

Whenever you ask for help with debugging on this site, please always post the whole traceback rather than just (part of) the last line - it contains a lot of information that can be helpful for diagnosing the problem.

The solution is simple enough - just don't convert the native Python complex floats returned by cmath.rect to mpmath.mpc complex floats:

```<code>raizes = []
for i in range(2*n):
   a, f = cmath.polar(l[i])
   if((f>np.pi/2) or (f<-np.pi/2)):
        raizes.append(cmath.rect(a*r,f))

Q = np.poly(raizes)

print(np.roots(Q))

# [-0.35372430 +1.08865146e+00j -0.92606224 +6.72823602e-01j
#  -0.35372430 -1.08865146e+00j -1.14467588 -9.11902316e-16j
#  -0.92606224 -6.72823602e-01j]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The items in raizes are actually mpmath.mpc instances rather than native Python complex floats. numpy doesn't know how to deal with mpmath types, hence the TypeError.

You didn't mention mpmath at all in your original question. The problem would still have been easy to diagnose if you had posted the full traceback, rather than cutting off the most important part at the end:

In [10]: np.roots(Q)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-10-f3a270c7e8c0> in <module>()
----> 1 np.roots(Q)

/home/alistair/.venvs/mpmath/lib/python3.6/site-packages/numpy/lib/polynomial.py in roots(p)
    220     # casting: if incoming array isn't floating point, make it floating point.
    221     if not issubclass(p.dtype.type, (NX.floating, NX.complexfloating)):
--> 222         p = p.astype(float)
    223
    224     N = len(p)

TypeError: float() argument must be a string or a number, not 'mpc'

Whenever you ask for help with debugging on this site, please always post the whole traceback rather than just (part of) the last line - it contains a lot of information that can be helpful for diagnosing the problem.

The solution is simple enough - just don't convert the native Python complex floats returned by cmath.rect to mpmath.mpc complex floats:

raizes = []
for i in range(2*n):
   a, f = cmath.polar(l[i])
   if((f>np.pi/2) or (f<-np.pi/2)):
        raizes.append(cmath.rect(a*r,f))

Q = np.poly(raizes)

print(np.roots(Q))

# [-0.35372430 +1.08865146e+00j -0.92606224 +6.72823602e-01j
#  -0.35372430 -1.08865146e+00j -1.14467588 -9.11902316e-16j
#  -0.92606224 -6.72823602e-01j]


问:
How to change the grouping of items in a list?
So if I have a list like this:

```<code>x = [0,1,2,3,4,5,6,7,8,9]
</code>```

How do I convert this list into something like this:

```<code>x = [01,23,45,67,89]
</code>```

How can I do that?

I know about the built in zip function,
but I don't want a tuple and I want 2 numbers grouped into 1.

Body:
So if I have a list like this:

x = [0,1,2,3,4,5,6,7,8,9]

How do I convert this list into something like this:

x = [01,23,45,67,89]

How can I do that?

I know about the built in zip function,
but I don't want a tuple and I want 2 numbers grouped into 1.

Body:
You can try this:

x = [0,1,2,3,4,5,6,7,8,9]

x = map(str, x)

new_list = map(int, [x[i]+x[i+1] for i in range(0, len(x)-1, 2)])


问:
How to check if a pair of values exist on a 2-dimensional array in java
I have a 2d array of that form:

```<code>int[][] moves ;
moves = new int[][]{{1, 2}, {1, -2}, {2, 1}, {2, -1}, {-1, 2},
            {-1, -2}, {-2, 1}, {-2, -1}};
</code>```

and i want to check programmaticaly if a pair of values {j,k}
exist on my 2d array moves.

答:
With java 8 you would write this one liner:</p>

```<code>int[][] moves ;
moves = new int[][]{{1, 2}, {1, -2}, {2, 1}, {2, -1}, {-1, 2},
        {-1, -2}, {-2, 1}, {-2, -1}};

int [] t= {2,1};
boolean found = Arrays.stream(moves).anyMatch(m->Arrays.equals(m,t));
</code>```

Body:
I have a 2d array of that form:

int[][] moves ;
moves = new int[][]{{1, 2}, {1, -2}, {2, 1}, {2, -1}, {-1, 2},
            {-1, -2}, {-2, 1}, {-2, -1}};

and i want to check programmaticaly if a pair of values {j,k}
exist on my 2d array moves.

Body:
With java 8 you would write this one liner:

int[][] moves ;
moves = new int[][]{{1, 2}, {1, -2}, {2, 1}, {2, -1}, {-1, 2},
        {-1, -2}, {-2, 1}, {-2, -1}};

int [] t= {2,1};
boolean found = Arrays.stream(moves).anyMatch(m->Arrays.equals(m,t));


问:
How do I create objects with a different number of arguments?
my question is what if I want to create an object that represents a person in a contact list.
The user has to enter a last name, if not, the program won't work.
Besides that the user can enter the first name, the address, phone number and so on, but these aren't necessary.
So how do I tackle these?
I could create a huge amount of constructors with the different parameter combinations, but I don't think that is the right solution.

Can you guys help me out?

答:
Have you heard of setters?

I once had this problem in a project and I thought of it this way:

The must fill values: pass them through a constructor

The optional values: pass them using setters

Code sample of the class person:

```<code>    public class person {

    private String lastName;
    private String firstName;
    private String address;
    private String phoneNumber;

    //lastName is mandatory you should pass when you create your object
    public person(String lastName) {
        this.lastName = lastName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    //This is optional you can pass it using this setter
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getAddress() {
        return address;
    }

    //This is optional you can pass it using this setter
    public void setAddress(String address) {
        this.address = address;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    //This is optional you can pass it using this setter
    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    }
</code>```

Code sample of the main class

```<code>public class yourclass {
    public static void main(String[] args) {
        String lastname="fooer"; //choose how you want to intercept the input if you are building a GUI app, tell me I would help you with JavaFx or Swing code.
        String firstname="foo" //let's say this is the only optional to pass
        person newperson = new person(lastname);
        if (firstname.isEmpty()==false)
            newperson.setFirstName(firstname);

    }
}
</code>```

Body:
Have you heard of setters?

I once had this problem in a project and I thought of it this way:

The must fill values: pass them through a constructor

The optional values: pass them using setters

Code sample of the class person:

    public class person {

    private String lastName;
    private String firstName;
    private String address;
    private String phoneNumber;

    //lastName is mandatory you should pass when you create your object
    public person(String lastName) {
        this.lastName = lastName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    //This is optional you can pass it using this setter
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getAddress() {
        return address;
    }

    //This is optional you can pass it using this setter
    public void setAddress(String address) {
        this.address = address;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    //This is optional you can pass it using this setter
    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    }

Code sample of the main class

public class yourclass {
    public static void main(String[] args) {
        String lastname="fooer"; //choose how you want to intercept the input if you are building a GUI app, tell me I would help you with JavaFx or Swing code.
        String firstname="foo" //let's say this is the only optional to pass
        person newperson = new person(lastname);
        if (firstname.isEmpty()==false)
            newperson.setFirstName(firstname);

    }
}


问:
Android master detail detail
I'm having a problem coming back from a detail page to its parent. The problem is that it's three levels and the issue is coming from the third level back to the second level.
Imagine a list of invoices. Tap on one of them and it loads the detail of the invoice with the list of line items in the invoice. Tap on a line item and it goes to a third activity with the details for that line item. The line item is launched via tap response like so...

[EDIT Added manifest info]

```<code><activity
    android:name=".InvocieListActivity"
    android:label="@string/app_name"
    android:theme="@style/AppTheme.NoActionBar">
</activity>

<activity
    android:name=".InvoiceDetailActivity"
    android:label="@string/title_activity_invoice_detail"
    android:parentActivityName=".InvoiceListActivity"
    android:theme="@style/AppTheme.NoActionBar">
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="com.myweb.ree.InvocieListActivity"/>
</activity>

<activity
    android:name=".InvoiceItemDetailActivity"
    android:label="@string/title_activity_invoiceitem_detail"
    android:parentActivityName=".InvoiceDetailActivity"
    android:theme="@style/AppTheme.NoActionBar">
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="com.myweb.ree.InvoiceDetailActivity"/>
</activity>

private BroadcastReceiver invoiceItemReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(ACTION_INVOICEITEM_TAPPED)) {
            String invoiceItemId = intent.getStringExtra(Constants.MSG_DATA);
            if (invoiceItemId != null && invoiceItemId.length() > 0) {
                launchInvoiceItemActivity(invoiceItemId);
            }
        }
    }
};

private void launchInvoiceItemActivity(String invoiceItemId) {
    Intent intent = new Intent(this, InvoiceItemDetailActivity.class);
    intent.putExtra(ARG_InvoiceItem_ID, invoiceItemId);
    this.startActivity(intent);
}
</code>```

The invoice detail has the getSupportActionBar().setDisplayHomeAsUpEnabled(true); so that it can return to the list of invoices. The line item detail page has the same line to allow the back button to go to the invoice.

When I tap the back button on the line item detail activity it can't load the invoice because it doesn't have the invoice number that was passed in from the original list.

I understand I can override onBackPressed and create an intent that launches its parent rather than letting the framework do it. My question is will that mess up any internal view stack that the framework is keeping in the case of parent-child navigation? Is there some other way that I'm supposed to track items in a master view so it can be reloaded with the correct content when returning from a detail view?

TIA
Mike

答:
From the code snippet and the description, i can understand that the back stack will be like

InvoiceListActivity -> InvoiceDetailsActivity -> InvoiceItemDetailActivity.

Now override onOptionsItemSelected method in each of child activity.

Eg: in InvoiceItemDetailActivity class, override the method as shown below.

```<code>@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
    // Respond to the action bar's Up/Home button
    case android.R.id.home:
   // this will finish the current activity. and as the activity behind this in the back stack is InvoiceDetailsActivity, the same will just be resumed.
        finish();
        return true;
}
return super.onOptionsItemSelected(item);
</code>```

}

The same can be done in InvoiceDetailsActivity as well. Hope this solves your problem.

Title: Android master detail detail

Body:
I'm having a problem coming back from a detail page to its parent. The problem is that it's three levels and the issue is coming from the third level back to the second level.
Imagine a list of invoices. Tap on one of them and it loads the detail of the invoice with the list of line items in the invoice. Tap on a line item and it goes to a third activity with the details for that line item. The line item is launched via tap response like so...

[EDIT Added manifest info]

<activity
    android:name=".InvocieListActivity"
    android:label="@string/app_name"
    android:theme="@style/AppTheme.NoActionBar">
</activity>

<activity
    android:name=".InvoiceDetailActivity"
    android:label="@string/title_activity_invoice_detail"
    android:parentActivityName=".InvoiceListActivity"
    android:theme="@style/AppTheme.NoActionBar">
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="com.myweb.ree.InvocieListActivity"/>
</activity>

<activity
    android:name=".InvoiceItemDetailActivity"
    android:label="@string/title_activity_invoiceitem_detail"
    android:parentActivityName=".InvoiceDetailActivity"
    android:theme="@style/AppTheme.NoActionBar">
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="com.myweb.ree.InvoiceDetailActivity"/>
</activity>

private BroadcastReceiver invoiceItemReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(ACTION_INVOICEITEM_TAPPED)) {
            String invoiceItemId = intent.getStringExtra(Constants.MSG_DATA);
            if (invoiceItemId != null && invoiceItemId.length() > 0) {
                launchInvoiceItemActivity(invoiceItemId);
            }
        }
    }
};

private void launchInvoiceItemActivity(String invoiceItemId) {
    Intent intent = new Intent(this, InvoiceItemDetailActivity.class);
    intent.putExtra(ARG_InvoiceItem_ID, invoiceItemId);
    this.startActivity(intent);
}

The invoice detail has the getSupportActionBar().setDisplayHomeAsUpEnabled(true); so that it can return to the list of invoices. The line item detail page has the same line to allow the back button to go to the invoice.

When I tap the back button on the line item detail activity it can't load the invoice because it doesn't have the invoice number that was passed in from the original list.

I understand I can override onBackPressed and create an intent that launches its parent rather than letting the framework do it. My question is will that mess up any internal view stack that the framework is keeping in the case of parent-child navigation? Is there some other way that I'm supposed to track items in a master view so it can be reloaded with the correct content when returning from a detail view?

TIA
Mike

Body:
From the code snippet and the description, i can understand that the back stack will be like

InvoiceListActivity -> InvoiceDetailsActivity -> InvoiceItemDetailActivity.

Now override onOptionsItemSelected method in each of child activity.

Eg: in InvoiceItemDetailActivity class, override the method as shown below.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
    // Respond to the action bar's Up/Home button
    case android.R.id.home:
   // this will finish the current activity. and as the activity behind this in the back stack is InvoiceDetailsActivity, the same will just be resumed.
        finish();
        return true;
}
return super.onOptionsItemSelected(item);

}

The same can be done in InvoiceDetailsActivity as well. Hope this solves your problem.


问:
Reason: image not found tensorflow GPU
I have installed tensorflow GPU with Nvidia CUDA on mac book pro 2012mid (Nvidia GT 650M)

But when I run the simple tensorflow program, image not found error occurs.

I have googled around and found this error is related with cuda installation.

[[[What I have checked are]]]

libcudart.8,0.dylib is here

```<code>/usr/local/cuda/lib/libcudart.8.0.dylib
</code>```

and environment setting looks propery.

```<code>(tensorflow) koala:tensorWorkspace daichi$ echo $LD_LIBRARY_PATH
/usr/local/cuda/lib:
(tensorflow) koala:tensorWorkspace daichi$ echo $CUDA_HOME
/usr/local/cuda
</code>```

Is therre any place I should check???

error log is below.

```<code>(tensorflow) koala:tensorWorkspace whitebear$ python3 hello.py
Traceback (most recent call last):
  File "/Users/whitebear/.pyenv/versions/3.5.2/lib/python3.5/site-packages/tensorflow/python/pywrap_tensorflow.py", line 41, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "/Users/whitebear/.pyenv/versions/3.5.2/lib/python3.5/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "/Users/whitebear/.pyenv/versions/3.5.2/lib/python3.5/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "/Users/whitebear/.pyenv/versions/3.5.2/lib/python3.5/imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "/Users/whitebear/.pyenv/versions/3.5.2/lib/python3.5/imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: dlopen(/Users/whitebear/.pyenv/versions/3.5.2/lib/python3.5/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so, 10): Library not loaded: @rpath/libcublas.8.0.dylib
  Referenced from: /Users/whitebear/.pyenv/versions/3.5.2/lib/python3.5/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so
  Reason: image not found

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "hello.py", line 1, in <module>
    import tensorflow as tf
  File "/Users/whitebear/.pyenv/versions/3.5.2/lib/python3.5/site-packages/tensorflow/__init__.py", line 24, in <module>
    from tensorflow.python import *
  File "/Users/whitebear/.pyenv/versions/3.5.2/lib/python3.5/site-packages/tensorflow/python/__init__.py", line 51, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "/Users/whitebear/.pyenv/versions/3.5.2/lib/python3.5/site-packages/tensorflow/python/pywrap_tensorflow.py", line 52, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "/Users/whitebear/.pyenv/versions/3.5.2/lib/python3.5/site-packages/tensorflow/python/pywrap_tensorflow.py", line 41, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "/Users/whitebear/.pyenv/versions/3.5.2/lib/python3.5/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "/Users/whitebear/.pyenv/versions/3.5.2/lib/python3.5/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "/Users/whitebear/.pyenv/versions/3.5.2/lib/python3.5/imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "/Users/whitebear/.pyenv/versions/3.5.2/lib/python3.5/imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: dlopen(/Users/whitebear/.pyenv/versions/3.5.2/lib/python3.5/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so, 10): Library not loaded: @rpath/libcublas.8.0.dylib
  Referenced from: /Users/whitebear/.pyenv/versions/3.5.2/lib/python3.5/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so
  Reason: image not found

Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/install_sources#common_installation_problems

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.
</code>```

答:
The problem is SIP installed from MAC os 10.11

Stop SIP according to  this article

The problem was solved.

Title: Reason: image not found tensorflow GPU

Body:
I have installed tensorflow GPU with Nvidia CUDA on mac book pro 2012mid (Nvidia GT 650M)

But when I run the simple tensorflow program, image not found error occurs.

I have googled around and found this error is related with cuda installation.

[[[What I have checked are]]]

libcudart.8,0.dylib is here

/usr/local/cuda/lib/libcudart.8.0.dylib

and environment setting looks propery.

(tensorflow) koala:tensorWorkspace daichi$ echo $LD_LIBRARY_PATH
/usr/local/cuda/lib:
(tensorflow) koala:tensorWorkspace daichi$ echo $CUDA_HOME
/usr/local/cuda

Is therre any place I should check???

error log is below.

(tensorflow) koala:tensorWorkspace whitebear$ python3 hello.py
Traceback (most recent call last):
  File "/Users/whitebear/.pyenv/versions/3.5.2/lib/python3.5/site-packages/tensorflow/python/pywrap_tensorflow.py", line 41, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "/Users/whitebear/.pyenv/versions/3.5.2/lib/python3.5/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "/Users/whitebear/.pyenv/versions/3.5.2/lib/python3.5/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "/Users/whitebear/.pyenv/versions/3.5.2/lib/python3.5/imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "/Users/whitebear/.pyenv/versions/3.5.2/lib/python3.5/imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: dlopen(/Users/whitebear/.pyenv/versions/3.5.2/lib/python3.5/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so, 10): Library not loaded: @rpath/libcublas.8.0.dylib
  Referenced from: /Users/whitebear/.pyenv/versions/3.5.2/lib/python3.5/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so
  Reason: image not found

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "hello.py", line 1, in <module>
    import tensorflow as tf
  File "/Users/whitebear/.pyenv/versions/3.5.2/lib/python3.5/site-packages/tensorflow/__init__.py", line 24, in <module>
    from tensorflow.python import *
  File "/Users/whitebear/.pyenv/versions/3.5.2/lib/python3.5/site-packages/tensorflow/python/__init__.py", line 51, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "/Users/whitebear/.pyenv/versions/3.5.2/lib/python3.5/site-packages/tensorflow/python/pywrap_tensorflow.py", line 52, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "/Users/whitebear/.pyenv/versions/3.5.2/lib/python3.5/site-packages/tensorflow/python/pywrap_tensorflow.py", line 41, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "/Users/whitebear/.pyenv/versions/3.5.2/lib/python3.5/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "/Users/whitebear/.pyenv/versions/3.5.2/lib/python3.5/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "/Users/whitebear/.pyenv/versions/3.5.2/lib/python3.5/imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "/Users/whitebear/.pyenv/versions/3.5.2/lib/python3.5/imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: dlopen(/Users/whitebear/.pyenv/versions/3.5.2/lib/python3.5/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so, 10): Library not loaded: @rpath/libcublas.8.0.dylib
  Referenced from: /Users/whitebear/.pyenv/versions/3.5.2/lib/python3.5/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so
  Reason: image not found

Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/install_sources#common_installation_problems

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.


问:
Error: Could not request certificate: No route to host - connect(2) for "puppet.myname.homelab" port 8140
I have two VMs setup to learn Puppet - one running puppetserver as my master and another as just a Puppet agent for DNS.

The VMs are running in Hyper-V (Windows 10) and are on the same virtual switch.

After setting up the internal DNS server using this Puppet module - https://github.com/ajjahn/puppet-dns my second, DNS VM can no longer connect to the puppetserver. I receive this error on puppet agent -t runs:

```<code>Error: Could not request certificate: No route to host - connect(2) for "puppet.myname.homelab" port 8140
</code>```

On the puppetserver I have reissued its own agent cert, which changed the cert from puppet <sha-omitted> to "puppet.myname.homelab" <sha omitted> (alt names: "DNS:puppet", "DNS:puppet.myname.homelab")

Running puppet agent -t on the puppetserver to update itself works fine post cert renewal.

I am able to successfully perform a nslookup on any of the hosts using the DNS server, and they do resolve with the new myname.homelab domain.

I still have DHCP enabled on my home router, but I have it set to be the second nameserver in /etc/resolv.conf on both VMs:

```<code>search myname.homelab
nameserver 192.168.1.107
nameserver 192.168.1.1
</code>```

I am running Ubuntu 16.04 and Puppet 4 on both VMs. I have allowed port 8140 in UFW on both VMs, and have even tried disabling UFW with no luck.

I'm still learning Puppet and am a novice to networking, so any suggestions on what else to try and to point me in the right direction would be appreciated.

Thanks!

答:
I slept on it and realized this morning that my router had reassigned my Puppetserver to a new IP, so the DNS A record for it was wrong, even though it was manually assigned in the router's DHCP.

Correcting that did the trick and now everything is working.

Body:
I have two VMs setup to learn Puppet - one running puppetserver as my master and another as just a Puppet agent for DNS.

The VMs are running in Hyper-V (Windows 10) and are on the same virtual switch.

After setting up the internal DNS server using this Puppet module - https://github.com/ajjahn/puppet-dns my second, DNS VM can no longer connect to the puppetserver. I receive this error on puppet agent -t runs:

Error: Could not request certificate: No route to host - connect(2) for "puppet.myname.homelab" port 8140

On the puppetserver I have reissued its own agent cert, which changed the cert from puppet <sha-omitted> to "puppet.myname.homelab" <sha omitted> (alt names: "DNS:puppet", "DNS:puppet.myname.homelab")

Running puppet agent -t on the puppetserver to update itself works fine post cert renewal.

I am able to successfully perform a nslookup on any of the hosts using the DNS server, and they do resolve with the new myname.homelab domain.

I still have DHCP enabled on my home router, but I have it set to be the second nameserver in /etc/resolv.conf on both VMs:

search myname.homelab
nameserver 192.168.1.107
nameserver 192.168.1.1

I am running Ubuntu 16.04 and Puppet 4 on both VMs. I have allowed port 8140 in UFW on both VMs, and have even tried disabling UFW with no luck.

I'm still learning Puppet and am a novice to networking, so any suggestions on what else to try and to point me in the right direction would be appreciated.

Thanks!


问:
Warning: Attempt to present * on * whose view is not in the window hierarchy - swift
I'm trying to present a ViewController if there is any saved data in the data model. But I get the following error:

Warning: Attempt to present * on *whose view is not in the window hierarchy"

Relevant code:

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    loginButton.backgroundColor = UIColor.orangeColor()

    var request = NSFetchRequest(entityName: "UserData")
    request.returnsObjectsAsFaults = false

    var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
    var context:NSManagedObjectContext = appDel.managedObjectContext!

    var results:NSArray = context.executeFetchRequest(request, error: nil)!

    if(results.count <= 0){
        print("Inga resultat")
    } else {
        print("SWITCH VIEW PLOX")
        let internVC = self.storyboard?.instantiateViewControllerWithIdentifier("internVC") as internViewController
        self.presentViewController(internVC, animated: true, completion: nil)
    }
}
</code>```

I've tried different solutions found using Google without success.

答:
Swift 3.

Call this function to get the topmost view controller, then have that view controller present.

```<code>func topMostController() -> UIViewController {
    var topController: UIViewController = UIApplication.shared.keyWindow!.rootViewController!
        while (topController.presentedViewController != nil) {
            topController = topController.presentedViewController!
        }
        return topController
    }
</code>```

Usage:

```<code>let topVC = topMostController()
let vcToPresent = self.storyboard!.instantiateViewController(withIdentifier: "YourVCStoryboardID") as! YourViewController
topVC.present(vcToPresent, animated: true, completion: nil)
</code>```

Body:
I'm trying to present a ViewController if there is any saved data in the data model. But I get the following error:

Warning: Attempt to present * on *whose view is not in the window hierarchy"

Relevant code:

override func viewDidLoad() {
    super.viewDidLoad()
    loginButton.backgroundColor = UIColor.orangeColor()

    var request = NSFetchRequest(entityName: "UserData")
    request.returnsObjectsAsFaults = false

    var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
    var context:NSManagedObjectContext = appDel.managedObjectContext!

    var results:NSArray = context.executeFetchRequest(request, error: nil)!

    if(results.count <= 0){
        print("Inga resultat")
    } else {
        print("SWITCH VIEW PLOX")
        let internVC = self.storyboard?.instantiateViewControllerWithIdentifier("internVC") as internViewController
        self.presentViewController(internVC, animated: true, completion: nil)
    }
}

I've tried different solutions found using Google without success.

Body:
Swift 3.

Call this function to get the topmost view controller, then have that view controller present.

func topMostController() -> UIViewController {
    var topController: UIViewController = UIApplication.shared.keyWindow!.rootViewController!
        while (topController.presentedViewController != nil) {
            topController = topController.presentedViewController!
        }
        return topController
    }

Usage:

let topVC = topMostController()
let vcToPresent = self.storyboard!.instantiateViewController(withIdentifier: "YourVCStoryboardID") as! YourViewController
topVC.present(vcToPresent, animated: true, completion: nil)


问:
Visual Studio 2017 C++ Shared Items Project does not recognize STL
I am experimenting with the Shared Items projects in VS2017 (Community Edition). (The goal is to create a non-visual library running on Windows and Linux.)

I added a C++ class, and the most standard of include directives for some reason fail. E.g. #include <iostream> results in an error. There are some headers in the automatic completion list but they look like proprietary Microsoft stuff.

I had the impression this stuff should work out of the box. For some reason, the Project properties also don't have much going about them, no place to tweak the libraries.

答:
Thanks to @RichardCritten, I found that indeed some components were missing (Clang, I believe, although I installed some others). They were not called "standard components" though. </p>

<p>Bad, bad Visual Studio. </p>

Body:
Thanks to @RichardCritten, I found that indeed some components were missing (Clang, I believe, although I installed some others). They were not called "standard components" though.

Bad, bad Visual Studio.


问:
Write a function accepting wrapped constants, but only one level deep
I want to write a function (apologies for probably not using the correct term here) wubble which is true for specific constants and true for those constants if wrapped into another constant, but only one layer deep! Examples:

```<code>% are supposed to be TRUE:
?- wubble(foo).
?- wubble(bar).
?- wubble(wrapper(foo)).
?- wubble(wrapper(bar)).

% are suppoed to be FALSE:
?- wubble(not_in_knowledge_base).
?- wubble(wrapper(wrapper(foo))).
</code>```

The naive (at least in my brain) implementation looks like this:

```<code>wubble(foo).
wubble(bar).

wubble(wrapper(wrapper(_))) :- !, fail.
wubble(wrapper(X)) :- wubble(X).
</code>```

And this works with the queries above. However, I can't enumerate all valid X for wubble with this implementation:

```<code>?- wubble(X).
X = foo
X = bar
</code>```

So this is missing X = wrapper(foo) and X = wrapper(bar). Is it possible to fix my implementation somehow?

答:
One solution in this particular case, as the OP noted himself, is the following:

```<code>wubble(foo).
wubble(bar).

wubble(wrapper(X)) :- wubble(X), ((X = wrapper(_), !, fail); true).
</code>```

Since he also asked for an explanation of this pattern, here is my best shot:

Given the above knowledge base, a query like wubble(X). looks through it from top to bottom for either facts or heads of rules that unify with the goal, wubble(X). If it finds a fact, like wubble(foo), the goal just succeeds, unifying X with the inner term of the fact, in this case foo. After that, we can tell Prolog to backtrack to the last choice point (a node in the depth first search tree that Prolog builds during this process), which in this case was given by the original goal wubble(X) and make it look for other solutions to that goal. If we do this here, we get the fact for the second constant wubble(bar) of course.

Now for the fun part. If we backtrack again, the only way left to satisfy the goal wubble(X) is by satisfying the antecedent of your rule. Now let's go through this mechanically. This might be surprising, but wubble(wrapper(X)) unifies with wubble(X); you have to think of these Xes as independent. Both in the case of the query wubble(X) and the rule definition wubble(wrapper(X)) :- ..., X is just a local name. Really, these two variables are independent, uninstantiated variables in this situation and since an uninstantiated variable unifies with basically everything, we have X = wrapper(X) and thus the head of the rule matches our query. Maybe we should call them X1 and X2 for the query and the rule respectively, for now.

Now the tail of the rule is a conjunction, so we first try to satisfy the first goal, wubble(X), which creates a new choice point. Now the process basically starts over: We search the knowledge base from top to bottom for stuff that unifies with that, which first finds wubble(foo). So X2 is now unified with foo and we check whether the second part of the conjunction, now with X2 = foo, succeeds, which it does, because foo \= wrapper(_). So because both goals of the conjunction succeeded with X2 = foo, our original goal succeeds as well with X1 = wrapper(X2) = wrapper(foo).

Backtracking from this basically brings us back to the second choice point, created by the first goal of the conjunction in the rule. Next, we find X2 = bar, which again checks out with the second part of the conjunction and our original goal succeeds with X1 = wrapper(bar).

Next, we get to the rule again; we unify X2 = wrapper(X3), our new goal is wubble(X3), creating a new choice point, and this succeeds with X3 = foo and the second part also checks out. So now we go one layer up and we have X2 = wrapper(foo). This does not satisfy the second part of the conjunction! It triggers the !, fail, so our original goal of wubble(X1), where we unified X1 = wrapper(X2) = wrapper(wrapper(foo)), fails this time. But not only that, we also cut, which eliminates the choice point of the first recursive kipple call and everything below it, so we don't even try X3 = bar or X3 = wrapper(X4) anymore.

So we go back further to our original choice point for the goal wubble(X1); but there are no further clauses in the database that match this, so we are done.

Now I get that this might be hard to follow in text form, so here is my attempt to visualize the search tree:

<img src="https://i.stack.imgur.com/OCLYK.png" alt="Search three for the query wubble(X). Red signifies what the cut ... well cuts.">

Body:
I want to write a function (apologies for probably not using the correct term here) wubble which is true for specific constants and true for those constants if wrapped into another constant, but only one layer deep! Examples:

% are supposed to be TRUE:
?- wubble(foo).
?- wubble(bar).
?- wubble(wrapper(foo)).
?- wubble(wrapper(bar)).

% are suppoed to be FALSE:
?- wubble(not_in_knowledge_base).
?- wubble(wrapper(wrapper(foo))).

The naive (at least in my brain) implementation looks like this:

wubble(foo).
wubble(bar).

wubble(wrapper(wrapper(_))) :- !, fail.
wubble(wrapper(X)) :- wubble(X).

And this works with the queries above. However, I can't enumerate all valid X for wubble with this implementation:

?- wubble(X).
X = foo
X = bar

So this is missing X = wrapper(foo) and X = wrapper(bar). Is it possible to fix my implementation somehow?

Body:
One solution in this particular case, as the OP noted himself, is the following:

wubble(foo).
wubble(bar).

wubble(wrapper(X)) :- wubble(X), ((X = wrapper(_), !, fail); true).

Since he also asked for an explanation of this pattern, here is my best shot:

Given the above knowledge base, a query like wubble(X). looks through it from top to bottom for either facts or heads of rules that unify with the goal, wubble(X). If it finds a fact, like wubble(foo), the goal just succeeds, unifying X with the inner term of the fact, in this case foo. After that, we can tell Prolog to backtrack to the last choice point (a node in the depth first search tree that Prolog builds during this process), which in this case was given by the original goal wubble(X) and make it look for other solutions to that goal. If we do this here, we get the fact for the second constant wubble(bar) of course.

Now for the fun part. If we backtrack again, the only way left to satisfy the goal wubble(X) is by satisfying the antecedent of your rule. Now let's go through this mechanically. This might be surprising, but wubble(wrapper(X)) unifies with wubble(X); you have to think of these Xes as independent. Both in the case of the query wubble(X) and the rule definition wubble(wrapper(X)) :- ..., X is just a local name. Really, these two variables are independent, uninstantiated variables in this situation and since an uninstantiated variable unifies with basically everything, we have X = wrapper(X) and thus the head of the rule matches our query. Maybe we should call them X1 and X2 for the query and the rule respectively, for now.

Now the tail of the rule is a conjunction, so we first try to satisfy the first goal, wubble(X), which creates a new choice point. Now the process basically starts over: We search the knowledge base from top to bottom for stuff that unifies with that, which first finds wubble(foo). So X2 is now unified with foo and we check whether the second part of the conjunction, now with X2 = foo, succeeds, which it does, because foo \= wrapper(_). So because both goals of the conjunction succeeded with X2 = foo, our original goal succeeds as well with X1 = wrapper(X2) = wrapper(foo).

Backtracking from this basically brings us back to the second choice point, created by the first goal of the conjunction in the rule. Next, we find X2 = bar, which again checks out with the second part of the conjunction and our original goal succeeds with X1 = wrapper(bar).

Next, we get to the rule again; we unify X2 = wrapper(X3), our new goal is wubble(X3), creating a new choice point, and this succeeds with X3 = foo and the second part also checks out. So now we go one layer up and we have X2 = wrapper(foo). This does not satisfy the second part of the conjunction! It triggers the !, fail, so our original goal of wubble(X1), where we unified X1 = wrapper(X2) = wrapper(wrapper(foo)), fails this time. But not only that, we also cut, which eliminates the choice point of the first recursive kipple call and everything below it, so we don't even try X3 = bar or X3 = wrapper(X4) anymore.

So we go back further to our original choice point for the goal wubble(X1); but there are no further clauses in the database that match this, so we are done.

Now I get that this might be hard to follow in text form, so here is my attempt to visualize the search tree:


问:
Quick and dirty solution for communication between processes in different machines
I have two processes written in java in two machines within my network that should pass simple chunks of data to each other.

I'm looking for a quick and dirty way (without resorting to writing files and polling for changes on network share files)

答:
Assuming the machines have each other's addresses (getting said addresses is a different issue), I think your best bet is Spring remoting. You have a data passing interface, a domain object that encapsulates the data you want to pass, and a remoting service implementing that interface on each side. After that, your code treats the remote service as just another collaborator. Cheap, easy, fast, and you can use whatever transport you like (RMI, HTTP, Hessian, Burlap etc).

It usually takes me about 10 minutes (at most) to expose an existing interface/service as a remoting service, though first time will take a little longer.

OwnerDisplayName: Dani

OwnerDisplayName: GaryF


问:
Processing - Line Implementation Help
I jumped into Processing (the language) today. I've been trying to implement a line without the line() function. In other words, I'm trying to replicate the line() function with my own code. I'm almost there, but not. (There's a screen, and you can click around, and this function connects those clicks with lines.)

There are four different line slopes I'm dealing with (m>1, 0

If you could just glance at the following code, and tell me where I've gone wrong, I'd be grateful.

```<code>int xStart = -1;                // Starting x and y are negative.
int yStart = -1;                // No lines are drawn when mouseReleased() and x/y are negative.
boolean isReset = false;        // Turns true when 'r' is pressed to reset polygon chain.
int clickCounter = 0;            // Changes background color every 10 clicks (after c is pressed).
color backgroundColor = 0;          // Starting background color. Changed occasionally.
color lineColor = 255;
int weight = 1;

void setup() {
  size(800, 800);            // Initial size is 800x800
  background(backgroundColor);            // ...background is black.
  smooth();
  stroke(lineColor);               //... lines/points are white.
  strokeWeight(weight);
}

void draw() {
}

void mousePressed(){
  clickCounter++;
}

void mouseReleased(){                // mouseReleased used instead of mousePressed to avoid dragged clicks.
  point(mouseX, mouseY);             // Draws white point at clicked coordinates.
  if((xStart < 0 && yStart < 0) || isReset){      // If x/y negative or if r was pressed, set start points and return. No line drawn.
    xStart = mouseX;
    yStart = mouseY;
    isReset = false;              // Reset isReset to false.
    return;
  }
                                                        // Sends starting and ending points to createLine function.
  createLine(xStart, yStart, mouseX, mouseY);           // createLine(...) - Creates line from start point to end point.
  xStart = mouseX;                                        // Start point = last click location. End point = Current click location.
  yStart = mouseY;                                   // Sets starting coordinates for next click at current click point.
}

void keyPressed(){
  if(key == 'x')                  // EXTRA CREDIT ADDITION: If x is pressed -> Exit program.
    exit();
  else if(key == 'c'){            // EXTRA CREDIT ADDITTION: If c pressed -> Set background black to clear all lines/points on screen.
    if(clickCounter > 10){
       backgroundColor = color(random(255), random(255), random(255));        // EXTRA CREDIT ADDITION: If cleared and clickCounter is greater
       clickCounter = 0;                                                        // ...than 10, background changes to random color.
    }
    background(backgroundColor);
    xStart = -1;                // Must set points negative so line is not drawn after next new point is made (since there will only be one point on the screen).
    yStart = -1;
  }
  else if(key == 'r'){          // If r pressed -> Reset: Next click will create new point that isn't connected with line to current points.
    isReset = true;
    lineColor = color(random(255), random(255), random(255));    // EXTRA CREDIT ADDITION: When dot chain is "reset", line changes color.
    weight = (int)random(10);
    strokeWeight(weight);                                    // EXTRA CREDIT ADDITION: ...and line/dot thickness changes.
    stroke(lineColor);
  }
  else
    return;
}

// createLine(): Function which draws line from (x0,y0) to (x1,y1).
void createLine(int x0, int y0, int x1, int y1){
  // 1) Line function draws from left to right. (Does not work right to left.) Check and swap points if ending point is left of starting point.
  if(x1 < x0){
    print("LEFT TO RIGHT SWITCH. \n");
    createLine(x1, y1, x0, y0);      // Drawing the line left to right cuts the number of line types we have to deal with to 4 regions.
    return;                              // Regions: slope > 1; 0 < slope < 1; -1 < slope < 0; slope < -1.
  }
  // Declare/Initialize data needed to draw line with midpoint algorithm.
  int dx = x1 - x0;
  int dy = y1 - y0;            //dy = Negative when y0 is lower on screen than y2, because origin is top left.
  print(y0 + "  " + x0 + "  " +y1 + "  " + x1+ "  x    y  \n");
  print(dy + "  " + dx + "  dx    dy\n");
  // Handle vertical & horizontal lines...
  if(dx == 0 || dy == 0){              // If slope is vertical or horizontal, create line with simple function.
      while(y1 != y0){                    // If vertical -> Paint by incrementing/decrementing y until points connect.
        if(y1 > y0){                          // If new point is above -> Draw upwards.
          y0 = y0 + 1;
          point(x0, y0);
        }
        else{                                // It new point below -> Draw downwards.
          y0 = y0 - 1;
          point(x0, y0);
        }
      }
      while(x1 != x0){                    // If horizontal -> Paint by incrementing x until points connect (will be left to right line always).
          x0 = x0 + 1;
          point(x0, y0);
      }
      return;
    }
  // Handle slanted lines...
  double tempDX = x1 - x0;
  double tempDY = y1 - y0;            // Had to create dx and dy as doubles because typecasting dy/dx to a double data type wasn't working.
  double m = (-tempDY / tempDX);      // m = line slope. (Note - The dy value is negative because positive y is downwards on the screen.)
  print("SLOPE CALCULATED: " + m + "\n");
  int deltaN = (2 * -dx);        // deltaX is the amount to increment d after choosing the next pixel on the line.
  int deltaNE = (2 * (-dy - dx));      // ...where X is the direction moved for that next pixel.
  int deltaE = (2 * -dy);            // deltaX variables are used below to plot line.
  int deltaSE = (2 * (dy + dx));
  int deltaS = (2 * dx);
  int x = x0;
  int y = y0;
  int d = 0;                            // d = Amount d-value changes from pixel to pixel. Depends on slope.
  int region = 0;                  // region = Variable to store slope region. Different regions require different formulas.
 if(m > 1){                            // if-statement: Initializes d, depending on the slope of the line.
      d = -dy - (2 * dx);                  // If slope is 1-Infiniti. -> Use NE/N initialization for d.
      region = 1;
  }
  else if(m == 1)
    region = 2;
  else if(m > 0 && m < 1){
      d = (2 * -dy) - dx;                  // If slope is 0-1 -> Use NE/E initialization for d.
      region = 3;
  }
  else if(m < 0 && m > -1){
      d = (2 * dy) + dx;                  // If slope is 0-(-1) -> Use E/SE initliazation for d.
      region = 4;
  }
  else if(m == -1)
    region = 5;
  else if(m < -1){
      d = dy + (2 * dx);                  // If slope is (-1)-(-Infiniti) -> Use SE/S initialization for d.
      region = 6;
  }
  while(x < x1){                    // Until points are connected...
        if(region == 1){          // If in region one...
              if(d <= 0){                // and d<=0...
              d += deltaNE;            // Add deltaNE to d, and increment x and y.
              x = x + 1;
              y = y - 1;
            }
            else{
              d += deltaN;        // If d > 0 -> Add deltaN, and increment y.
              y = y - 1;
            }
        }
        else if(region == 2){
             x = x + 1;
             y = y - 1;
        }
        else if(region == 3){
                if(d <= 0){
              d += deltaE;
              x = x + 1;
            }
            else{
              d += deltaNE;
              x = x + 1;
              y = y - 1;
            }
        }
        else if(region == 4){
              if(d <= 0){
              d += deltaSE;
              x = x + 1;
              y = y + 1;
            }
            else{
              d += deltaE;
              x = x + 1;
            }
        }
        else if(region == 5){
             x = x + 1;
             y = y + 1;
        }
        else if(region == 6){
              if(d <= 0){
              d += deltaSE;
              x = x + 1;
              y = y + 1;
            }
            else{
              d += deltaS;
              y = y + 1;
            }
          }
        point(x, y);
  }
  return;
}
</code>```

答:
When programs pause, look for while() loops that don't resolve properly. I inserted the following println statements into your while loop to print out what was happening. Then I recreated the problematic condition and quit the program, and checked the console for signs of what was going wrong.

```<code>println("top of the while loop to ya...");
println("x: " + x + ", x1: " + x1);
println("region: " + region + ", d: " + d);
</code>```

It looks like region 6 is causing the pausing problem. If d > 0, it is never decreased and x is never increased, so there is no way to satisfy the while condition.

With the same set of statements you can troubleshoot the inaccurate line issue. It occurs in region 4, but I'll leave the details as an exercise.

Title: Processing - Line Implementation Help

Body:
I jumped into Processing (the language) today. I've been trying to implement a line without the line() function. In other words, I'm trying to replicate the line() function with my own code. I'm almost there, but not. (There's a screen, and you can click around, and this function connects those clicks with lines.)

There are four different line slopes I'm dealing with (m>1, 0

If you could just glance at the following code, and tell me where I've gone wrong, I'd be grateful.

int xStart = -1;                // Starting x and y are negative.
int yStart = -1;                // No lines are drawn when mouseReleased() and x/y are negative.
boolean isReset = false;        // Turns true when 'r' is pressed to reset polygon chain.
int clickCounter = 0;            // Changes background color every 10 clicks (after c is pressed).
color backgroundColor = 0;          // Starting background color. Changed occasionally.
color lineColor = 255;
int weight = 1;

void setup() {
  size(800, 800);            // Initial size is 800x800
  background(backgroundColor);            // ...background is black.
  smooth();
  stroke(lineColor);               //... lines/points are white.
  strokeWeight(weight);
}

void draw() {
}

void mousePressed(){
  clickCounter++;
}

void mouseReleased(){                // mouseReleased used instead of mousePressed to avoid dragged clicks.
  point(mouseX, mouseY);             // Draws white point at clicked coordinates.
  if((xStart < 0 && yStart < 0) || isReset){      // If x/y negative or if r was pressed, set start points and return. No line drawn.
    xStart = mouseX;
    yStart = mouseY;
    isReset = false;              // Reset isReset to false.
    return;
  }
                                                        // Sends starting and ending points to createLine function.
  createLine(xStart, yStart, mouseX, mouseY);           // createLine(...) - Creates line from start point to end point.
  xStart = mouseX;                                        // Start point = last click location. End point = Current click location.
  yStart = mouseY;                                   // Sets starting coordinates for next click at current click point.
}

void keyPressed(){
  if(key == 'x')                  // EXTRA CREDIT ADDITION: If x is pressed -> Exit program.
    exit();
  else if(key == 'c'){            // EXTRA CREDIT ADDITTION: If c pressed -> Set background black to clear all lines/points on screen.
    if(clickCounter > 10){
       backgroundColor = color(random(255), random(255), random(255));        // EXTRA CREDIT ADDITION: If cleared and clickCounter is greater
       clickCounter = 0;                                                        // ...than 10, background changes to random color.
    }
    background(backgroundColor);
    xStart = -1;                // Must set points negative so line is not drawn after next new point is made (since there will only be one point on the screen).
    yStart = -1;
  }
  else if(key == 'r'){          // If r pressed -> Reset: Next click will create new point that isn't connected with line to current points.
    isReset = true;
    lineColor = color(random(255), random(255), random(255));    // EXTRA CREDIT ADDITION: When dot chain is "reset", line changes color.
    weight = (int)random(10);
    strokeWeight(weight);                                    // EXTRA CREDIT ADDITION: ...and line/dot thickness changes.
    stroke(lineColor);
  }
  else
    return;
}

// createLine(): Function which draws line from (x0,y0) to (x1,y1).
void createLine(int x0, int y0, int x1, int y1){
  // 1) Line function draws from left to right. (Does not work right to left.) Check and swap points if ending point is left of starting point.
  if(x1 < x0){
    print("LEFT TO RIGHT SWITCH. \n");
    createLine(x1, y1, x0, y0);      // Drawing the line left to right cuts the number of line types we have to deal with to 4 regions.
    return;                              // Regions: slope > 1; 0 < slope < 1; -1 < slope < 0; slope < -1.
  }
  // Declare/Initialize data needed to draw line with midpoint algorithm.
  int dx = x1 - x0;
  int dy = y1 - y0;            //dy = Negative when y0 is lower on screen than y2, because origin is top left.
  print(y0 + "  " + x0 + "  " +y1 + "  " + x1+ "  x    y  \n");
  print(dy + "  " + dx + "  dx    dy\n");
  // Handle vertical & horizontal lines...
  if(dx == 0 || dy == 0){              // If slope is vertical or horizontal, create line with simple function.
      while(y1 != y0){                    // If vertical -> Paint by incrementing/decrementing y until points connect.
        if(y1 > y0){                          // If new point is above -> Draw upwards.
          y0 = y0 + 1;
          point(x0, y0);
        }
        else{                                // It new point below -> Draw downwards.
          y0 = y0 - 1;
          point(x0, y0);
        }
      }
      while(x1 != x0){                    // If horizontal -> Paint by incrementing x until points connect (will be left to right line always).
          x0 = x0 + 1;
          point(x0, y0);
      }
      return;
    }
  // Handle slanted lines...
  double tempDX = x1 - x0;
  double tempDY = y1 - y0;            // Had to create dx and dy as doubles because typecasting dy/dx to a double data type wasn't working.
  double m = (-tempDY / tempDX);      // m = line slope. (Note - The dy value is negative because positive y is downwards on the screen.)
  print("SLOPE CALCULATED: " + m + "\n");
  int deltaN = (2 * -dx);        // deltaX is the amount to increment d after choosing the next pixel on the line.
  int deltaNE = (2 * (-dy - dx));      // ...where X is the direction moved for that next pixel.
  int deltaE = (2 * -dy);            // deltaX variables are used below to plot line.
  int deltaSE = (2 * (dy + dx));
  int deltaS = (2 * dx);
  int x = x0;
  int y = y0;
  int d = 0;                            // d = Amount d-value changes from pixel to pixel. Depends on slope.
  int region = 0;                  // region = Variable to store slope region. Different regions require different formulas.
 if(m > 1){                            // if-statement: Initializes d, depending on the slope of the line.
      d = -dy - (2 * dx);                  // If slope is 1-Infiniti. -> Use NE/N initialization for d.
      region = 1;
  }
  else if(m == 1)
    region = 2;
  else if(m > 0 && m < 1){
      d = (2 * -dy) - dx;                  // If slope is 0-1 -> Use NE/E initialization for d.
      region = 3;
  }
  else if(m < 0 && m > -1){
      d = (2 * dy) + dx;                  // If slope is 0-(-1) -> Use E/SE initliazation for d.
      region = 4;
  }
  else if(m == -1)
    region = 5;
  else if(m < -1){
      d = dy + (2 * dx);                  // If slope is (-1)-(-Infiniti) -> Use SE/S initialization for d.
      region = 6;
  }
  while(x < x1){                    // Until points are connected...
        if(region == 1){          // If in region one...
              if(d <= 0){                // and d<=0...
              d += deltaNE;            // Add deltaNE to d, and increment x and y.
              x = x + 1;
              y = y - 1;
            }
            else{
              d += deltaN;        // If d > 0 -> Add deltaN, and increment y.
              y = y - 1;
            }
        }
        else if(region == 2){
             x = x + 1;
             y = y - 1;
        }
        else if(region == 3){
                if(d <= 0){
              d += deltaE;
              x = x + 1;
            }
            else{
              d += deltaNE;
              x = x + 1;
              y = y - 1;
            }
        }
        else if(region == 4){
              if(d <= 0){
              d += deltaSE;
              x = x + 1;
              y = y + 1;
            }
            else{
              d += deltaE;
              x = x + 1;
            }
        }
        else if(region == 5){
             x = x + 1;
             y = y + 1;
        }
        else if(region == 6){
              if(d <= 0){
              d += deltaSE;
              x = x + 1;
              y = y + 1;
            }
            else{
              d += deltaS;
              y = y + 1;
            }
          }
        point(x, y);
  }
  return;
}

Body:
When programs pause, look for while() loops that don't resolve properly. I inserted the following println statements into your while loop to print out what was happening. Then I recreated the problematic condition and quit the program, and checked the console for signs of what was going wrong.

println("top of the while loop to ya...");
println("x: " + x + ", x1: " + x1);
println("region: " + region + ", d: " + d);

It looks like region 6 is causing the pausing problem. If d > 0, it is never decreased and x is never increased, so there is no way to satisfy the while condition.

With the same set of statements you can troubleshoot the inaccurate line issue. It occurs in region 4, but I'll leave the details as an exercise.


问:
how do you separate each part of an array into another array?
so I have a string that is split at any period. It is then stored into the array "sentences". Now I want to split all parts of the array "sentences" by spacing. How do I do that?

my code so far:

```<code>string input = TextEditor.Text;
string[] sentences = input.Split('.');
string[] words = sentences[0].Split(' ');
</code>```

this does not work though, obviously.

the output I want is if the string is: hello world I feel great. How about you.

output:

```<code>wordarray[0] = {"hello", "world", "I", "feel", "great"};
wordarray[1] = {"How", "about", "you"};
</code>```

答:
So you want your result to be a string[][] right? Each sub array contains a sentence. And each item in the subarrays contains words that make up the sentence.

Just use LINQ:

```<code>string[][] words = sentences.Select(x =>
    x.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries)).ToArray();
</code>```

Body:
so I have a string that is split at any period. It is then stored into the array "sentences". Now I want to split all parts of the array "sentences" by spacing. How do I do that?

my code so far:

string input = TextEditor.Text;
string[] sentences = input.Split('.');
string[] words = sentences[0].Split(' ');

this does not work though, obviously.

the output I want is if the string is: hello world I feel great. How about you.

output:

wordarray[0] = {"hello", "world", "I", "feel", "great"};
wordarray[1] = {"How", "about", "you"};

Body:
So you want your result to be a string[][] right? Each sub array contains a sentence. And each item in the subarrays contains words that make up the sentence.

Just use LINQ:

string[][] words = sentences.Select(x =>
    x.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries)).ToArray();


问:
What happens if an ISR hangs in Linux?
If an ISR hangs for some reason, e.g. waiting for a spinlock, or a never ending loop, how does Linux recover from this ?</p>

Title: What happens if an ISR hangs in Linux?

Body:
If we are stuck in ISR by some reason then it would be difficult to take out system from this state. You would get kernel stack traces after equal interval of time, however it would be not possible to say that system would recover from this state ever. We may need to restart even in worst case.

The kernel trace would be similar to this one:

[ 1872.084006] CPU: 0 PID: 5585 Comm: insmod Tainted: G           OEL  4.4.0-78-generic #99~14.04.2-Ubuntu
    [ 1872.084006] Hardware name: LENOVO 2847DJU/2847DJU, BIOS 6JET85WW (1.43 ) 12/24/2010
    [ 1872.084006] task: ffff880117d94e00 ti: ffff88004a654000 task.ti: ffff88004a654000
    [ 1872.084006] RIP: 0010:[<ffffffffc0008019>]  [<ffffffffc0008019>] sample_init+0x19/0x1000 [sample]
    [ 1872.084006] RSP: 0018:ffff88004a657cc0  EFLAGS: 00000292
    [ 1872.084006] RAX: 0000000000000020 RBX: ffffffff81e13080 RCX: 0000000000000006
    [ 1872.084006] RDX: 0000000000000000 RSI: 0000000000000246 RDI: ffff88013fc0dd90
    [ 1872.084006] RBP: ffff88004a657cc0 R08: 000000000000000a R09: 0000000000000000
    [ 1872.084006] R10: 0000000000000000 R11: 000000000000047c R12: ffff88003a50ffe0
    [ 1872.084006] R13: 0000000000000000 R14: ffffffffc0008000 R15: ffff88004a657eb0
    [ 1872.084006] FS:  00007f53c147b740(0000) GS:ffff88013fc00000(0000) knlGS:0000000000000000
    [ 1872.084006] CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
    [ 1872.084006] CR2: ffffffffc0007fee CR3: 000000004a530000 CR4: 00000000000406f0
    [ 1872.084006] Stack:
    [ 1872.084006]  ffff88004a657d38 ffffffff8100213d ffff88004a657eb0 ffff88004a657d10
    [ 1872.084006]  0000000000000246 0000000000000002 ffffffff811deafd ffff88013b401c00
    [ 1872.084006]  ffffffff81183ca4 0000000000000018 00000000f91cc401 ffffffffc06f3000
    [ 1872.084006] Call Trace:
    [ 1872.084006]  [<ffffffff8100213d>] do_one_initcall+0xcd/0x1f0
    [ 1872.084006]  [<ffffffff811deafd>] ? kmem_cache_alloc_trace+0x1ad/0x220
    [ 1872.084006]  [<ffffffff81183ca4>] ? do_init_module+0x27/0x1d2
    [ 1872.084006]  [<ffffffff81183cdd>] do_init_module+0x60/0x1d2
    [ 1872.084006]  [<ffffffff81104134>] load_module+0x1424/0x1b10
    [ 1872.084006]  [<ffffffff81100920>] ? __symbol_put+0x40/0x40
    [ 1872.084006]  [<ffffffff81206be1>] ? kernel_read+0x41/0x60
    [ 1872.084006]  [<ffffffff811049ee>] SYSC_finit_module+0x7e/0xa0
    [ 1872.084006]  [<ffffffff81104a2e>] SyS_finit_module+0xe/0x10
    [ 1872.084006]  [<ffffffff8180b776>] entry_SYSCALL_64_fastpath+0x16/0x75
    [ 1872.084006] Code: <eb> fe 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
    [ 1884.688004] INFO: rcu_sched self-detected stall on CPU
    [ 1884.688004]  0-...: (105006 ticks this GP) idle=41d/140000000000001/0 softirq=64742/64742 fqs=104241
    [ 1884.688004]   (t=105006 jiffies g=35345 c=35344 q=27697)
    [ 1884.688004] Task dump for CPU 0:
    [ 1884.688004] insmod          R  running task        0  5585   1990 0x0000000c
    [ 1884.688004]  ffffffff81e55040 ffff88013fc03db8 ffffffff810ab14f 0000000000000000
    [ 1884.688004]  ffffffff81e55040 ffff88013fc03dd0 ffffffff810ad8b9 0000000000000001
    [ 1884.688004]  ffff88013fc03e00 ffffffff810dff6a ffff88013fc17b80 ffffffff81e55040
    [ 1884.688004] Call Trace:
    [ 1884.688004]  <IRQ>  [<ffffffff810ab14f>] sched_show_task+0xaf/0x110
    [ 1884.688004]  [<ffffffff810ad8b9>] dump_cpu_task+0x39/0x40
    [ 1884.688004]  [<ffffffff810dff6a>] rcu_dump_cpu_stacks+0x8a/0xc0
    [ 1884.688004]  [<ffffffff810e3a93>] rcu_check_callbacks+0x4b3/0x7a0
    [ 1884.688004]  [<ffffffff810ae361>] ? account_system_time+0x81/0x110
    [ 1884.688004]  [<ffffffff810ae600>] ? account_process_tick+0x60/0x170
    [ 1884.688004]  [<ffffffff810f9200>] ? tick_sched_do_timer+0x30/0x30
    [ 1884.688004]  [<ffffffff810e9b79>] update_process_times+0x39/0x60
    [ 1884.688004]  [<ffffffff810f8c05>] tick_sched_handle.isra.15+0x25/0x60
    [ 1884.688004]  [<ffffffff810f923d>] tick_sched_timer+0x3d/0x70
    [ 1884.688004]  [<ffffffff810ea6d3>] __hrtimer_run_queues+0xf3/0x260
    [ 1884.688004]  [<ffffffff810eab78>] hrtimer_interrupt+0xa8/0x1a0
    [ 1884.688004]  [<ffffffffc0008000>] ? 0xffffffffc0008000
    [ 1884.688004]  [<ffffffff81050ec5>] local_apic_timer_interrupt+0x35/0x60
    [ 1884.688004]  [<ffffffff8180e21d>] smp_apic_timer_interrupt+0x3d/0x50
    [ 1884.688004]  [<ffffffff8180c4e2>] apic_timer_interrupt+0x82/0x90
    [ 1884.688004]  <EOI>  [<ffffffffc0008000>] ? 0xffffffffc0008000
    [ 1884.688004]  [<ffffffffc0008019>] ? sample_init+0x19/0x1000 [sample]
    [ 1884.688004]  [<ffffffff8100213d>] do_one_initcall+0xcd/0x1f0
    [ 1884.688004]  [<ffffffff811deafd>] ? kmem_cache_alloc_trace+0x1ad/0x220
    [ 1884.688004]  [<ffffffff81183ca4>] ? do_init_module+0x27/0x1d2
    [ 1884.688004]  [<ffffffff81183cdd>] do_init_module+0x60/0x1d2
    [ 1884.688004]  [<ffffffff81104134>] load_module+0x1424/0x1b10
    [ 1884.688004]  [<ffffffff81100920>] ? __symbol_put+0x40/0x40
    [ 1884.688004]  [<ffffffff81206be1>] ? kernel_read+0x41/0x60
    [ 1884.688004]  [<ffffffff811049ee>] SYSC_finit_module+0x7e/0xa0
    [ 1884.688004]  [<ffffffff81104a2e>] SyS_finit_module+0xe/0x10
    [ 1884.688004]  [<ffffffff8180b776>] entry_SYSCALL_64_fastpath+0x16/0x75