问:
Fix Cassandra Python RestApi
I have the following code to list the keyspaces of the Apache Cassandra database (Rest Api). The problem is the code version of the Apache Cassandra database that was done with the 2.0.

Select keyspace_name from schema_keyspaces does not work in version 3.0 and if I replace the query with: SELECT * FROM system_schema.keyspaces that works in version 3.0 I have the following error:

```<code>from math import ceil
class Pagination(object):
def __init__(self, page, per_page, total_count):
    self.page = page
    self.per_page = per_page
    self.total_count = total_count

@property
def pages(self):
    return int(ceil(self.total_count / float(self.per_page)))

@property
def has_prev(self):
    return self.page > 1

@property
def has_next(self):
    return self.page < self.pages

def iter_pages(self, left_edge=2, left_current=2,
               right_current=5, right_edge=2):
    last = 0
    for num in xrange(1, self.pages + 1):
        if num <= left_edge or \
           (num > self.page - left_current - 1 and \
            num < self.page + right_current) or \
           num > self.pages - right_edge:
            if last + 1 != num:
                yield None
            yield num
            last = num
@app.route('/keyspaces/', defaults={'page': 1}, methods=['GET'])
@app.route('/keyspaces/page/<int:page>', methods=['GET'])
def getKeyspaces(page):
auth_provider = PlainTextAuthProvider(username='admin',
        password='root')
cluster = Cluster(['hostname'],
                  auth_provider=auth_provider)
session = cluster.connect()
rows = session.execute('select keyspace_name from schema_keyspaces')
keyspaces = []
for row in range(len(rows)):
    keyspaces.append(rows[row][0])
    pages = keyspaces[(page - 1) * PER_PAGE:PER_PAGE * page]
    if not pages and page != 1:
        abort(404)
        pagination = Pagination(page, PER_PAGE, len(rows))
        return render_template('listkeyspace.html',
                               pagination=pagination, pages=pages,
                               section='getKeyspaces')
</code>```

答:
According to the docs, ResultSet is an iterator. If you want to be able to index into the results, you will first need to convert the iterator into a list, thus iterating through all the results first:

```<code>rows = session.execute('select keyspace_name from schema_keyspaces')
row_list = list(rows)
for row in range(len(row_list)):
    ...
</code>```

and then index into row_list rather than rows throughout the body of your loop

Title: Fix Cassandra Python RestApi

Body:
I have the following code to list the keyspaces of the Apache Cassandra database (Rest Api). The problem is the code version of the Apache Cassandra database that was done with the 2.0.

Select keyspace_name from schema_keyspaces does not work in version 3.0 and if I replace the query with: SELECT * FROM system_schema.keyspaces that works in version 3.0 I have the following error:

from math import ceil
class Pagination(object):
def __init__(self, page, per_page, total_count):
    self.page = page
    self.per_page = per_page
    self.total_count = total_count

@property
def pages(self):
    return int(ceil(self.total_count / float(self.per_page)))

@property
def has_prev(self):
    return self.page > 1

@property
def has_next(self):
    return self.page < self.pages

def iter_pages(self, left_edge=2, left_current=2,
               right_current=5, right_edge=2):
    last = 0
    for num in xrange(1, self.pages + 1):
        if num <= left_edge or \
           (num > self.page - left_current - 1 and \
            num < self.page + right_current) or \
           num > self.pages - right_edge:
            if last + 1 != num:
                yield None
            yield num
            last = num
@app.route('/keyspaces/', defaults={'page': 1}, methods=['GET'])
@app.route('/keyspaces/page/<int:page>', methods=['GET'])
def getKeyspaces(page):
auth_provider = PlainTextAuthProvider(username='admin',
        password='root')
cluster = Cluster(['hostname'],
                  auth_provider=auth_provider)
session = cluster.connect()
rows = session.execute('select keyspace_name from schema_keyspaces')
keyspaces = []
for row in range(len(rows)):
    keyspaces.append(rows[row][0])
    pages = keyspaces[(page - 1) * PER_PAGE:PER_PAGE * page]
    if not pages and page != 1:
        abort(404)
        pagination = Pagination(page, PER_PAGE, len(rows))
        return render_template('listkeyspace.html',
                               pagination=pagination, pages=pages,
                               section='getKeyspaces')

Body:
According to the docs, ResultSet is an iterator. If you want to be able to index into the results, you will first need to convert the iterator into a list, thus iterating through all the results first:

rows = session.execute('select keyspace_name from schema_keyspaces')
row_list = list(rows)
for row in range(len(row_list)):
    ...

and then index into row_list rather than rows throughout the body of your loop


来源: stackexchange

问:
Can i retrieve array value not using loop?
is there a way to retrieve array value not using any loop function?
I have this sort of array</p>

```<code>$at=array(
    array(
        array('Title:','titl','s','c',$titles),
        array('First Name:','name','i','A',2,10 ),
    ),
</code>```

答:
Your example looks like it's probably one level too deep, but to directly work with a more basic example:</p>

```<code>$at=array( array('Title:','titl','s','c',$titles), array('First Name:','name','i','A',2,10 )

list($title, $something, $foo, $bar) = current($at);

echo $title;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
is there a way to retrieve array value not using any loop function?
I have this sort of array

$at=array(
    array(
        array('Title:','titl','s','c',$titles),
        array('First Name:','name','i','A',2,10 ),
    ),

Body:
Your example looks like it's probably one level too deep, but to directly work with a more basic example:

$at=array( array('Title:','titl','s','c',$titles), array('First Name:','name','i','A',2,10 )

list($title, $something, $foo, $bar) = current($at);

echo $title;


问:
Click one of contact in contact list in whatsapp web (javascript)
I try to use JavaScript to perform a click action to click a contact form contact list in order to open a chat in Whatsapp Web.

I use normal click action to click but not working, like

```<code>var div = document.querySelector('.infinite-list-item')[0];
div.click();
</code>```

And i know whatsapp web is made by react js, ant special to perform a click?

I even use jQuery click() function but still not working, what should I use?

答:
You're using document.querySelector() and then trying to access it as if it was a data structure.

document.querySelector() will return only one DOM element. You should try using document.querySelectorAll()[0] if you want to put all the contacts in a structure.

Solution:

```<code>    var itemList = document.querySelectorAll('.infinite-list-item');
    itemList[0].click();
</code>```

Also, this would work as an alternative solution ( though using querySelector instead of querySelectorAll to target a class name that is used more than once is not at all recommended ):

```<code>    var div = document.querySelector('.infinite-list-item');
    div.click();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I try to use JavaScript to perform a click action to click a contact form contact list in order to open a chat in Whatsapp Web.

I use normal click action to click but not working, like

var div = document.querySelector('.infinite-list-item')[0];
div.click();

And i know whatsapp web is made by react js, ant special to perform a click?

I even use jQuery click() function but still not working, what should I use?

Body:
You're using document.querySelector() and then trying to access it as if it was a data structure.

document.querySelector() will return only one DOM element. You should try using document.querySelectorAll()[0] if you want to put all the contacts in a structure.

Solution:

    var itemList = document.querySelectorAll('.infinite-list-item');
    itemList[0].click();

Also, this would work as an alternative solution ( though using querySelector instead of querySelectorAll to target a class name that is used more than once is not at all recommended ):

    var div = document.querySelector('.infinite-list-item');
    div.click();


问:
How to set the module name of a dynamically created class?
I am using Python 3 to create a dynamic class:

```<code>def setup(namespace):
    namespace['a'] = 1

A = types.new_class('A', bases=(), kwds=None, exec_body=setup)

class B:
    b = 2

print(A)
print(B)
</code>```

Output:

```<code><class 'types.A'>
<class '__main__.B'>
</code>```

I would like to put the class A also in the __main__ module/scope (instead of the types module/scope). How can that be done?

答:
Just set the __module__ attribute after the fact:

```<code>A.__module__ == '__main__'
</code>```

You can do this in the exec_body callable:

```<code>def setup(namespace):
    namespace['a'] = 1
    namespace['__module__'] = '__main__'
</code>```

Demo:

```<code>>>> import types
>>> def setup(namespace):
...     namespace['a'] = 1
...
>>> A = types.new_class('A', bases=(), kwds=None, exec_body=setup)
>>> A.__module__ = '__main__'
>>> A
<class '__main__.A'>
</code>```

or with the exec_body() callable:

```<code>>>> def setup(namespace):
...     namespace['a'] = 1
...     namespace['__module__'] = '__main__'
...
>>> A = types.new_class('A', bases=(), kwds=None, exec_body=setup)
>>> A
<class '__main__.A'>
</code>```

Body:
I am using Python 3 to create a dynamic class:

def setup(namespace):
    namespace['a'] = 1

A = types.new_class('A', bases=(), kwds=None, exec_body=setup)

class B:
    b = 2

print(A)
print(B)

Output:

<class 'types.A'>
<class '__main__.B'>

I would like to put the class A also in the __main__ module/scope (instead of the types module/scope). How can that be done?

Body:
Just set the __module__ attribute after the fact:

A.__module__ == '__main__'

You can do this in the exec_body callable:

def setup(namespace):
    namespace['a'] = 1
    namespace['__module__'] = '__main__'

Demo:

>>> import types
>>> def setup(namespace):
...     namespace['a'] = 1
...
>>> A = types.new_class('A', bases=(), kwds=None, exec_body=setup)
>>> A.__module__ = '__main__'
>>> A
<class '__main__.A'>

or with the exec_body() callable:

>>> def setup(namespace):
...     namespace['a'] = 1
...     namespace['__module__'] = '__main__'
...
>>> A = types.new_class('A', bases=(), kwds=None, exec_body=setup)
>>> A
<class '__main__.A'>


问:
Recursive listing of a particular file type in Windows PowerShell
I was trying to recursively list using ls all the *.py files in a directory in Windows PowerShell. It didn't work. I checked up on the man page and then online page that -Recurse flag doesn't accept wildcards so *.py wouldn't work.

I want to know whether there is a simple in-built way to recursively list the files of a particular file extension in a directory using Windows PowerShell 2.0?

I am a newbie in PowerShell and don't want to indulge in Shell scripting at this stage. So please recommend in-built commands, flags, etc. only, if any.

By commands I means the in-built keywords of the PowerShell. I am not sure if that is proper vocabulary for PowerShell.

答:
ls is an alias for Get-ChildItem. (So is dir and gci). A simple Google will give you all kinds of examples but the thing to know is -include (or -exclude) are built in parameters that will show (or not show) file types you are looking for. An additional parameter, -filter, can also be used for partial file types. The switch parameter -recurse checks the contents of subfolders in the directory as well. Example01:
gci -path \$computername\$directory -Include *.py -recurse
Example02:
gci -path \$computername\$directory -Filter *.py -recurse

I like to suppress errors so a full example would look like this:
gci -path \Svr01\C$ -Include *.py -recurse -erroraction SilentlyContinue


问:
Why can't I access a variable declared in derived class with the object of base class
Good Evening everyone

I have created two classes namely Shape, Rectangle with Draw() method in both the classes, Rectangle class  is a derived class from Shape. I have declared a public variable  in Rectangle called num and initialized a value to it.

In the main class I have created an object of type class in following manner.

```<code>Shape s = new Rectangle();
</code>```

Now when I am trying to access num variable of rectangle class it gives error saying

“ /Users/apple/Projects/Practice/Practice/Program.cs(33,33): Error
  CS1061: 'Shape' does not contain a definition for 'num' and no
  extension method 'num' accepting a first argument of type 'Shape'
  could be found (are you missing a using directive or an assembly
  reference?) (CS1061) (Practice)”

My Understanding : The statement new Rectangle(); creates an object of type Rectangle in the memory and its reference is stored in object s of type Shape. So the object s should have access to variable num defined in rectangle class. Please make me understand this concept why we can’t access num variable from Object of type Shape.

Pls find the attached screenshot.

答:
You could access s.num in a dynamic language. In a dynamic language, the type tests and tests for availability of members are performed at runtime. The runtime type of s is Rectangle, i.e. s references an object of type Rectangle. However, C# is a statically and strongly typed language. I.e. these tests are performed at compile-time. At compile-time, only members available through the static type of s are visible. num is not a member of the static type Shape and is therefore invisible.

The Shape object (indeed any class) sees its own members and members of its ancestors, i.e. inherited members, if they are public or protected. It cannot see members of derived classes (here Rectangle), since they are not declared in Shape, nor are they known at compile time, if the 2 classes are declared in 2 different assemblies.

A base class must contain everything which is common to itself and its descendants.
If you still want to access Rectangle stuff from a Shape variable, you can cast (assuming VS 2017):

```<code>if (shape is Rectangle rect) {
    var x = rect.num;
}
</code>```

However, this is often a sign of a bad OO-design. In this case, you could simply override ToString

```<code>public class Rectangle : Shape
{
    private int num = 10;

    ...

    public override string ToString()
    {
        return $"Rectangle num = {num}";
    }
}
</code>```

...

```<code>Shape shape = new Rectangle();
Console.WriteLine(shape); // Uses ToString() of rectangle.
</code>```

Body:
Good Evening everyone

I have created two classes namely Shape, Rectangle with Draw() method in both the classes, Rectangle class  is a derived class from Shape. I have declared a public variable  in Rectangle called num and initialized a value to it.

In the main class I have created an object of type class in following manner.

Shape s = new Rectangle();

Now when I am trying to access num variable of rectangle class it gives error saying

“ /Users/apple/Projects/Practice/Practice/Program.cs(33,33): Error
  CS1061: 'Shape' does not contain a definition for 'num' and no
  extension method 'num' accepting a first argument of type 'Shape'
  could be found (are you missing a using directive or an assembly
  reference?) (CS1061) (Practice)”

My Understanding : The statement new Rectangle(); creates an object of type Rectangle in the memory and its reference is stored in object s of type Shape. So the object s should have access to variable num defined in rectangle class. Please make me understand this concept why we can’t access num variable from Object of type Shape.

Pls find the attached screenshot.

Body:
You could access s.num in a dynamic language. In a dynamic language, the type tests and tests for availability of members are performed at runtime. The runtime type of s is Rectangle, i.e. s references an object of type Rectangle. However, C# is a statically and strongly typed language. I.e. these tests are performed at compile-time. At compile-time, only members available through the static type of s are visible. num is not a member of the static type Shape and is therefore invisible.

The Shape object (indeed any class) sees its own members and members of its ancestors, i.e. inherited members, if they are public or protected. It cannot see members of derived classes (here Rectangle), since they are not declared in Shape, nor are they known at compile time, if the 2 classes are declared in 2 different assemblies.

A base class must contain everything which is common to itself and its descendants.
If you still want to access Rectangle stuff from a Shape variable, you can cast (assuming VS 2017):

if (shape is Rectangle rect) {
    var x = rect.num;
}

However, this is often a sign of a bad OO-design. In this case, you could simply override ToString

public class Rectangle : Shape
{
    private int num = 10;

    ...

    public override string ToString()
    {
        return $"Rectangle num = {num}";
    }
}

...

Shape shape = new Rectangle();
Console.WriteLine(shape); // Uses ToString() of rectangle.


问:
Random number generator that returns unique entries in sorted order
I need a generator for many (up to one trillion, 10^12) unique random 64-bit numbers.
The generator needs to return the numbers in sorted order (Long.MIN_VALUE to Long.MAX_VALUE). The problem is that sorting $10^{12}$ numbers is slow. The use case is replicating a test that was run for BBHash (in the paper, 4.5 Indexing a trillion keys).

The straightforward solution is to create a set in memory, using a huge bit set or so
to ensure no duplicates are returned.
But that uses too much memory or I/O.
I'd like to use at most a few MB of internal state.

The generator should use a java.util.Random internally.
It should be as "fair" as possible (have the same statistical distribution as if generated otherwise). I would also like to have a version for 128-bit numbers (2 longs).

What I have so far is code to create a set in memory (Java code):

```<code>public static void main(String... args) {
    for(long x : randomSet(10, 0)) {
        System.out.println(x);
    }
}

static Iterable<Long> randomSet(int size, int seed) {
    Random r = new Random(seed);
    TreeSet<Long> set = new TreeSet<Long>();
    while (set.size() < size) {
        set.add(r.nextLong());
    }
    return set;
}

-8292973307042192125
-7423979211207825555
-6688467811848818630
-4962768465676381896
-2228689144322150137
-1083761183081836303
-279624296851435688
4437113781045784766
6146794652083548235
7105486291024734541
</code>```

The simplest (wrong) solution, which is not random, is to distribute the results evenly.
I don't think a solution along the line of "add a random gap" will work,
because it is slow, and the sum of such gaps, after 10^12, will not land where it should (well, maybe: remember how many numbers are left, then re-calculate the distribution...). I think the following should work, but is complex, and not sure what formulas to use: for each bit level,
recursively, calculating how many 0s / 1s will likely occur
(using the Binomial distribution or the approximation, the normal / Gaussian distribution, somehow).
Stop at some point (say, blocks of 1 million entries or less),
use the code above, for speed.
But maybe there is an elegant solution.
Maybe this is related to the Metropolis–Hastings algorithm, not sure.
I read "An Efficient Algorithm for Sequential Random Sampling",
but I think it is only for small n, and I find it hard to get to a simple algorithm from this.

Java code would be best, but C is fine (anyway at some point I might have to convert it to C / C++). I would like to not use too many libraries, to simplify porting.

答:
I have a solution.

(It turns out, generating 100'000 or more entries in roughly sorted order is faster than generating using a large HashSet. Roughly sorted means replace TreeSet with a HashSet, and using a limit of 10'000 instead of 5. This is because testing for duplicates is much faster.)

Random number of entries for each fixed (sub-)range

Create a tree: For each bit level (starting with the most significant bit), recursively generate a random number of how many entries should have the bit at that level set to 0, using the normal distribution. The remaining entries have the bit at this level set to 1. At each recursion level, this will narrow the range by about half. Stop for example when there are less than 1 million entries, and then switch to using an in-memory pseudo-RNG and sort those numbers (or use a bit field).

Here some code (not tested yet):

```<code>public static void main(String... args) {
    Random r = new Random();
    Iterator<Long> it = randomSequence(r, 10, 32);
    while(it.hasNext()) {
        System.out.println(it.next());
    }
}

/**
 * Random sequence generator.
 *
 * @param r the random generator
 * @param size the number of entries to generate
 * @param shift the number of bits of the result
 * @return the iterator
 */
static Iterator<Long> randomSequence(final Random r, final long size, final int shift) {
    if (size < 5) {
        // small lists are generated using a regular hash set
        TreeSet<Long> set = new TreeSet<Long>();
        while (set.size() < size) {
            set.add(r.nextLong() & ((2L << shift) - 1));
        }
        return set.iterator();
    }
    // large lists are created recursively
    return new Iterator<Long>() {
        long remaining = size, zeros = randomHalf(r, size);
        Iterator<Long> lowBits0 = randomSequence(r, zeros, shift - 1);
        Iterator<Long> lowBits1;
        @Override
        public boolean hasNext() {
            return remaining > 0;
        }
        @Override
        public Long next() {
            remaining--;
            if (lowBits0.hasNext()) {
                return lowBits0.next();
            }
            if (lowBits1 == null) {
                lowBits1 = randomSequence(r, size - zeros, shift - 1);
            }
            return (1L << shift) + lowBits1.next();
        }
    };
}

/**
 * Get the number of entries that are supposed to be below the half,
 * according to the probability theory. For example, for a number of coin
 * flips, how many are heads.
 *
 * @param r the random generator
 * @param samples the total number of entries
 * @return the number of entries that should be used for one half
 */
static long randomHalf(Random r, long samples) {
    long low = 0, high = samples;
    double x = r.nextDouble();
    while (low + 1 < high) {
        long mid = (low + high) / 2;
        double p = probabilityBucketAtMost(samples, mid);
        if (x > p) {
            low = mid;
        } else {
            high = mid;
        }
    }
    return (low + high) / 2;
}

static double probabilityBucketAtMost(long flips, long heads) {
    // https://www.fourmilab.ch/rpkp/experiments/statistics.html
    long x = heads;
    long n = flips;
    double variance = Math.sqrt(n/4);
    // mean
    long mu = n / 2;
    // https://en.wikipedia.org/wiki/Normal_distribution
    // Numerical approximations for the normal CDF
    // the probability that the value of a standard normal random variable X is <= x
    return phi((x - mu) / variance);
}

static double phi(double x) {
    return 0.5 * (1 + Math.signum(x) * Math.sqrt(1 - Math.exp(-2 * x * x / Math.PI)));
}
</code>```

Body:
I need a generator for many (up to one trillion, 10^12) unique random 64-bit numbers.
The generator needs to return the numbers in sorted order (Long.MIN_VALUE to Long.MAX_VALUE). The problem is that sorting $10^{12}$ numbers is slow. The use case is replicating a test that was run for BBHash (in the paper, 4.5 Indexing a trillion keys).

The straightforward solution is to create a set in memory, using a huge bit set or so
to ensure no duplicates are returned.
But that uses too much memory or I/O.
I'd like to use at most a few MB of internal state.

The generator should use a java.util.Random internally.
It should be as "fair" as possible (have the same statistical distribution as if generated otherwise). I would also like to have a version for 128-bit numbers (2 longs).

What I have so far is code to create a set in memory (Java code):

public static void main(String... args) {
    for(long x : randomSet(10, 0)) {
        System.out.println(x);
    }
}

static Iterable<Long> randomSet(int size, int seed) {
    Random r = new Random(seed);
    TreeSet<Long> set = new TreeSet<Long>();
    while (set.size() < size) {
        set.add(r.nextLong());
    }
    return set;
}

-8292973307042192125
-7423979211207825555
-6688467811848818630
-4962768465676381896
-2228689144322150137
-1083761183081836303
-279624296851435688
4437113781045784766
6146794652083548235
7105486291024734541

The simplest (wrong) solution, which is not random, is to distribute the results evenly.
I don't think a solution along the line of "add a random gap" will work,
because it is slow, and the sum of such gaps, after 10^12, will not land where it should (well, maybe: remember how many numbers are left, then re-calculate the distribution...). I think the following should work, but is complex, and not sure what formulas to use: for each bit level,
recursively, calculating how many 0s / 1s will likely occur
(using the Binomial distribution or the approximation, the normal / Gaussian distribution, somehow).
Stop at some point (say, blocks of 1 million entries or less),
use the code above, for speed.
But maybe there is an elegant solution.
Maybe this is related to the Metropolis–Hastings algorithm, not sure.
I read "An Efficient Algorithm for Sequential Random Sampling",
but I think it is only for small n, and I find it hard to get to a simple algorithm from this.

Java code would be best, but C is fine (anyway at some point I might have to convert it to C / C++). I would like to not use too many libraries, to simplify porting.

Body:
I have a solution.

(It turns out, generating 100'000 or more entries in roughly sorted order is faster than generating using a large HashSet. Roughly sorted means replace TreeSet with a HashSet, and using a limit of 10'000 instead of 5. This is because testing for duplicates is much faster.)

Random number of entries for each fixed (sub-)range

Create a tree: For each bit level (starting with the most significant bit), recursively generate a random number of how many entries should have the bit at that level set to 0, using the normal distribution. The remaining entries have the bit at this level set to 1. At each recursion level, this will narrow the range by about half. Stop for example when there are less than 1 million entries, and then switch to using an in-memory pseudo-RNG and sort those numbers (or use a bit field).

Here some code (not tested yet):

public static void main(String... args) {
    Random r = new Random();
    Iterator<Long> it = randomSequence(r, 10, 32);
    while(it.hasNext()) {
        System.out.println(it.next());
    }
}

/**
 * Random sequence generator.
 *
 * @param r the random generator
 * @param size the number of entries to generate
 * @param shift the number of bits of the result
 * @return the iterator
 */
static Iterator<Long> randomSequence(final Random r, final long size, final int shift) {
    if (size < 5) {
        // small lists are generated using a regular hash set
        TreeSet<Long> set = new TreeSet<Long>();
        while (set.size() < size) {
            set.add(r.nextLong() & ((2L << shift) - 1));
        }
        return set.iterator();
    }
    // large lists are created recursively
    return new Iterator<Long>() {
        long remaining = size, zeros = randomHalf(r, size);
        Iterator<Long> lowBits0 = randomSequence(r, zeros, shift - 1);
        Iterator<Long> lowBits1;
        @Override
        public boolean hasNext() {
            return remaining > 0;
        }
        @Override
        public Long next() {
            remaining--;
            if (lowBits0.hasNext()) {
                return lowBits0.next();
            }
            if (lowBits1 == null) {
                lowBits1 = randomSequence(r, size - zeros, shift - 1);
            }
            return (1L << shift) + lowBits1.next();
        }
    };
}

/**
 * Get the number of entries that are supposed to be below the half,
 * according to the probability theory. For example, for a number of coin
 * flips, how many are heads.
 *
 * @param r the random generator
 * @param samples the total number of entries
 * @return the number of entries that should be used for one half
 */
static long randomHalf(Random r, long samples) {
    long low = 0, high = samples;
    double x = r.nextDouble();
    while (low + 1 < high) {
        long mid = (low + high) / 2;
        double p = probabilityBucketAtMost(samples, mid);
        if (x > p) {
            low = mid;
        } else {
            high = mid;
        }
    }
    return (low + high) / 2;
}

static double probabilityBucketAtMost(long flips, long heads) {
    // https://www.fourmilab.ch/rpkp/experiments/statistics.html
    long x = heads;
    long n = flips;
    double variance = Math.sqrt(n/4);
    // mean
    long mu = n / 2;
    // https://en.wikipedia.org/wiki/Normal_distribution
    // Numerical approximations for the normal CDF
    // the probability that the value of a standard normal random variable X is <= x
    return phi((x - mu) / variance);
}

static double phi(double x) {
    return 0.5 * (1 + Math.signum(x) * Math.sqrt(1 - Math.exp(-2 * x * x / Math.PI)));
}


问:
regex to parse import statements in python
can someone help me writing single regex to get module(s) from python source line?

```<code>from abc.lmn import pqr
from abc.lmn import pqr as xyz
import abc
import abc as xyz
</code>```

it has 3 sub parts in it

```<code>[from(\s)<module>(\s)] --> get module if this part exist
import(\s)<module>     --> get module
[(\s)as(\s)<alias>]    --> ignore if this part exist
</code>```

something like this

```<code>:?[from(\s)<module>(\s)]import(\s)<module>:?[(\s)as(\s)<alias>]
</code>```

答:
Instead of using a regex, using the built in python library ast might be a better approach.  https://docs.python.org/2/library/ast.html  You can use it to parse python syntax.

```<code>import ast

import_string = """from abc.lmn import pqr
from abc.lmn import pqr as xyz
import abc
import abc as xyz"""

modules = []
for node in ast.iter_child_nodes(ast.parse(import_string)):
    if isinstance(node, ast.ImportFrom):
        if not node.names[0].asname:  # excluding the 'as' part of import
            modules.append(node.module)
    elif isinstance(node, ast.Import): # excluding the 'as' part of import
        if not node.names[0].asname:
            modules.append(node.names[0].name)
</code>```

that will give you ['abc.lmn', 'abc'] and it is fairly easy to tweak if you want to pull other information.

Body:
can someone help me writing single regex to get module(s) from python source line?

from abc.lmn import pqr
from abc.lmn import pqr as xyz
import abc
import abc as xyz

it has 3 sub parts in it

[from(\s)<module>(\s)] --> get module if this part exist
import(\s)<module>     --> get module
[(\s)as(\s)<alias>]    --> ignore if this part exist

something like this

:?[from(\s)<module>(\s)]import(\s)<module>:?[(\s)as(\s)<alias>]

Body:
Instead of using a regex, using the built in python library ast might be a better approach.  https://docs.python.org/2/library/ast.html  You can use it to parse python syntax.

import ast

import_string = """from abc.lmn import pqr
from abc.lmn import pqr as xyz
import abc
import abc as xyz"""

modules = []
for node in ast.iter_child_nodes(ast.parse(import_string)):
    if isinstance(node, ast.ImportFrom):
        if not node.names[0].asname:  # excluding the 'as' part of import
            modules.append(node.module)
    elif isinstance(node, ast.Import): # excluding the 'as' part of import
        if not node.names[0].asname:
            modules.append(node.names[0].name)

that will give you ['abc.lmn', 'abc'] and it is fairly easy to tweak if you want to pull other information.


问:
Remove Style in Materializecss inputs
How can completely remove the styling of inputs in materializecss? Changing the CSS alone doesn't seem to work as expected. </p>

答:
The easiest way to remove the styling of inputs in materializecss is to download the sass file and remove the elements you dont wish to be imported. After that you just have to compile sass to css.

View the source of this if you want to download the compiled css file from which the input styling was removed.

How to install/use sass

Title: Remove Style in Materializecss inputs


问:
Return empty string when placeholder is shown
I have a custom text box with placeholder effect. If the textbox is empty, the placeholder is shown.

When I pass the value of the textbox (when the textbox is empty and the placeholder is shown instead) to a function , it passes the placeholder value, but I want it to just pass an empty string.

I thought about overriding the Text property and do an internal check. Something like

```<code>public string Text
{
    get
    {
        if (this.Text == this.Placeholder)
        {
            return "";
        }
        return this.Text;
    }
    set
    {
        this.Text = value;
    }
}
</code>```

but I don't know if this is possible. This would create an infinite loop, I think. How do I make this work?

I know I can use a custom property (e.g., ActualText instead of Text) to do this, but if it's possible, I'd like to use Text. If not, I'll use a custom property.

```<code>using System;
using System.Drawing;
using System.Windows.Forms;
using CustomExtensions;

namespace CustomControls
{
    public class CustomTextBox : TextBox
    {
        private string _placeholder;

        public string Placeholder
        {
            get
            {
                return this._placeholder;
            }
            set
            {
                this._placeholder = value;
                if (value.IsEmpty(true))
                {
                    this._placeholder = "";
                }
                else
                {
                    this._placeholder = value;
                }
            }
        }

        public CustomTextBox()
        {
            Initialize();
        }

        private void Initialize()
        {
            this.Enter += new EventHandler(this.Placeholder_Hide);
            this.Leave += new EventHandler(this.Placeholder_Show);
        }

        // called from MainForm_Load
        public void InitPH()
        {
            if (!this.Placeholder.IsEmpty(true) && this.Text.IsEmpty())
            {
                this.Text = this.Placeholder;
                this.ForeColor = Color.Gray;
                this.Font = new Font("Segoe UI", 10.2F, FontStyle.Italic);
            }
        }

        private void Placeholder_Hide(object sender, EventArgs e)
        {
            if (this.Text == this._placeholder)
            {
                this.Text = "";
                this.ForeColor = Color.Black;
                this.Font = new Font("Segoe UI", 10.2F, FontStyle.Regular);
            }
        }

        private void Placeholder_Show(object sender, EventArgs e)
        {
            if (this.IsEmpty())
            {
                this.Text = this._placeholder;
                this.ForeColor = Color.Gray;
                this.Font = new Font("Segoe UI", 10.2F, FontStyle.Italic);
            }
        }

        public bool IsEmpty()
        {
            return this.Text.IsEmpty(true, this.Placeholder);
        }
    }
}
</code>```

答:
You can set a cue text on the TextBox that won't affect the Text property. See EM_SETCUEBANNER for more information.

Define the following on your Form

```<code>private const int EM_SETCUEBANNER = 0x1501;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern Int32 SendMessage(IntPtr hWnd, int msg, int wParam, [MarshalAs(UnmanagedType.LPWStr)]string lParam);
</code>```

Then in your Form Load

```<code>protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    SendMessage(textBox1.Handle, EM_SETCUEBANNER, 0, "http://example.com");
}
</code>```

Body:
I have a custom text box with placeholder effect. If the textbox is empty, the placeholder is shown.

When I pass the value of the textbox (when the textbox is empty and the placeholder is shown instead) to a function , it passes the placeholder value, but I want it to just pass an empty string.

I thought about overriding the Text property and do an internal check. Something like

public string Text
{
    get
    {
        if (this.Text == this.Placeholder)
        {
            return "";
        }
        return this.Text;
    }
    set
    {
        this.Text = value;
    }
}

but I don't know if this is possible. This would create an infinite loop, I think. How do I make this work?

I know I can use a custom property (e.g., ActualText instead of Text) to do this, but if it's possible, I'd like to use Text. If not, I'll use a custom property.

using System;
using System.Drawing;
using System.Windows.Forms;
using CustomExtensions;

namespace CustomControls
{
    public class CustomTextBox : TextBox
    {
        private string _placeholder;

        public string Placeholder
        {
            get
            {
                return this._placeholder;
            }
            set
            {
                this._placeholder = value;
                if (value.IsEmpty(true))
                {
                    this._placeholder = "";
                }
                else
                {
                    this._placeholder = value;
                }
            }
        }

        public CustomTextBox()
        {
            Initialize();
        }

        private void Initialize()
        {
            this.Enter += new EventHandler(this.Placeholder_Hide);
            this.Leave += new EventHandler(this.Placeholder_Show);
        }

        // called from MainForm_Load
        public void InitPH()
        {
            if (!this.Placeholder.IsEmpty(true) && this.Text.IsEmpty())
            {
                this.Text = this.Placeholder;
                this.ForeColor = Color.Gray;
                this.Font = new Font("Segoe UI", 10.2F, FontStyle.Italic);
            }
        }

        private void Placeholder_Hide(object sender, EventArgs e)
        {
            if (this.Text == this._placeholder)
            {
                this.Text = "";
                this.ForeColor = Color.Black;
                this.Font = new Font("Segoe UI", 10.2F, FontStyle.Regular);
            }
        }

        private void Placeholder_Show(object sender, EventArgs e)
        {
            if (this.IsEmpty())
            {
                this.Text = this._placeholder;
                this.ForeColor = Color.Gray;
                this.Font = new Font("Segoe UI", 10.2F, FontStyle.Italic);
            }
        }

        public bool IsEmpty()
        {
            return this.Text.IsEmpty(true, this.Placeholder);
        }
    }
}

Body:
You can set a cue text on the TextBox that won't affect the Text property. See EM_SETCUEBANNER for more information.

Define the following on your Form

private const int EM_SETCUEBANNER = 0x1501;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern Int32 SendMessage(IntPtr hWnd, int msg, int wParam, [MarshalAs(UnmanagedType.LPWStr)]string lParam);

Then in your Form Load

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    SendMessage(textBox1.Handle, EM_SETCUEBANNER, 0, "http://example.com");
}


问:
Jar not found in Maven Repository
I am trying to add a dependency in my project(i am using maven) however the jar i want to add it seems like it does not exist in the maven central repository.The jar i want to add is Neko HTML jar version 1.9.22.When i am searching for the jar through the add dependency dialog from netbeans the jar is not displayed,however the jar seems to exist on the maven central repository->https://mvnrepository.com/artifact/net.sourceforge.nekohtml/nekohtml/1.9.22(Search through google)

Then result i get from the add dependency dialog is this ->
https://www.dropbox.com/s/wo1ix3lefwxy91a/DepDialog.JPG?dl=0

I did not manage to find a solution,so i would appreciate it if someone could help me figure this out.

Title: Jar not found in Maven Repository

Body:
http://repo1.maven.org/maven2/net/sourceforge/nekohtml/nekohtml/1.9.22/

<groupId>net.sourcefourge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.19.22</version>


问:
MongoDB returns nothing?

I am trying to run Perl with MongoDB but I get nothing

use MongoDB;
use Data::Dumper;

my $client = MongoDB::connect("mongodb://admin:admin123@localhost");
my $db = $client->get_database( 'admin' );
my $x = $db->get_collection( 'inventory' );
my $y = $x->find({"item" => "journal"});
print Dumper($y->all);
```

<p>In the <code>mongo</code> client, I get this</p>

<pre class="lang-none prettyprint-override"><code>mongo -u admin -p admin123 --authenticationDatabase admin
MongoDB shell version: 3.2.15
connecting to: test
Server has startup warnings:
2017-07-08T08:28:16.694-0500 I CONTROL  [initandlisten]
2017-07-08T08:28:16.694-0500 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2017-07-08T08:28:16.694-0500 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2017-07-08T08:28:16.694-0500 I CONTROL  [initandlisten]
> db.inventory.find({})
{ "_id" : ObjectId("5960dec814a535e879221157"), "item" : "journal", "qty" : 26, "size" : { "h" : 17, "w" : 21, "uom" : "cm" }, "status" : "B" }
{ "_id" : ObjectId("5960dec814a535e879221158"), "item" : "notebook", "qty" : 50, "size" : { "h" : 8.5, "w" : 11, "uom" : "in" }, "status" : "A" }
{ "_id" : ObjectId("5960dec814a535e879221159"), "item" : "paper", "qty" : 100, "size" : { "h" : 8.5, "w" : 11, "uom" : "in" }, "status" : "D" }
{ "_id" : ObjectId("5960dec814a535e87922115a"), "item" : "planner", "qty" : 75, "size" : { "h" : 22.85, "w" : 30, "uom" : "cm" }, "status" : "D" }
{ "_id" : ObjectId("5960dec814a535e87922115b"), "item" : "postcard", "qty" : 45, "size" : { "h" : 10, "w" : 15.25, "uom" : "cm" }, "status" : "A" }
{ "_id" : ObjectId("5960e7bb14a535e87922115c"), "foo" : { "a" : [ 1, 2, 3 ] } }
{ "_id" : ObjectId("5960e87614a535e87922115d"), "foo" : { "a" : [ 2, 3, 4 ] } }
{ "_id" : ObjectId("5960e87c14a535e87922115e"), "foo" : { "a" : [ 5, 3, 4 ] } }
>
</code>```

答:
First of all, you must always start every Perl program you write with

```<code>use strict;
use warnings 'all';
</code>```

and please use better identifiers than $x and $y

You're calling connect as a simple subroutine when it should be a class method. Change

```<code>my $client = MongoDB::connect("mongodb://admin:admin123@localhost")
</code>```

to

```<code>my $client = MongoDB->connect("mongodb://admin:admin123@localhost")
</code>```

Title: MongoDB returns nothing?

Body:
I am trying to run Perl with MongoDB but I get nothing

use MongoDB;
use Data::Dumper;

my $client = MongoDB::connect("mongodb://admin:admin123@localhost");
my $db = $client->get_database( 'admin' );
my $x = $db->get_collection( 'inventory' );
my $y = $x->find({"item" => "journal"});
print Dumper($y->all);

In the mongo client, I get this

mongo -u admin -p admin123 --authenticationDatabase admin
MongoDB shell version: 3.2.15
connecting to: test
Server has startup warnings:
2017-07-08T08:28:16.694-0500 I CONTROL  [initandlisten]
2017-07-08T08:28:16.694-0500 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2017-07-08T08:28:16.694-0500 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2017-07-08T08:28:16.694-0500 I CONTROL  [initandlisten]
> db.inventory.find({})
{ "_id" : ObjectId("5960dec814a535e879221157"), "item" : "journal", "qty" : 26, "size" : { "h" : 17, "w" : 21, "uom" : "cm" }, "status" : "B" }
{ "_id" : ObjectId("5960dec814a535e879221158"), "item" : "notebook", "qty" : 50, "size" : { "h" : 8.5, "w" : 11, "uom" : "in" }, "status" : "A" }
{ "_id" : ObjectId("5960dec814a535e879221159"), "item" : "paper", "qty" : 100, "size" : { "h" : 8.5, "w" : 11, "uom" : "in" }, "status" : "D" }
{ "_id" : ObjectId("5960dec814a535e87922115a"), "item" : "planner", "qty" : 75, "size" : { "h" : 22.85, "w" : 30, "uom" : "cm" }, "status" : "D" }
{ "_id" : ObjectId("5960dec814a535e87922115b"), "item" : "postcard", "qty" : 45, "size" : { "h" : 10, "w" : 15.25, "uom" : "cm" }, "status" : "A" }
{ "_id" : ObjectId("5960e7bb14a535e87922115c"), "foo" : { "a" : [ 1, 2, 3 ] } }
{ "_id" : ObjectId("5960e87614a535e87922115d"), "foo" : { "a" : [ 2, 3, 4 ] } }
{ "_id" : ObjectId("5960e87c14a535e87922115e"), "foo" : { "a" : [ 5, 3, 4 ] } }
>

Body:
First of all, you must always start every Perl program you write with

use strict;
use warnings 'all';

and please use better identifiers than $x and $y

You're calling connect as a simple subroutine when it should be a class method. Change

my $client = MongoDB::connect("mongodb://admin:admin123@localhost")

to

my $client = MongoDB->connect("mongodb://admin:admin123@localhost")


问:
Pandas pivot_table preserve order
```<code>>>> df
   A   B   C      D
0  foo one small  1
1  foo one large  2
2  foo one large  2
3  foo two small  3
4  foo two small  3
5  bar one large  4
6  bar one small  5
7  bar two small  6
8  bar two large  7
>>> table = pivot_table(df, values='D', index=['A', 'B'],
...                     columns=['C'], aggfunc=np.sum)
>>> table
          small  large
foo  one  1      4
     two  6      NaN
bar  one  5      4
     two  6      7
</code>```

I want the output to be as shown above, but I get a sorted output.
bar comes above foo and so on.

答:
While creating pivot_table, the index is automatically sorted  alphabetically. Not only foo and bar, you may also notice small and large is sorted. If you want foo on top, you may need to sort them again using sortlevel. If you are expecting output as in example here, then sorting on A and C both may be needed.

```<code>table.sortlevel(["A","B"], ascending= [False,True], sort_remaining=False, inplace=True)
table.sortlevel(["C"], axis=1, ascending=False,  sort_remaining=False, inplace=True)
print(table)
</code>```

Output:

```<code>C        small  large
A   B
foo one  1.0    4.0
    two  6.0    NaN
bar one  5.0    4.0
    two  6.0    7.0
</code>```

Update:

To remove index names A, B and C:

```<code>table.columns.name = None
table.index.names = (None, None)
</code>```

Title: Pandas pivot_table preserve order

Body:
>>> df
   A   B   C      D
0  foo one small  1
1  foo one large  2
2  foo one large  2
3  foo two small  3
4  foo two small  3
5  bar one large  4
6  bar one small  5
7  bar two small  6
8  bar two large  7
>>> table = pivot_table(df, values='D', index=['A', 'B'],
...                     columns=['C'], aggfunc=np.sum)
>>> table
          small  large
foo  one  1      4
     two  6      NaN
bar  one  5      4
     two  6      7

I want the output to be as shown above, but I get a sorted output.
bar comes above foo and so on.

Body:
While creating pivot_table, the index is automatically sorted  alphabetically. Not only foo and bar, you may also notice small and large is sorted. If you want foo on top, you may need to sort them again using sortlevel. If you are expecting output as in example here, then sorting on A and C both may be needed.

table.sortlevel(["A","B"], ascending= [False,True], sort_remaining=False, inplace=True)
table.sortlevel(["C"], axis=1, ascending=False,  sort_remaining=False, inplace=True)
print(table)

Output:

C        small  large
A   B
foo one  1.0    4.0
    two  6.0    NaN
bar one  5.0    4.0
    two  6.0    7.0

Update:

To remove index names A, B and C:

table.columns.name = None
table.index.names = (None, None)


问:
How to create a new component with aurelia cli?
Instead of creating new files manually, is there a command to create new components? Like au new but only for components:

hello.html

```<code><template>

  <!-- Hello template -->

</template>
</code>```

hello.js

```<code>export class Hello {

  constructor() {

  }

}
</code>```

答:
Typing au generate at the command line will give you the following list of options:

```<code>$ au generate
                      _ _          ____ _     ___
  __ _ _   _ _ __ ___| (_) __ _   / ___| |   |_ _|
 / _` | | | | '__/ _ \ | |/ _` | | |   | |    | |
| (_| | |_| | | |  __/ | | (_| | | |___| |___ | |
 \__,_|\__,_|_|  \___|_|_|\__,_|  \____|_____|___|

No Generator Specified. Available Generators:

attribute

    Creates a custom attribute class and places it in the project resources.

binding-behavior

    Creates a binding behavior class and places it in the project resources.

component

    Creates a custom component class and template (view model and view), placing them in the project source folder (or optionally in sub folders).

element

    Creates a custom element class and template, placing them in the project resources.

generator

    Creates a generator class and places it in the project generators folder.

task

    Creates a task and places it in the project tasks folder.

value-converter

    Creates a value converter class and places it in the project resources.
</code>```

Simply type au generate X where X is one of the options listed. For example au generate component.

Body:
Instead of creating new files manually, is there a command to create new components? Like au new but only for components:

hello.html

<template>

</template>

hello.js

export class Hello {

  constructor() {

  }

}

Body:
Typing au generate at the command line will give you the following list of options:

$ au generate
                      _ _          ____ _     ___
  __ _ _   _ _ __ ___| (_) __ _   / ___| |   |_ _|
 / _` | | | | '__/ _ \ | |/ _` | | |   | |    | |
| (_| | |_| | | |  __/ | | (_| | | |___| |___ | |
 \__,_|\__,_|_|  \___|_|_|\__,_|  \____|_____|___|

No Generator Specified. Available Generators:

attribute

    Creates a custom attribute class and places it in the project resources.

binding-behavior

    Creates a binding behavior class and places it in the project resources.

component

    Creates a custom component class and template (view model and view), placing them in the project source folder (or optionally in sub folders).

element

    Creates a custom element class and template, placing them in the project resources.

generator

    Creates a generator class and places it in the project generators folder.

task

    Creates a task and places it in the project tasks folder.

value-converter

    Creates a value converter class and places it in the project resources.

Simply type au generate X where X is one of the options listed. For example au generate component.


问:
How to make my game adapt to all android devices?
I'm  developing a game and I'm a beginner in Android game development. I'm using Android Studio and libgdx. I need screen to be adaptable on all devices. I am using screen width and height in my code which is changing the position and view of the game screen in different devices. How can I solve this? Can anyone help me getting this done with neat code?

答:
You should use dp units to size the elements in the screen

Then multipling the dp with the screen density you will get screen pixels.
To obtain the screen density do :

```<code>float density = getResources().getDisplayMetrics().density;
</code>```

Body:
You should use dp units to size the elements in the screen

Then multipling the dp with the screen density you will get screen pixels.
To obtain the screen density do :

float density = getResources().getDisplayMetrics().density;


问:
Way to get floating-point special values in CUDA?
Is there any device functions in CUDA to obtain IEEE 754 special values like inf, NaN? I mean the stable way, not by some maths ops that could be optimized-out by compilers.

I only manage to find a device function called nan() that must take some unknown string argument.

答:
CUDA now has the nanf instruction in the maths library.

device float nanf( const char *tagp )

```<code>Returns "NaN"
</code>```

Body:
CUDA now has the nanf instruction in the maths library.

device float nanf( const char *tagp )

Returns "NaN"


问:
Are there cases where a singleton is the best option?
There is a lot of discussion on this site about why singletons should be avoided but are there any cases where a singleton makes sense and is the best option?

An example where I think that a singleton is the best option is when implementing an Identity Map where you need to keep track of all models that have already been loaded from the database in your mapping layer. In this case it is important that the map is effectively global so that all client code uses the same instance of the map and they are all accessing the same list of loaded models. The simplest solution seems to be to implement the class as a singleton (or as static methods). Is this the best approach or is there another way?

Are there any other cases where it is OK to use a singleton or are they always bad?

答:
There is a use for singletons (and similar) in languages that don't allow static interface members - such as in .NET. By providing a singleton, you have an instance that can provide the interface as an instance. So in .NET, examples might be:

Comparer<T>.Default - provides an IComparer<T> implementation for sorting T

EqualityComparer<T>.Default - provides an IEqualityComparer<T> implementation for hashing/equality-testing T

This is as a means-to-an-end; it isn't what we are trying to do, just a reasonable "how".

In terms of the "identity map" example, personally I would rather keep that on an instance, and make the instance available to all my code. Apart from anything else, it aids testability if you can discard the map between tests, or have the flexibility (later) to have multiple identity maps at the same time.

OwnerDisplayName: Marc Gravell


问:
Accord and Mulit-label Support Vector Machines
I'm working through the example in the docs for a multi-class support vector machine - http://accord-framework.net/docs/html/T_Accord_MachineLearning_VectorMachines_MultilabelSupportVectorMachine.htm

Though, I'm not getting a 0 error rate, and when I try to compute values, they do not give the output values they should. Is there something wrong with the example?

```<code>    static void Main(string[] args)
    {
        // Sample input data
        double[][] inputs =
        {
            new double[] { 0 },
            new double[] { 1 },
            new double[] { 2 },
            new double[] { 3 },
        };

        // Outputs for each of the inputs
        int[][] outputs =
            {
                new[] {1,-1,-1,-1},
                new[] {-1,1,-1,-1},
                new[] {-1,-1,1,-1},
                new[] {-1,-1,-1,1},
            };

        // Create a new Linear kernel
        IKernel kernel = new Linear();

        // Create a new Multi-class Support Vector Machine with one input,
        //  using the linear kernel and for four disjoint classes.
        var machine = new MultilabelSupportVectorMachine(1, kernel, 4);

        // Create the Multi-label learning algorithm for the machine
        var teacher = new MultilabelSupportVectorLearning(machine, inputs, outputs);

        // Configure the learning algorithm to use SMO to train the
        //  underlying SVMs in each of the binary class subproblems.
        teacher.Algorithm = (svm, classInputs, classOutputs, i, j) =>
            new SequentialMinimalOptimization(svm, classInputs, classOutputs);

        // Run the learning algorithm
        double error = teacher.Run();

        error = teacher.Run(); // 0.1875 error rate
        var answer = machine.Compute(new double[] {2});  // gives -1,-1,-1,-1, instead of -1,-1,1,-1
</code>```

Should the error rate be zero, and why does it seem that only an input of 0 gives the right output?

答:
To answer the question, it is very likely that there was something wrong with that particular example. Most examples have been updated to reflect the new .Learn() API that was put in place last year.

Now you may see that the documentation page for Multi-label Support Vector Machine has also changed addresses due the new API and is now at

http://accord-framework.net/docs/html/T_Accord_MachineLearning_VectorMachines_MultilabelSupportVectorMachine_1.htm

And now it includes this example, among others:

```<code>// Let's say we have the following data to be classified
// into three possible classes. Those are the samples:
//
double[][] inputs =
{
    //               input         output
    new double[] { 0, 1, 1, 0 }, //  0
    new double[] { 0, 1, 0, 0 }, //  0
    new double[] { 0, 0, 1, 0 }, //  0
    new double[] { 0, 1, 1, 0 }, //  0
    new double[] { 0, 1, 0, 0 }, //  0
    new double[] { 1, 0, 0, 0 }, //  1
    new double[] { 1, 0, 0, 0 }, //  1
    new double[] { 1, 0, 0, 1 }, //  1
    new double[] { 0, 0, 0, 1 }, //  1
    new double[] { 0, 0, 0, 1 }, //  1
    new double[] { 1, 1, 1, 1 }, //  2
    new double[] { 1, 0, 1, 1 }, //  2
    new double[] { 1, 1, 0, 1 }, //  2
    new double[] { 0, 1, 1, 1 }, //  2
    new double[] { 1, 1, 1, 1 }, //  2
};

int[] outputs = // those are the class labels
{
    0, 0, 0, 0, 0,
    1, 1, 1, 1, 1,
    2, 2, 2, 2, 2,
};

// Create the multi-class learning algorithm for the machine
var teacher = new MulticlassSupportVectorLearning<Gaussian>()
{
    // Configure the learning algorithm to use SMO to train the
    //  underlying SVMs in each of the binary class subproblems.
    Learner = (param) => new SequentialMinimalOptimization<Gaussian>()
    {
        // Estimate a suitable guess for the Gaussian kernel's parameters.
        // This estimate can serve as a starting point for a grid search.
        UseKernelEstimation = true
    }
};

// Configure parallel execution options
teacher.ParallelOptions.MaxDegreeOfParallelism = 1;

// Learn a machine
var machine = teacher.Learn(inputs, outputs);

// Obtain class predictions for each sample
int[] predicted = machine.Decide(inputs);

// Get class scores for each sample
double[] scores = machine.Score(inputs);

// Compute classification error
double error = new ZeroOneLoss(outputs).Loss(predicted);
</code>```

Body:
I'm working through the example in the docs for a multi-class support vector machine - http://accord-framework.net/docs/html/T_Accord_MachineLearning_VectorMachines_MultilabelSupportVectorMachine.htm

Though, I'm not getting a 0 error rate, and when I try to compute values, they do not give the output values they should. Is there something wrong with the example?

    static void Main(string[] args)
    {
        // Sample input data
        double[][] inputs =
        {
            new double[] { 0 },
            new double[] { 1 },
            new double[] { 2 },
            new double[] { 3 },
        };

        // Outputs for each of the inputs
        int[][] outputs =
            {
                new[] {1,-1,-1,-1},
                new[] {-1,1,-1,-1},
                new[] {-1,-1,1,-1},
                new[] {-1,-1,-1,1},
            };

        // Create a new Linear kernel
        IKernel kernel = new Linear();

        // Create a new Multi-class Support Vector Machine with one input,
        //  using the linear kernel and for four disjoint classes.
        var machine = new MultilabelSupportVectorMachine(1, kernel, 4);

        // Create the Multi-label learning algorithm for the machine
        var teacher = new MultilabelSupportVectorLearning(machine, inputs, outputs);

        // Configure the learning algorithm to use SMO to train the
        //  underlying SVMs in each of the binary class subproblems.
        teacher.Algorithm = (svm, classInputs, classOutputs, i, j) =>
            new SequentialMinimalOptimization(svm, classInputs, classOutputs);

        // Run the learning algorithm
        double error = teacher.Run();

        error = teacher.Run(); // 0.1875 error rate
        var answer = machine.Compute(new double[] {2});  // gives -1,-1,-1,-1, instead of -1,-1,1,-1

Should the error rate be zero, and why does it seem that only an input of 0 gives the right output?

Body:
To answer the question, it is very likely that there was something wrong with that particular example. Most examples have been updated to reflect the new .Learn() API that was put in place last year.

Now you may see that the documentation page for Multi-label Support Vector Machine has also changed addresses due the new API and is now at

http://accord-framework.net/docs/html/T_Accord_MachineLearning_VectorMachines_MultilabelSupportVectorMachine_1.htm

And now it includes this example, among others:

// Let's say we have the following data to be classified
// into three possible classes. Those are the samples:
//
double[][] inputs =
{
    //               input         output
    new double[] { 0, 1, 1, 0 }, //  0
    new double[] { 0, 1, 0, 0 }, //  0
    new double[] { 0, 0, 1, 0 }, //  0
    new double[] { 0, 1, 1, 0 }, //  0
    new double[] { 0, 1, 0, 0 }, //  0
    new double[] { 1, 0, 0, 0 }, //  1
    new double[] { 1, 0, 0, 0 }, //  1
    new double[] { 1, 0, 0, 1 }, //  1
    new double[] { 0, 0, 0, 1 }, //  1
    new double[] { 0, 0, 0, 1 }, //  1
    new double[] { 1, 1, 1, 1 }, //  2
    new double[] { 1, 0, 1, 1 }, //  2
    new double[] { 1, 1, 0, 1 }, //  2
    new double[] { 0, 1, 1, 1 }, //  2
    new double[] { 1, 1, 1, 1 }, //  2
};

int[] outputs = // those are the class labels
{
    0, 0, 0, 0, 0,
    1, 1, 1, 1, 1,
    2, 2, 2, 2, 2,
};

// Create the multi-class learning algorithm for the machine
var teacher = new MulticlassSupportVectorLearning<Gaussian>()
{
    // Configure the learning algorithm to use SMO to train the
    //  underlying SVMs in each of the binary class subproblems.
    Learner = (param) => new SequentialMinimalOptimization<Gaussian>()
    {
        // Estimate a suitable guess for the Gaussian kernel's parameters.
        // This estimate can serve as a starting point for a grid search.
        UseKernelEstimation = true
    }
};

// Configure parallel execution options
teacher.ParallelOptions.MaxDegreeOfParallelism = 1;

// Learn a machine
var machine = teacher.Learn(inputs, outputs);

// Obtain class predictions for each sample
int[] predicted = machine.Decide(inputs);

// Get class scores for each sample
double[] scores = machine.Score(inputs);

// Compute classification error
double error = new ZeroOneLoss(outputs).Loss(predicted);


问:
laravel 5 vue.js csrf token
I've been at it for a while to get this csrf token to work with the vue.js example.

but it keeps saying i don't have a token. I've tried all kinds of variations.

bottom (not head, before end of body)

```<code>    <script>
    window.myToken =  <?php echo json_encode([
        '_token' => csrf_token(),
    ]); ?>
    </script>

    <script src="/js/manifest.js"></script>
    <script src="/js/vendor.js"></script>
    <script src="/js/app.js"></script>
</code>```

html

```<code><div id="app">
@section('content')
<example></example>
@endsection
</div>
</code>```

console output

```<code>CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token

vendor.js:7635 You are running Vue in development mode.
Make sure to turn on production mode when deploying for production.
See more tips at https://vuejs.org/guide/deployment.html
</code>```

Example doesn't seem to do much either, but I guess i need the token.

答:
Insert this script into your page head tag.

```<code><script>
   window.Laravel = {
      'csrfToken' => '{{csrf_token()}}',
   };
</script>
</code>```

In your bootstrap.js:

```<code>window.axios.defaults.headers.common = {
    'X-CSRF-TOKEN': window.Laravel.csrfToken,
    'X-Requested-With': 'XMLHttpRequest'
}
</code>```

Title: laravel 5 vue.js csrf token

Body:
I've been at it for a while to get this csrf token to work with the vue.js example.

but it keeps saying i don't have a token. I've tried all kinds of variations.

bottom (not head, before end of body)

html

@section('content')
<example></example>
@endsection

console output

CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token

vendor.js:7635 You are running Vue in development mode.
Make sure to turn on production mode when deploying for production.
See more tips at https://vuejs.org/guide/deployment.html

Example doesn't seem to do much either, but I guess i need the token.

Body:
Insert this script into your page head tag.

<script>
   window.Laravel = {
      'csrfToken' => '{{csrf_token()}}',
   };
</script>

In your bootstrap.js:

window.axios.defaults.headers.common = {
    'X-CSRF-TOKEN': window.Laravel.csrfToken,
    'X-Requested-With': 'XMLHttpRequest'
}


问:
What will happen if i call one method from AsyncTask?
Suppose there is a method which is used to fetch the data in string by passing url say:

```<code>public class JsonParser extends AsyncTask<Void,String,JsonObject>{
doInBackground(String url){
..........
.....  }
 postExecute(Jobject jobj){
......
return data;
}
}
</code>```

Now if i call this method from three to four AsyncTasks and passing different urls, is there any possibilty that i may get data mismatch..

答:
yes it is possible to get mismatched data because Async task work independently of each other i.e doesn't wait for other task to end.
Async task details</p>

Body:
Suppose there is a method which is used to fetch the data in string by passing url say:

public class JsonParser extends AsyncTask<Void,String,JsonObject>{
doInBackground(String url){
..........
.....  }
 postExecute(Jobject jobj){
......
return data;
}
}

Now if i call this method from three to four AsyncTasks and passing different urls, is there any possibilty that i may get data mismatch..


问:
How do i get GHCi to load Opengl packages?
I can successfully build executables that link against OpenGL using GHC, however I cannot get the package to load into GHCi. This is definitely a regression for me because it works on 32-bit GHC (at least the version I upgraded from). I do not think the GHC version matters, just the fact that I am using the 64-bit GHC system.

On the recommendation of the maintainer I explicitly brought the correct 64-bit version of opengl32 into GHCi successfully. It seems to be an issue higher up the stream.

Here is the output that is relevant. The verbose output is unfortunately just as specific. The function wglGetProcAddress is used to find where the opengl api hooks are in the dll.

```<code>$ ghcii.sh  -package OpenGL
GHCi, version 7.6.1: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Loading package OpenGLRaw-1.2.0.0 ... linking ... ghc.exe: unable to load
package `OpenGLRaw-1.2.0.0'
ghc.exe: C:\...\cabal\OpenGLRaw-1.2.0.0\ghc-7.6.1\HSOpenGLRaw-1.2.0.0.o:
unknown symbol `__imp_wglGetProcAddress'
</code>```

答:
It's been some time since I've dabbled on that level of Haskell development. But it looks similar enough to a standard linking problem.

I can give you an answer on why it happens, but at the moment am at a loss how to resolve it short of fixing the problem upstream.

The function wglGetProcAddress is found in opengl32.dll. So your HSOpenGLRaw seems not to be properly linked against that, hence the failure to locate the symbol.

If this happened in a *nix environment a simple solution would be to LD_PRELOAD libGL.so. However on Windows loading a module into a process doesn't make its symbols automatically visible to the rest of the process, so that wouldn't work there.

This also explains why it works for standalone binaries. Those are linked outside of runtime. Thus extra libraries can be passed to the linker which will resolve the missing dependencies.

Body:
I can successfully build executables that link against OpenGL using GHC, however I cannot get the package to load into GHCi. This is definitely a regression for me because it works on 32-bit GHC (at least the version I upgraded from). I do not think the GHC version matters, just the fact that I am using the 64-bit GHC system.

On the recommendation of the maintainer I explicitly brought the correct 64-bit version of opengl32 into GHCi successfully. It seems to be an issue higher up the stream.

Here is the output that is relevant. The verbose output is unfortunately just as specific. The function wglGetProcAddress is used to find where the opengl api hooks are in the dll.

$ ghcii.sh  -package OpenGL
GHCi, version 7.6.1: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Loading package OpenGLRaw-1.2.0.0 ... linking ... ghc.exe: unable to load
package `OpenGLRaw-1.2.0.0'
ghc.exe: C:\...\cabal\OpenGLRaw-1.2.0.0\ghc-7.6.1\HSOpenGLRaw-1.2.0.0.o:
unknown symbol `__imp_wglGetProcAddress'


问:
Dynamically generated Javascript, CSS in ASP.NET MVC
ASP.NET allows to generate HTML dynamically using server tags (razor or ASPX). But Is there any good way to generate *.js or *.css content the same way, other than using inline(embedded) CSS/Javascript. Nowadays with technologies like Ajax more and more logic moves from server-side to client side in Javascript. It would be great to have that opportunity to generate JS dynamically using all flexibility that ASP.NET provides for HTML generation.

For example, my Javascript contains Knockout view model declaration with initial data loaded from server during Javascript rendering, and some additional js-functions, so in my Html instead of embedded scripts I want to have script references like that:

```<code><script src="~/Scripts/ContactViewModel.js?contactId=@Model.ContactId"></script>
</code>```

Another example, where developer might need it is using user-profile based CSS. User profile information contains style information (fonts, colors, not just theme) that must be respected during CSS generation, so In my view I will have something like:

```<code><link href="~/Styles/CurrentUserOverrides.css" rel="stylesheet" />
</code>```

CurrentUserOverrides.css will be generated dynamically based on profile data of authenticated user.

How to do that using ASP.NET MVC? I want to find solution that will allow me to do this as easy as I create dynamic HTML using ASP.NET, with properly working intellisence and everything else what VS offers for ASP.NET views.

答:
Dynamic CSS in a CSHTML File

I use CSS comments /* */ to comment out a new
```

<p><strong>Dynamic JS in a CSHTML File</strong></p>

<p>I use JavaScript comments <code><!--//</code> to comment out a new <code>
</code>```

MyDynamicCss.cshtml

```<code>@{
var fieldList = new List<string>();
fieldList.Add("field1");
fieldList.Add("field2");

}/*
</code>```

MyDynamicJavsScript.cshtml

```<code>@{
var fieldList = new List<string>();
fieldList.Add("field1");
fieldList.Add("field2");
fieldArray = string.Join(",", fieldList);

}

//<script type="text/javascript">

$(document).ready(function () {
    var fieldList = "@Html.Raw(fieldArray)";
    var fieldArray = fieldList.split(',');
    var arrayLength = fieldArray.length;
    var selector = '';
    for (var i = 0; i < arrayLength; i++) {
        var field = fieldArray[i];
        selector += (selector == '' ? '' : ',')
                    + 'input[name="' + field + '"]'
                  + ',select[name="' + field + '"]';
    }
    $(selector).attr('disabled', 'disabled');
    $(selector).addClass('disabled');
});
@{return;}</script>
</code>```

No Controller Required (using Views/Shared)

I put both of my dynamic scripts into Views/Shared/ and I can easily embed them into any existing page (or in _Layout.cshtml) using the following code:

```<code>
<script type="text/javascript">@Html.Partial("MyDynamicJavaScript")</script>
</code>```

Using a Controller (optional)

If you prefer you may create a controller e.g.

```<code><link rel="stylesheet" type="text/css" href="@Url.Action("MyDynamicCss", "MyDynamicCode")">
<script type="text/javascript" src="@Url.Action("MyDynamicJavaScript", "MyDynamicCode")"></script>
</code>```

Here's what the controller might look like

MyDynamicCodeController.cs (optional)

```<code>[HttpGet]
public ActionResult MyDynamicCss()
{
    Response.ContentType = "text/css";
    return View();
}

[HttpGet]
public ActionResult MyDynamicJavaScript()
{
    Response.ContentType = "application/javascript";
    return View();
}
</code>```

Notes

The controller version is not tested.  I just typed that off the top of my head.

After re-reading my answer, it occurs to me it might be just as easy to comment out the closing tags rather than use the cshtml @{return;}, but I haven't tried it.  I imagine it's a matter of preference.

Concerning my entire answer, if you find any syntax errors or improvements please let me know.

Body:
ASP.NET allows to generate HTML dynamically using server tags (razor or ASPX). But Is there any good way to generate *.js or *.css content the same way, other than using inline(embedded) CSS/Javascript. Nowadays with technologies like Ajax more and more logic moves from server-side to client side in Javascript. It would be great to have that opportunity to generate JS dynamically using all flexibility that ASP.NET provides for HTML generation.

For example, my Javascript contains Knockout view model declaration with initial data loaded from server during Javascript rendering, and some additional js-functions, so in my Html instead of embedded scripts I want to have script references like that:

Another example, where developer might need it is using user-profile based CSS. User profile information contains style information (fonts, colors, not just theme) that must be respected during CSS generation, so In my view I will have something like:

<link href="~/Styles/CurrentUserOverrides.css" rel="stylesheet" />

CurrentUserOverrides.css will be generated dynamically based on profile data of authenticated user.

How to do that using ASP.NET MVC? I want to find solution that will allow me to do this as easy as I create dynamic HTML using ASP.NET, with properly working intellisence and everything else what VS offers for ASP.NET views.

Body:
Dynamic CSS in a CSHTML File

I use CSS comments /* */ to comment out a new <style> tag and then I return; before the closing style tag:

/*<style type="text/css">/* */

    CSS GOES HERE

@{return;}</style>

Dynamic JS in a CSHTML File

I use JavaScript comments <!--// to comment out a new <script> tag and then I return; before the closing script tag:

//<script type="text/javascript">

    JAVASCRIPT GOES HERE

@{return;}</script>

MyDynamicCss.cshtml

@{
var fieldList = new List<string>();
fieldList.Add("field1");
fieldList.Add("field2");

}/*<style type="text/css">/* */

@foreach (var field in fieldList) {<text>

input[name="@field"]
, select[name="@field"]
{
    background-color: #bbb;
    color: #6f6f6f;
}

</text>}

@{return;}</style>

MyDynamicJavsScript.cshtml

@{
var fieldList = new List<string>();
fieldList.Add("field1");
fieldList.Add("field2");
fieldArray = string.Join(",", fieldList);

}

//<script type="text/javascript">

$(document).ready(function () {
    var fieldList = "@Html.Raw(fieldArray)";
    var fieldArray = fieldList.split(',');
    var arrayLength = fieldArray.length;
    var selector = '';
    for (var i = 0; i < arrayLength; i++) {
        var field = fieldArray[i];
        selector += (selector == '' ? '' : ',')
                    + 'input[name="' + field + '"]'
                  + ',select[name="' + field + '"]';
    }
    $(selector).attr('disabled', 'disabled');
    $(selector).addClass('disabled');
});
@{return;}</script>

No Controller Required (using Views/Shared)

I put both of my dynamic scripts into Views/Shared/ and I can easily embed them into any existing page (or in _Layout.cshtml) using the following code:

<style type="text/css">@Html.Partial("MyDynamicCss")</style>
<script type="text/javascript">@Html.Partial("MyDynamicJavaScript")</script>

Using a Controller (optional)

If you prefer you may create a controller e.g.

<link rel="stylesheet" type="text/css" href="@Url.Action("MyDynamicCss", "MyDynamicCode")">
<script type="text/javascript" src="@Url.Action("MyDynamicJavaScript", "MyDynamicCode")"></script>

Here's what the controller might look like

MyDynamicCodeController.cs (optional)

[HttpGet]
public ActionResult MyDynamicCss()
{
    Response.ContentType = "text/css";
    return View();
}

[HttpGet]
public ActionResult MyDynamicJavaScript()
{
    Response.ContentType = "application/javascript";
    return View();
}

Notes

The controller version is not tested.  I just typed that off the top of my head.

After re-reading my answer, it occurs to me it might be just as easy to comment out the closing tags rather than use the cshtml @{return;}, but I haven't tried it.  I imagine it's a matter of preference.

Concerning my entire answer, if you find any syntax errors or improvements please let me know.


问:
Plotting dates in 3D plots R
I am trying to plot date, x and y in a 3D plot in R. (Using RStudio 0.99.903), R (3.3.2), scatterplot3d(0.3-40), rgl(0.98.1)</p>

```<code>dates = c("2016-11-10","2016-11-20","2016-12-01","2016-12-15","2016-12-30")

x = rnorm(5,0,1)

y = rnorm(5,1,2)

A = data.frame(dates, x, y)

A$dates = as.Date(A$dates,"%yyyy-%mm-%dd")

library(scatterplot3d)

with(data=A, scatterplot3d(x=x,y=y,z=dates))

This plots the dates as integers

I also tried the rgl package, but get the same result.

library(rgl)

plot3d(x=A$x,y=A$y,z=A$dates)
</code>```

答:
Read about how to use as.Date. You need to format date appropriately and you get your desired plot:

```<code>     dates = c("2016-11-10","2016-11-20","2016-12-01","2016-12-15","2016-12-30")
     x = rnorm(5,0,1)
     y = rnorm(5,1,2)
     A = data.frame(dates, x, y)

     A$dates = as.Date(A$dates,"%Y-%m-%d")

     library(scatterplot3d)

     scatterplot3d(x=A$x, y=A$y, z=A$dates)
</code>```

Plot would look like:

To correct the z-axis you can refer to this page.

To avoid these mistakes you can use anytime package by Dirk Eddelbuettel.

```<code>library(anytime)
A$dates <- anytime(A$dates)
</code>```

Title: Plotting dates in 3D plots R

Body:
I am trying to plot date, x and y in a 3D plot in R. (Using RStudio 0.99.903), R (3.3.2), scatterplot3d(0.3-40), rgl(0.98.1)

dates = c("2016-11-10","2016-11-20","2016-12-01","2016-12-15","2016-12-30")

x = rnorm(5,0,1)

y = rnorm(5,1,2)

A = data.frame(dates, x, y)

A$dates = as.Date(A$dates,"%yyyy-%mm-%dd")

library(scatterplot3d)

with(data=A, scatterplot3d(x=x,y=y,z=dates))

This plots the dates as integers

I also tried the rgl package, but get the same result.

library(rgl)

plot3d(x=A$x,y=A$y,z=A$dates)

Body:
Read about how to use as.Date. You need to format date appropriately and you get your desired plot:

     dates = c("2016-11-10","2016-11-20","2016-12-01","2016-12-15","2016-12-30")
     x = rnorm(5,0,1)
     y = rnorm(5,1,2)
     A = data.frame(dates, x, y)

     A$dates = as.Date(A$dates,"%Y-%m-%d")

     library(scatterplot3d)

     scatterplot3d(x=A$x, y=A$y, z=A$dates)

Plot would look like:

To correct the z-axis you can refer to this page.

To avoid these mistakes you can use anytime package by Dirk Eddelbuettel.

library(anytime)
A$dates <- anytime(A$dates)

ContentLicense: CC BY-SA 4.0


问:
Django commits to database before transaction ends
I am using Django 1.10 with Postgres database and django-rest-framework. I debug my code and wherever I have some_entity.save(), I immediately see the changes in database. The thing is that I have ATOMIC_REQUESTS = True and this would mean that nothing gets committed to the database until view successfully finishes. I am worried about the database integrity now- if later an exception occurs, nothing gets rolled back

答:
What you describe is a perfectly expected behavior with database transactions.

With ATOMIC_REQUESTS = True each request is wrapped in a database transaction, meaning a transaction is started when the request is received and is committed after a response is produced without problem.

During the transaction, you can read your own writes: that's how SQL databases work (and the contrary would be very confusing).

In most configurations though, these writes are "isolated": if they are not committed yet, they will not be visible from a concurrent request (in a distinct transaction). For more details about Transaction Isolation, look at postgresql docs: https://www.postgresql.org/docs/current/static/transaction-iso.html


问:
Swift 3.0 Get User Location Coordinates from Different View Controller
I have two view controllers - one with the mapView that is able to obtain user location coordinations through locationManager, and a second VC that I wish to be able to pull these user coordinates.

First VC: MapView

```<code>func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    var coordinatesOfUser = locations.last?.coordinate
    print("The value of usercoordinates are \(coordinatesOfUser)")

    // here I want to be able to pull this variable, coordinatesOfUser

    if let location = locations.last {
        let span = MKCoordinateSpanMake(0.00775, 0.00775)
        let myLocation = CLLocationCoordinate2DMake(location.coordinate.latitude,location.coordinate.longitude)
        let region = MKCoordinateRegionMake(myLocation, span)
        map.setRegion(region, animated: true)
    }
    self.map.showsUserLocation = true
    locationManager.stopUpdatingLocation()

}
</code>```

Second VC:

I was thinking of calling the locationManager function in this VC. Is this the most efficient way to pull the coordinates to this VC? And if so, how would I go about doing it?

答:
I had the same problem and I finally fixed it with a Notification, as kuhncj said.

This is how the code looks like at the end:

```<code>    //Get user location
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {

            if status == .authorizedWhenInUse {
                locationManager.startUpdatingLocation()

                mapView.isMyLocationEnabled = true
                mapView.settings.myLocationButton = true
            } else {
                initialLocation()
            }
        }

        func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

            if let location = locations.first {

                mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)

                locationManager.stopUpdatingLocation()

                let userInfo: NSDictionary = ["location": location]

                //Post notification
                NotificationCenter.default.post(name: NSNotification.Name("UserLocationNotification"), object: self, userInfo: userInfo as [NSObject : AnyObject])

            }
        }
</code>```

And then in the other view controller:

```<code>    var userLocation: String?

    override func viewDidLoad() {
            super.viewDidLoad()

            //Observer that receives the notification
            NotificationCenter.default.addObserver(self, selector: #selector(locationUpdateNotification), name: Notification.Name("UserLocationNotification"), object: nil)

        }

        func locationUpdateNotification(notification: NSNotification) {
            if let userInfo = notification.userInfo?["location"] as? CLLocation {
                //Store user location
                self.userLocation = "\(userInfo.coordinate.latitude), \(userInfo.coordinate.longitude)"
            }
        }
</code>```

Then I was able to use the stored userLocation for another methods.

Body:
I have two view controllers - one with the mapView that is able to obtain user location coordinations through locationManager, and a second VC that I wish to be able to pull these user coordinates.

First VC: MapView

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    var coordinatesOfUser = locations.last?.coordinate
    print("The value of usercoordinates are \(coordinatesOfUser)")

    // here I want to be able to pull this variable, coordinatesOfUser

    if let location = locations.last {
        let span = MKCoordinateSpanMake(0.00775, 0.00775)
        let myLocation = CLLocationCoordinate2DMake(location.coordinate.latitude,location.coordinate.longitude)
        let region = MKCoordinateRegionMake(myLocation, span)
        map.setRegion(region, animated: true)
    }
    self.map.showsUserLocation = true
    locationManager.stopUpdatingLocation()

}

Second VC:

I was thinking of calling the locationManager function in this VC. Is this the most efficient way to pull the coordinates to this VC? And if so, how would I go about doing it?

Body:
I had the same problem and I finally fixed it with a Notification, as kuhncj said.

This is how the code looks like at the end:

    //Get user location
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {

            if status == .authorizedWhenInUse {
                locationManager.startUpdatingLocation()

                mapView.isMyLocationEnabled = true
                mapView.settings.myLocationButton = true
            } else {
                initialLocation()
            }
        }

        func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

            if let location = locations.first {

                mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)

                locationManager.stopUpdatingLocation()

                let userInfo: NSDictionary = ["location": location]

                //Post notification
                NotificationCenter.default.post(name: NSNotification.Name("UserLocationNotification"), object: self, userInfo: userInfo as [NSObject : AnyObject])

            }
        }

And then in the other view controller:

    var userLocation: String?

    override func viewDidLoad() {
            super.viewDidLoad()

            //Observer that receives the notification
            NotificationCenter.default.addObserver(self, selector: #selector(locationUpdateNotification), name: Notification.Name("UserLocationNotification"), object: nil)

        }

        func locationUpdateNotification(notification: NSNotification) {
            if let userInfo = notification.userInfo?["location"] as? CLLocation {
                //Store user location
                self.userLocation = "\(userInfo.coordinate.latitude), \(userInfo.coordinate.longitude)"
            }
        }

Then I was able to use the stored userLocation for another methods.


问:
Web Exception with Web Service
I have developed a client application to consume a web service,

there are no error's in my code however when I debug I get the following exception,

'WebException was unhandled - the underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.'

I think this is to do with the fact that it is a secure web service I am trying to consume,
so my question is would this error occur due to the security certificate not being installed correctly? And if so is there a way to manually instal the certificate into the application?

Thanks for your time.

答:
This is basically an issue of missing trust. The server's ssl certificate needs to trusted by the consuming client. There are two ways to fix this:

Buy an SSL certificate from a trusted certificate authority (CA)

Add the server's SSL certificate to the Trusted People certificate store of the user running the app (or the computer on which the app is to be run (LocalMacine/TrustedPeople))

You can use the X509CertificateStore class to add certificates to the appropriate store programmatically, so basically you can distribute the public key of the server's ssl certificate with your app and install it when needed.

Title: Web Exception with Web Service


问:
Map a collection using a predicate and two functions
While trying to write code in a functional style, I often encounter the scenario where I want to map one collection or stream to another using two functions: one function applied to elements that pass a given predicate and another function applied to elements that fail. Both functions produce a common output, which should be collected for further processing.

Here is a contrived example in Java.

Stream.of("foo", "bar", "baz", "qux")
      .map(it -> it.startsWith("ba") ? it.toUpperCase() : new StringBuilder(it).reverse())
      .forEach(System.out::println);
```

<p>And the same example in Groovy.</p>

<pre class="lang-groovy prettyprint-override"><code>["foo", "bar", "baz", "qux"]
      .collect{ it.startsWith("ba") ? it.toUpperCase() : it.reverse() }
      .each{ println(it) }
</code>```

My question is regarding the conditional (ternary) statement used to implement this mapping. Is there a functional idiom to implement such a mapping without resorting to branching logic?

答:
You can always abstract over an expression with another function. Since you tagged your question language-agnostic, I encode my example with Javascript, executable in your favorite browser - I hope this is okay:

// select :: (a -> Boolean, a -> b, a -> b) -> a -> b
const select = (p, f, g) => x => p(x) ? f(x) : g(x);

// mapSelect :: (a -> Boolean, a -> b, a -> b) -> [a] -> [b]
const mapSelect = (p, f, g) => xs => xs.map(select(p, f, g));

const reverse = s => s.split("").reverse().join("");
const toUpperCase = s => s.toUpperCase();
const startsWith = s => t => t.indexOf(s) === 0

const xs = ["foo", "bar", "baz", "qux"];

console.log(
  mapSelect(startsWith("ba"), toUpperCase, reverse) (xs)
);```

Obviously, mapSelect doesn't save you from the conditional operator. It is just another layer of abstraction. Since it is not as common as map, you increase especially the cognitive load of your coworkers without getting much.

Conclusion: I would stick with the explicit conditional operator instead of disguising the branching logic.

Body:
While trying to write code in a functional style, I often encounter the scenario where I want to map one collection or stream to another using two functions: one function applied to elements that pass a given predicate and another function applied to elements that fail. Both functions produce a common output, which should be collected for further processing.

Here is a contrived example in Java.

Stream.of("foo", "bar", "baz", "qux")
      .map(it -> it.startsWith("ba") ? it.toUpperCase() : new StringBuilder(it).reverse())
      .forEach(System.out::println);

And the same example in Groovy.

["foo", "bar", "baz", "qux"]
      .collect{ it.startsWith("ba") ? it.toUpperCase() : it.reverse() }
      .each{ println(it) }

My question is regarding the conditional (ternary) statement used to implement this mapping. Is there a functional idiom to implement such a mapping without resorting to branching logic?

Body:
You can always abstract over an expression with another function. Since you tagged your question language-agnostic, I encode my example with Javascript, executable in your favorite browser - I hope this is okay:

// select :: (a -> Boolean, a -> b, a -> b) -> a -> b
const select = (p, f, g) => x => p(x) ? f(x) : g(x);

// mapSelect :: (a -> Boolean, a -> b, a -> b) -> [a] -> [b]
const mapSelect = (p, f, g) => xs => xs.map(select(p, f, g));

const reverse = s => s.split("").reverse().join("");
const toUpperCase = s => s.toUpperCase();
const startsWith = s => t => t.indexOf(s) === 0

const xs = ["foo", "bar", "baz", "qux"];

console.log(
  mapSelect(startsWith("ba"), toUpperCase, reverse) (xs)
);

Obviously, mapSelect doesn't save you from the conditional operator. It is just another layer of abstraction. Since it is not as common as map, you increase especially the cognitive load of your coworkers without getting much.

Conclusion: I would stick with the explicit conditional operator instead of disguising the branching logic.


问:
StateT over Cont. Why is my state not being reset?
I'm playing with the Cont monad tricks described here and in this SO question.

This function lets you "jump back" to earlier in the computation, taking a parameter so you can do things differently:

```<code>import Control.Monad.Cont
import Control.Monad.State.Strict
import Control.Monad.Writer.Strict

getCC' :: MonadCont m => a -> m (a,a -> m b)
getCC' x0 = callCC (\c -> let f x = c (x, f) in return (x0, f))
</code>```

I have these toy examples of monad transformers on top of Cont:

```<code>foo :: WriterT String (Cont String) ()
foo = do
    (stop,loop) <- getCC' False
    if stop
        then do tell "bbb"
        else do tell "aaa"
                loop True

foo' :: StateT String (Cont String) ()
foo' = do
    (stop,loop) <- getCC' False
    if stop
        then do modify $ \s -> s ++ "bbb"
        else do modify $ \s -> s ++ "aaa"
                loop True
</code>```

In the first example (as explained in the linked SO question) the effects of Cont have "priority" over the effects of the WriterT. When we reset the computation, the log is lost:

```<code>*Main> print $ runCont (execWriterT foo) id
"bbb"
</code>```

The second example does exactly the same thing, only using StateT instead of WriterT. However, in this case the log is preserved!

```<code>*Main> print $ runCont (execStateT foo' "") id
"aaabbb"
</code>```

What is the explanation of this discrepancy?

答:
(I feel this is not a completely satisfactory answer, but at least it should clarify a little.)

I believe this is because of the lifting of callCC. In the state monad case, after chasing the rabbit down the hole, we meet this:

```<code>liftCallCC :: CallCC m (a, s) (b, s) -> CallCC (StateT s m) a b
</code>```

Uniform lifting of a callCC operation to the new monad. This version
  rolls back to the original state on entering the continuation.

```<code>liftCallCC' :: CallCC m (a, s) (b, s) -> CallCC (StateT s m) a b
</code>```

In-situ lifting of a callCC operation to the new monad. This version
  uses the current state on entering the continuation.

Which one is taken? The one preserving state:

```<code>instance MonadCont m => MonadCont (LazyState.StateT s m) where
    callCC = LazyState.liftCallCC' callCC

instance MonadCont m => MonadCont (StrictState.StateT s m) where
    callCC = StrictState.liftCallCC' callCC
</code>```

What happens for the writer monad?

```<code>instance (Monoid w, MonadCont m) => MonadCont (LazyWriter.WriterT w m) where
    callCC = LazyWriter.liftCallCC callCC

instance (Monoid w, MonadCont m) => MonadCont (StrictWriter.WriterT w m) where
    callCC = StrictWriter.liftCallCC callCC
</code>```

Ah-ha! No '!

```<code>liftCallCC :: Monoid w => CallCC m (a, w) (b, w) -> CallCC (WriterT w m) a b
</code>```

Lift a callCC operation to the new monad.

No state-preserving variant is found in the library. The above variant, instead, is found there defined as

```<code>liftCallCC callCC f = WriterT $
    callCC $ \ c ->
    runWriterT (f (\ a -> WriterT $ c (a, mempty)))
</code>```

Note the mempty. If we had a get operation, we could store there the "current state", so that it is not lost in the process, but if we had that we would no longer be in the writer monad, but in the state one.

Also note that stacking the monads in the opposite order achieves what we'd want.

```<code>bar :: ContT String (Writer String) ()
bar = do
    (stop,loop) <- getCC' False
    if stop
        then do lift $tell "bbb"
        else do lift $ tell "aaa"
                loop True

-- > runWriter (runContT bar (const $ pure ""))
-- ("","aaabbb")
</code>```

Body:
I'm playing with the Cont monad tricks described here and in this SO question.

This function lets you "jump back" to earlier in the computation, taking a parameter so you can do things differently:

import Control.Monad.Cont
import Control.Monad.State.Strict
import Control.Monad.Writer.Strict

getCC' :: MonadCont m => a -> m (a,a -> m b)
getCC' x0 = callCC (\c -> let f x = c (x, f) in return (x0, f))

I have these toy examples of monad transformers on top of Cont:

foo :: WriterT String (Cont String) ()
foo = do
    (stop,loop) <- getCC' False
    if stop
        then do tell "bbb"
        else do tell "aaa"
                loop True

foo' :: StateT String (Cont String) ()
foo' = do
    (stop,loop) <- getCC' False
    if stop
        then do modify $ \s -> s ++ "bbb"
        else do modify $ \s -> s ++ "aaa"
                loop True

In the first example (as explained in the linked SO question) the effects of Cont have "priority" over the effects of the WriterT. When we reset the computation, the log is lost:

*Main> print $ runCont (execWriterT foo) id
"bbb"

The second example does exactly the same thing, only using StateT instead of WriterT. However, in this case the log is preserved!

*Main> print $ runCont (execStateT foo' "") id
"aaabbb"

What is the explanation of this discrepancy?

Body:
(I feel this is not a completely satisfactory answer, but at least it should clarify a little.)

I believe this is because of the lifting of callCC. In the state monad case, after chasing the rabbit down the hole, we meet this:

liftCallCC :: CallCC m (a, s) (b, s) -> CallCC (StateT s m) a b

Uniform lifting of a callCC operation to the new monad. This version
  rolls back to the original state on entering the continuation.

liftCallCC' :: CallCC m (a, s) (b, s) -> CallCC (StateT s m) a b

In-situ lifting of a callCC operation to the new monad. This version
  uses the current state on entering the continuation.

Which one is taken? The one preserving state:

instance MonadCont m => MonadCont (LazyState.StateT s m) where
    callCC = LazyState.liftCallCC' callCC

instance MonadCont m => MonadCont (StrictState.StateT s m) where
    callCC = StrictState.liftCallCC' callCC

What happens for the writer monad?

instance (Monoid w, MonadCont m) => MonadCont (LazyWriter.WriterT w m) where
    callCC = LazyWriter.liftCallCC callCC

instance (Monoid w, MonadCont m) => MonadCont (StrictWriter.WriterT w m) where
    callCC = StrictWriter.liftCallCC callCC

Ah-ha! No '!

liftCallCC :: Monoid w => CallCC m (a, w) (b, w) -> CallCC (WriterT w m) a b

Lift a callCC operation to the new monad.

No state-preserving variant is found in the library. The above variant, instead, is found there defined as

liftCallCC callCC f = WriterT $
    callCC $ \ c ->
    runWriterT (f (\ a -> WriterT $ c (a, mempty)))

Note the mempty. If we had a get operation, we could store there the "current state", so that it is not lost in the process, but if we had that we would no longer be in the writer monad, but in the state one.

Also note that stacking the monads in the opposite order achieves what we'd want.

bar :: ContT String (Writer String) ()
bar = do
    (stop,loop) <- getCC' False
    if stop
        then do lift $tell "bbb"
        else do lift $ tell "aaa"
                loop True

-- > runWriter (runContT bar (const $ pure ""))
-- ("","aaabbb")