问:
How do I append one string to another in Python?
How do I efficiently append one string to another? Are there any faster alternatives to:

```<code>var1 = "foo"
var2 = "bar"
var3 = var1 + var2
</code>```

For handling multiple strings in a list, see How to concatenate (join) items in a list to a single string.

See How do I put a variable’s value inside a string (interpolate it into the string)? if some inputs are not strings, but the result should still be a string.

答:
If you only have one reference to a string and you concatenate another string to the end, CPython now special cases this and tries to extend the string in place.

The end result is that the operation is amortized O(n).

e.g.

```<code>s = ""
for i in range(n):
    s += str(i)
</code>```

used to be O(n^2), but now it is O(n).

More information

From the source (bytesobject.c):

void
PyBytes_ConcatAndDel(register PyObject **pv, register PyObject *w)
{
    PyBytes_Concat(pv, w);
    Py_XDECREF(w);
}

/* The following function breaks the notion that strings are immutable:
   it changes the size of a string.  We get away with this only if there
   is only one module referencing the object.  You can also think of it
   as creating a new string object and destroying the old one, only
   more efficiently.  In any case, don't use this if the string may
   already be known to some other part of the code...
   Note that if there's not enough memory to resize the string, the original
   string object at *pv is deallocated, *pv is set to NULL, an "out of
   memory" exception is set, and -1 is returned.  Else (on success) 0 is
   returned, and the value in *pv may or may not be the same as on input.
   As always, an extra byte is allocated for a trailing \0 byte (newsize
   does *not* include that), and a trailing \0 byte is stored.
*/

int
_PyBytes_Resize(PyObject **pv, Py_ssize_t newsize)
{
    register PyObject *v;
    register PyBytesObject *sv;
    v = *pv;
    if (!PyBytes_Check(v) || Py_REFCNT(v) != 1 || newsize < 0) {
        *pv = 0;
        Py_DECREF(v);
        PyErr_BadInternalCall();
        return -1;
    }
    /* XXX UNREF/NEWREF interface should be more symmetrical */
    _Py_DEC_REFTOTAL;
    _Py_ForgetReference(v);
    *pv = (PyObject *)
        PyObject_REALLOC((char *)v, PyBytesObject_SIZE + newsize);
    if (*pv == NULL) {
        PyObject_Del(v);
        PyErr_NoMemory();
        return -1;
    }
    _Py_NewReference(*pv);
    sv = (PyBytesObject *) *pv;
    Py_SIZE(sv) = newsize;
    sv->ob_sval[newsize] = '\0';
    sv->ob_shash = -1;          /* invalidate cached hash value */
    return 0;
}
```
<p>It's easy enough to verify empirically.</p>
```
$ python -m timeit -s"s=''" "for i in xrange(10):s+='a'"
1000000 loops, best of 3: 1.85 usec per loop
$ python -m timeit -s"s=''" "for i in xrange(100):s+='a'"
10000 loops, best of 3: 16.8 usec per loop
$ python -m timeit -s"s=''" "for i in xrange(1000):s+='a'"
10000 loops, best of 3: 158 usec per loop
$ python -m timeit -s"s=''" "for i in xrange(10000):s+='a'"
1000 loops, best of 3: 1.71 msec per loop
$ python -m timeit -s"s=''" "for i in xrange(100000):s+='a'"
10 loops, best of 3: 14.6 msec per loop
$ python -m timeit -s"s=''" "for i in xrange(1000000):s+='a'"
10 loops, best of 3: 173 msec per loop
```
<p><strong>It's important</strong> however to note that this optimisation isn't part of the Python spec. It's only in the cPython implementation as far as I know. The same empirical testing on pypy or jython for example might show the older O(n**2) performance.</p>
```
$ pypy -m timeit -s"s=''" "for i in xrange(10):s+='a'"
10000 loops, best of 3: 90.8 usec per loop
$ pypy -m timeit -s"s=''" "for i in xrange(100):s+='a'"
1000 loops, best of 3: 896 usec per loop
$ pypy -m timeit -s"s=''" "for i in xrange(1000):s+='a'"
100 loops, best of 3: 9.03 msec per loop
$ pypy -m timeit -s"s=''" "for i in xrange(10000):s+='a'"
10 loops, best of 3: 89.5 msec per loop
```
<p>So far so good, but then,</p>
```
$ pypy -m timeit -s"s=''" "for i in xrange(100000):s+='a'"
10 loops, best of 3: 12.8 sec per loop
```

ouch even worse than quadratic. So pypy is doing something that works well with short strings, but performs poorly for larger strings.

Body:
How do I efficiently append one string to another? Are there any faster alternatives to:

var1 = "foo"
var2 = "bar"
var3 = var1 + var2

For handling multiple strings in a list, see How to concatenate (join) items in a list to a single string.

See How do I put a variable’s value inside a string (interpolate it into the string)? if some inputs are not strings, but the result should still be a string.

Body:
If you only have one reference to a string and you concatenate another string to the end, CPython now special cases this and tries to extend the string in place.

The end result is that the operation is amortized O(n).

e.g.

s = ""
for i in range(n):
    s += str(i)

used to be O(n^2), but now it is O(n).

More information

From the source (bytesobject.c):

void
PyBytes_ConcatAndDel(register PyObject **pv, register PyObject *w)
{
    PyBytes_Concat(pv, w);
    Py_XDECREF(w);
}

/* The following function breaks the notion that strings are immutable:
   it changes the size of a string.  We get away with this only if there
   is only one module referencing the object.  You can also think of it
   as creating a new string object and destroying the old one, only
   more efficiently.  In any case, don't use this if the string may
   already be known to some other part of the code...
   Note that if there's not enough memory to resize the string, the original
   string object at *pv is deallocated, *pv is set to NULL, an "out of
   memory" exception is set, and -1 is returned.  Else (on success) 0 is
   returned, and the value in *pv may or may not be the same as on input.
   As always, an extra byte is allocated for a trailing \0 byte (newsize
   does *not* include that), and a trailing \0 byte is stored.
*/

int
_PyBytes_Resize(PyObject **pv, Py_ssize_t newsize)
{
    register PyObject *v;
    register PyBytesObject *sv;
    v = *pv;
    if (!PyBytes_Check(v) || Py_REFCNT(v) != 1 || newsize < 0) {
        *pv = 0;
        Py_DECREF(v);
        PyErr_BadInternalCall();
        return -1;
    }
    /* XXX UNREF/NEWREF interface should be more symmetrical */
    _Py_DEC_REFTOTAL;
    _Py_ForgetReference(v);
    *pv = (PyObject *)
        PyObject_REALLOC((char *)v, PyBytesObject_SIZE + newsize);
    if (*pv == NULL) {
        PyObject_Del(v);
        PyErr_NoMemory();
        return -1;
    }
    _Py_NewReference(*pv);
    sv = (PyBytesObject *) *pv;
    Py_SIZE(sv) = newsize;
    sv->ob_sval[newsize] = '\0';
    sv->ob_shash = -1;          /* invalidate cached hash value */
    return 0;
}

It's easy enough to verify empirically.

$ python -m timeit -s"s=''" "for i in xrange(10):s+='a'"
1000000 loops, best of 3: 1.85 usec per loop
$ python -m timeit -s"s=''" "for i in xrange(100):s+='a'"
10000 loops, best of 3: 16.8 usec per loop
$ python -m timeit -s"s=''" "for i in xrange(1000):s+='a'"
10000 loops, best of 3: 158 usec per loop
$ python -m timeit -s"s=''" "for i in xrange(10000):s+='a'"
1000 loops, best of 3: 1.71 msec per loop
$ python -m timeit -s"s=''" "for i in xrange(100000):s+='a'"
10 loops, best of 3: 14.6 msec per loop
$ python -m timeit -s"s=''" "for i in xrange(1000000):s+='a'"
10 loops, best of 3: 173 msec per loop

It's important however to note that this optimisation isn't part of the Python spec. It's only in the cPython implementation as far as I know. The same empirical testing on pypy or jython for example might show the older O(n**2) performance.

$ pypy -m timeit -s"s=''" "for i in xrange(10):s+='a'"
10000 loops, best of 3: 90.8 usec per loop
$ pypy -m timeit -s"s=''" "for i in xrange(100):s+='a'"
1000 loops, best of 3: 896 usec per loop
$ pypy -m timeit -s"s=''" "for i in xrange(1000):s+='a'"
100 loops, best of 3: 9.03 msec per loop
$ pypy -m timeit -s"s=''" "for i in xrange(10000):s+='a'"
10 loops, best of 3: 89.5 msec per loop

So far so good, but then,

$ pypy -m timeit -s"s=''" "for i in xrange(100000):s+='a'"
10 loops, best of 3: 12.8 sec per loop

ouch even worse than quadratic. So pypy is doing something that works well with short strings, but performs poorly for larger strings.


来源: stackexchange

问:
Cannot check the value of popup after closing it manually in Excel for Windows
I have built an Excel add-in with a button. Clicking on the button opens a popup. The following code works well in Excel Online: we could open a popup (in Chrome), close it manually, and reopen a popup.

```<code>var popup;
function openPopup(url) {
    console.log("openPopup here");
    console.log(popup);
    if ((popup === null) || (popup === undefined) || (popup === {}) || (popup.location === undefined) || (popup.location.href === undefined)) {
        popup = window.open(url, "popup", "status=1, location=1, width=1000, height=1200, scrollbars=yes, resizable=yes");
    } else {
        popup.location.href = url;
    }
}
</code>```

However, I realise that it does not work with Excel 2016 for Windows: it can open a popup for the first time (in IE 11), but after closing it manually, we cannot re-open a popup anymore. F12 tool gives the following error at the line if:

```<code>openPopup here
[Object] { }
Error
   at openPopup ... ...
</code>```

Does anyone know where is the problem?

答: I don't see you are using the OfficeJS dialog API. Windows.open doesn't work on the rich clients. Please refer here for details.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have built an Excel add-in with a button. Clicking on the button opens a popup. The following code works well in Excel Online: we could open a popup (in Chrome), close it manually, and reopen a popup.

var popup;
function openPopup(url) {
    console.log("openPopup here");
    console.log(popup);
    if ((popup === null) || (popup === undefined) || (popup === {}) || (popup.location === undefined) || (popup.location.href === undefined)) {
        popup = window.open(url, "popup", "status=1, location=1, width=1000, height=1200, scrollbars=yes, resizable=yes");
    } else {
        popup.location.href = url;
    }
}

However, I realise that it does not work with Excel 2016 for Windows: it can open a popup for the first time (in IE 11), but after closing it manually, we cannot re-open a popup anymore. F12 tool gives the following error at the line if:

openPopup here
[Object] { }
Error
   at openPopup ... ...

Does anyone know where is the problem?


问:
List of most occurrences of element
I have a list let's say {1,1,2,2,3,3,3,4,4,4}. I want to find a List of the elements that occur the most often (it has to be a list as there can be a situation like here that 3 and 4 occur most and I need to get that information. How can I achieve this using LINQ?</p>

答:
By Grouping:</p>

```<code>var grp = list.GroupBy(i => i).ToList();
int max = grp.Max(c => c.Count());
var most = grp.Where(d => d.Count() == max)
              .Select(c => c.Key).ToList();
</code>```

Title: List of most occurrences of element

Body:
By Grouping:

var grp = list.GroupBy(i => i).ToList();
int max = grp.Max(c => c.Count());
var most = grp.Where(d => d.Count() == max)
              .Select(c => c.Key).ToList();


问:
How to compare timestamps in Ruby
What is the  simplest way to achieve this in Ruby?

I have two strings:

```<code>a = "08:02:04.982"
b = "10:07:12.004"
</code>```

I need to convert each string to a date object then compare to ensure that b is greater (later) than a. Such as:

```<code>if b > a
  print "this is normal"
else
  print "this is not normal"
end
</code>```

I tried using:

```<code>Time.parse("08:02:04.982")
</code>```

but that insisted on returning a date.

So I tried:

```<code>Time.parse("08:02:04.982", "%H:%M:%S.%3N")
</code>```

but that complains about undefined method "year".

答:
Meditate on this:

```<code>require 'time'

TIME_FORMAT = '%H:%M:%S.%n'

a = "08:02:04.982"
b = "10:07:12.004"

a_time = Time.strptime(a, TIME_FORMAT) # => 2017-06-04 08:02:04 -0700
b_time = Time.strptime(b, TIME_FORMAT) # => 2017-06-04 10:07:12 -0700

a_time < b_time # => true
a_time > b_time# => false
a_time <=> b_time # => -1
</code>```

Without a date component comparing Time values is risky. It's hard to know whether the times are occurring in the same day. Time will supply the current "today" if it doesn't see that information, but it can be a bug if you aren't sure if the date would be the same.

As you found, you can compare two equally formatted strings without converting them to Time or DateTime objects:

```<code>a < b   # => true
a > b   # => false
a <=> b # => -1
</code>```

You have to be careful though, because if you received a time string that didn't have a leading zero in any column then your comparison would be wrong, whereas, with parsing to the object it'd test correctly:

```<code>"8:2:4.982" == "08:02:04.982"  # => false
Time.strptime("8:2:4.982",    TIME_FORMAT) # => 2017-06-04 08:02:04 -0700
Time.strptime("08:02:04.982", TIME_FORMAT) # => 2017-06-04 08:02:04 -0700
</code>```

(And, yes, it's very possible you could get dates and times without leading zeros. In the wilds of the internet all sorts of crazy things happen.)

I tried using:

```<code>Time.parse("08:02:04.982")
</code>```

but that insisted on returning a date.

Um... no:

```<code>Time.parse("08:02:04.982").class # => Time
Time.parse("08:02:04.982") # => 2017-06-04 08:02:04 -0700
</code>```

Don't rely on parse unless you know the LOCALE of the incoming date/datetime strings. You can research why. Instead, if the strings are in a consistent form define your own format string. It'll be faster and more reliable.

Title: How to compare timestamps in Ruby

Body:
What is the  simplest way to achieve this in Ruby?

I have two strings:

a = "08:02:04.982"
b = "10:07:12.004"

I need to convert each string to a date object then compare to ensure that b is greater (later) than a. Such as:

if b > a
  print "this is normal"
else
  print "this is not normal"
end

I tried using:

Time.parse("08:02:04.982")

but that insisted on returning a date.

So I tried:

Time.parse("08:02:04.982", "%H:%M:%S.%3N")

but that complains about undefined method "year".

Body:
Meditate on this:

require 'time'

TIME_FORMAT = '%H:%M:%S.%n'

a = "08:02:04.982"
b = "10:07:12.004"

a_time = Time.strptime(a, TIME_FORMAT) # => 2017-06-04 08:02:04 -0700
b_time = Time.strptime(b, TIME_FORMAT) # => 2017-06-04 10:07:12 -0700

a_time < b_time # => true
a_time > b_time# => false
a_time <=> b_time # => -1

Without a date component comparing Time values is risky. It's hard to know whether the times are occurring in the same day. Time will supply the current "today" if it doesn't see that information, but it can be a bug if you aren't sure if the date would be the same.

As you found, you can compare two equally formatted strings without converting them to Time or DateTime objects:

a < b   # => true
a > b   # => false
a <=> b # => -1

You have to be careful though, because if you received a time string that didn't have a leading zero in any column then your comparison would be wrong, whereas, with parsing to the object it'd test correctly:

"8:2:4.982" == "08:02:04.982"  # => false
Time.strptime("8:2:4.982",    TIME_FORMAT) # => 2017-06-04 08:02:04 -0700
Time.strptime("08:02:04.982", TIME_FORMAT) # => 2017-06-04 08:02:04 -0700

(And, yes, it's very possible you could get dates and times without leading zeros. In the wilds of the internet all sorts of crazy things happen.)

I tried using:

Time.parse("08:02:04.982")

but that insisted on returning a date.

Um... no:

Time.parse("08:02:04.982").class # => Time
Time.parse("08:02:04.982") # => 2017-06-04 08:02:04 -0700

Don't rely on parse unless you know the LOCALE of the incoming date/datetime strings. You can research why. Instead, if the strings are in a consistent form define your own format string. It'll be faster and more reliable.


问:
Indexes update in DynamoDB
I've been working with LSI and GSI in DynamoDB, but I guess I'm missing something.

I created an index to always query by the latest results without using the partition key only other attributes and without reading the entire items, only those that really matter, but with the GSI at some point my query returns data that are not up-to-date; this I understand due to the fact of eventual consistence described in the docs (You may correct me if I'm wrong).

And what about LSI? Even using the ConsistentRead, at some point my data is not being queried correctly, and the results are not up-to-date. From the docs I thought that LSI where updated syncronized with its table and with the ConsistentRead property set I'd always get the latest results, but this is not happening.

I'm using a REST endpoint (API Gateway) to perform inserts into my dynamo table (I perform some treatments before the insertion) so, I've been wondering if this has something to do with it: maybe the code (currently Java) or DynamoDB is slow to update but since in my endpoint everything seems to work fine I perform another request too fast or if I have to wait a little longer to interact with the table because the index is being updated, although I have already tested waiting longer I'm receiving the same wrong results. I'm a bit lost here.

This is the code I'm using to query the index:

```<code> QuerySpec spec = new QuerySpec()
                .withKeyConditionExpression("#c = :v_attrib1 and #e = :v_attrib2")
                .withNameMap(new NameMap()
                        .with("#c", "attrib1")
                        .with("#e", "attrib2"))
                .withValueMap(new ValueMap()
                        .withString(":v_attrib1", attrib1Value)
                        .withString(":v_attrib2", attrib2Value))
                .withMaxResultSize(1) // to only bring the latest one
                .withConsistentRead(true) // is this wrong?
                .withScanIndexForward(false); // what about this one?
</code>```

I don't know if the maven library version would interfere, but in any case the version I'm using is the 1.11.76 (I know there are a lot of newer versions, but if this is the problem we'll update it then).

Thank you all in advance.

答:
After searching for quite some time and some other tests I, finally, figured out that the problem was not in DynamoDB indexes, they are working as expected, but in the Lambda functions.

The fact that I was sending a lot of requests, one after another, was not giving the indexes time to remain updated: Lambda functions execute asynchronously (I should have known), and so the requests received by the database were not ordered and my data was not properly updated. So, we changed our implementation to use Atomic Counters: we can keep our data updated no matter the number or the order of the requests.

See: http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.AtomicCounters

Title: Indexes update in DynamoDB

Body:
I've been working with LSI and GSI in DynamoDB, but I guess I'm missing something.

I created an index to always query by the latest results without using the partition key only other attributes and without reading the entire items, only those that really matter, but with the GSI at some point my query returns data that are not up-to-date; this I understand due to the fact of eventual consistence described in the docs (You may correct me if I'm wrong).

And what about LSI? Even using the ConsistentRead, at some point my data is not being queried correctly, and the results are not up-to-date. From the docs I thought that LSI where updated syncronized with its table and with the ConsistentRead property set I'd always get the latest results, but this is not happening.

I'm using a REST endpoint (API Gateway) to perform inserts into my dynamo table (I perform some treatments before the insertion) so, I've been wondering if this has something to do with it: maybe the code (currently Java) or DynamoDB is slow to update but since in my endpoint everything seems to work fine I perform another request too fast or if I have to wait a little longer to interact with the table because the index is being updated, although I have already tested waiting longer I'm receiving the same wrong results. I'm a bit lost here.

This is the code I'm using to query the index:

 QuerySpec spec = new QuerySpec()
                .withKeyConditionExpression("#c = :v_attrib1 and #e = :v_attrib2")
                .withNameMap(new NameMap()
                        .with("#c", "attrib1")
                        .with("#e", "attrib2"))
                .withValueMap(new ValueMap()
                        .withString(":v_attrib1", attrib1Value)
                        .withString(":v_attrib2", attrib2Value))
                .withMaxResultSize(1) // to only bring the latest one
                .withConsistentRead(true) // is this wrong?
                .withScanIndexForward(false); // what about this one?

I don't know if the maven library version would interfere, but in any case the version I'm using is the 1.11.76 (I know there are a lot of newer versions, but if this is the problem we'll update it then).

Thank you all in advance.


问:
PHP function on Blade directives
I'm using @lang from Blade directives to handle translations.

I'd like to use PHP function to act on this directive "return statement" in views, for example :

```<code>strtoupper(@lang('messages.test'))
</code>```

Is that possible with Blade ?

答:
Then don't use the blade helper.</p>

```<code>{{ strtoupper(trans('messages.test')) }}
</code>```

Title: PHP function on Blade directives

Body:
I'm using @lang from Blade directives to handle translations.

I'd like to use PHP function to act on this directive "return statement" in views, for example :

strtoupper(@lang('messages.test'))

Is that possible with Blade ?

Body:
Then don't use the blade helper.

{{ strtoupper(trans('messages.test')) }}


问:
Store words in char array C language
I have this code:

```<code>char *pch;
pch = strtok(texto," ");

while (pch != NULL)
{
  pch = strtok (NULL, " ");
}
</code>```

My "texto" variable have something like "This is my text example".

And i need to store each value comming from pch in while, in an array of characteres, but i really dont know how to do it.

I need something like that, each value in array will have a word, so:

"This is my text example".

```<code>Array[0][20] = This;

Array[1][20] = is;

Array[2][20] = my;

Array[3][20] = text;

Array[4][20] = example;
</code>```

The pch in while having all these words already split, but I don't know how to add into a char array, or how I will declare him too.

答:
Consider the following example:

#include <stdio.h>
#include <string.h>

#define MAXSTRLEN 20
#define MAXWORD 6

int main(void)
{
    char arr[MAXWORD][MAXSTRLEN+1] = {0};
    char str[] ="This is my text example";
    char *pch;
    int i = 0;
    pch = strtok (str," ");
    while (pch != NULL && i < MAXWORD)
    {
        strncpy(arr[i++], pch, MAXSTRLEN);
        pch = strtok (NULL, " ");
    }
    return 0;
}
```

Title: Store words in char array C language

Body:
I have this code:

char *pch;
pch = strtok(texto," ");

while (pch != NULL)
{
  pch = strtok (NULL, " ");
}

My "texto" variable have something like "This is my text example".

And i need to store each value comming from pch in while, in an array of characteres, but i really dont know how to do it.

I need something like that, each value in array will have a word, so:

"This is my text example".

Array[0][20] = This;

Array[1][20] = is;

Array[2][20] = my;

Array[3][20] = text;

Array[4][20] = example;

The pch in while having all these words already split, but I don't know how to add into a char array, or how I will declare him too.


问:
Update only not null fields
How to tell hibernate to not update fields with null values ?

I have filled entity (without password field which is not-null field). I want to update all filled fields in entity (skip the fields with null values) but I recive error like that:

```<code>by: org.postgresql.util.PSQLException: ERROR: null value in column "password" violates not-null constraint
</code>```

How to tell hibernate to update ONLY changed fields (an skip all null values).

Edit (code)

workerService:

```<code>public Worker updateWorker(Worker worker) { // only a few fields are filled.
     workerDao.update(worker);
     return worker;
}
</code>```

and DAO:

```<code>@Repository
@Transactional
abstract public class AbstractDao<T> {

@Autowired
private SessionFactory sessionFactory;

//....

public void update(T entity) {
    sessionFactory.getCurrentSession().update(entity);
}
//...
</code>```

WorkerEntity:

```<code>@Entity
@Table(name = "worker", schema = "public")
@DynamicUpdate
public class Worker implements java.io.Serializable {
</code>```

答:
The dynamic-update attribute tells Hibernate whether to include unmodified properties in the SQL UPDATE statement.

dynamic-update=true then only updated column will appear in update query

```<code>@Entity
@Table(name = "test", catalog = "test_1")
@org.hibernate.annotations.Entity(
        dynamicUpdate = true
)
</code>```

Title: Update only not null fields

Body:
How to tell hibernate to not update fields with null values ?

I have filled entity (without password field which is not-null field). I want to update all filled fields in entity (skip the fields with null values) but I recive error like that:

by: org.postgresql.util.PSQLException: ERROR: null value in column "password" violates not-null constraint

How to tell hibernate to update ONLY changed fields (an skip all null values).

Edit (code)

workerService:

public Worker updateWorker(Worker worker) { // only a few fields are filled.
     workerDao.update(worker);
     return worker;
}

and DAO:

@Repository
@Transactional
abstract public class AbstractDao<T> {

@Autowired
private SessionFactory sessionFactory;

//....

public void update(T entity) {
    sessionFactory.getCurrentSession().update(entity);
}
//...

WorkerEntity:

@Entity
@Table(name = "worker", schema = "public")
@DynamicUpdate
public class Worker implements java.io.Serializable {

Body:
The dynamic-update attribute tells Hibernate whether to include unmodified properties in the SQL UPDATE statement.

dynamic-update=true then only updated column will appear in update query

@Entity
@Table(name = "test", catalog = "test_1")
@org.hibernate.annotations.Entity(
        dynamicUpdate = true
)


问:
How to rename the index of a Dask Dataframe
How would I go about renaming the index on a dask dataframe? I tried it like so

```<code>df.index.name = 'foo'
</code>```

but rechecking df.index.name shows it still being whatever it was previously.

答:
This does not seem like an efficient way to do it, so I wouldn't be surprised if there is something more direct.

d.index.name starts off as 'foo';

```<code>def f(df, name):
    df.index.name = name
    return df

d.map_partitions(f, 'pow')
</code>```

The output now has index name of 'pow'. If this is done with the threaded scheduler, I think you also change the index name of d in-place (in which case you don't really need the output of map_partitions).

Body:
How would I go about renaming the index on a dask dataframe? I tried it like so

df.index.name = 'foo'

but rechecking df.index.name shows it still being whatever it was previously.

Body:
This does not seem like an efficient way to do it, so I wouldn't be surprised if there is something more direct.

d.index.name starts off as 'foo';

def f(df, name):
    df.index.name = name
    return df

d.map_partitions(f, 'pow')

The output now has index name of 'pow'. If this is done with the threaded scheduler, I think you also change the index name of d in-place (in which case you don't really need the output of map_partitions).


问:
Is there any info table/matrix which shows the attributes of char, varchar, text, real, double, float, binary, set, int, integer, longtext?
Is there any info table/matrix which shows the attributes of char, varchar, text, real, double, float, binary, set, int, integer, longtext, blob, numeric, datatime, varbinary?

Edit: yes, like online documentation.

答:
Something like this?
http://kimbriggs.com/computers/computer-notes/mysql-notes/mysql-data-types-50.file</p>

ContentLicense: CC BY-SA 2.5


问:
python csv to dictionary using csv or pandas module
I am using Python's csv.DictReader to read in values from a CSV file to create a dictionary where keys are first row or headers in the CSV and other rows are values. It works perfectly as expected and I am able to get a dictionary, but I only want certain keys to be in the dictionary rather than all of the column values. What is the best way to do this? I tried using csv.reader but I don't think it has this functionality. Maybe this can be achieved using pandas?

Here is the code I was using with CSV module where Fieldnames was the keys that I wanted to retain in my dict. I realized it isn't used for what I described above.

```<code>import csv
with open(target_path+target_file) as csvfile:
    reader = csv.DictReader(csvfile,fieldnames=Fieldnames)
    for i in reader:
        print i
</code>```

答:
You can use the to_dict method to get a list of dicts:

```<code>import pandas as pd

df = pd.read_csv(target_path+target_file, names=Fieldnames)

records = df.to_dict(orient='records')

for row in records:
    print row
</code>```

to_dict documentation:

```<code>In [67]: df.to_dict?
Signature: df.to_dict(orient='dict')
Docstring:
Convert DataFrame to dictionary.

Parameters
----------
orient : str {'dict', 'list', 'series', 'split', 'records', 'index'}
    Determines the type of the values of the dictionary.

    - dict (default) : dict like {column -> {index -> value}}
    - list : dict like {column -> [values]}
    - series : dict like {column -> Series(values)}
    - split : dict like
      {index -> [index], columns -> [columns], data -> [values]}
    - records : list like
      [{column -> value}, ... , {column -> value}]
    - index : dict like {index -> {column -> value}}

      .. versionadded:: 0.17.0

    Abbreviations are allowed. `s` indicates `series` and `sp`
    indicates `split`.

Returns
-------
result : dict like {column -> {index -> value}}
File:      /usr/local/lib/python2.7/dist-packages/pandas/core/frame.py
Type:      instancemethod
</code>```

Body:
I am using Python's csv.DictReader to read in values from a CSV file to create a dictionary where keys are first row or headers in the CSV and other rows are values. It works perfectly as expected and I am able to get a dictionary, but I only want certain keys to be in the dictionary rather than all of the column values. What is the best way to do this? I tried using csv.reader but I don't think it has this functionality. Maybe this can be achieved using pandas?

Here is the code I was using with CSV module where Fieldnames was the keys that I wanted to retain in my dict. I realized it isn't used for what I described above.

import csv
with open(target_path+target_file) as csvfile:
    reader = csv.DictReader(csvfile,fieldnames=Fieldnames)
    for i in reader:
        print i

Body:
You can use the to_dict method to get a list of dicts:

import pandas as pd

df = pd.read_csv(target_path+target_file, names=Fieldnames)

records = df.to_dict(orient='records')

for row in records:
    print row

to_dict documentation:

In [67]: df.to_dict?
Signature: df.to_dict(orient='dict')
Docstring:
Convert DataFrame to dictionary.

Parameters
----------
orient : str {'dict', 'list', 'series', 'split', 'records', 'index'}
    Determines the type of the values of the dictionary.

    - dict (default) : dict like {column -> {index -> value}}
    - list : dict like {column -> [values]}
    - series : dict like {column -> Series(values)}
    - split : dict like
      {index -> [index], columns -> [columns], data -> [values]}
    - records : list like
      [{column -> value}, ... , {column -> value}]
    - index : dict like {index -> {column -> value}}

      .. versionadded:: 0.17.0

    Abbreviations are allowed. `s` indicates `series` and `sp`
    indicates `split`.

Returns
-------
result : dict like {column -> {index -> value}}
File:      /usr/local/lib/python2.7/dist-packages/pandas/core/frame.py
Type:      instancemethod


问:
How to change a listbox unselected item colour from code behind
I have to create listBox via code behind. After that I have to change the colour that the selected item has when the listbox is not selected.
I have found that solution but am not able to render it via code behind.

Thank you

答:
As you've already seen the answer as in the link, you need to apply a style. Now You need help applying that style (defined in XAML) via code behind? If yes then apply the below code:

```<code>Style style = this.FindResource("YourStyleName") as Style;
myListBox.Style = style;
</code>```

The above code works if your style is defined in the same Window's XAML. If it's somewhere else, follow the below code:

```<code>Style style = Application.Current.FindResource("YourStyleName") as Style;
myListBox.Style = style;
</code>```

That being said, I would not recommend adding a listbox via C# as it can be tough to handle UI via C#. I would recommend defining listbox in XAML and using databinding, INotifyPropertyChanged to reduce your code complexity.

I hope I've answered your question. let me know if there is anything else in the comments section.

Also, please note: in the question the link you've mentioned. exactly like that the style will go in the XAML

Body:
As you've already seen the answer as in the link, you need to apply a style. Now You need help applying that style (defined in XAML) via code behind? If yes then apply the below code:

Style style = this.FindResource("YourStyleName") as Style;
myListBox.Style = style;

The above code works if your style is defined in the same Window's XAML. If it's somewhere else, follow the below code:

Style style = Application.Current.FindResource("YourStyleName") as Style;
myListBox.Style = style;

That being said, I would not recommend adding a listbox via C# as it can be tough to handle UI via C#. I would recommend defining listbox in XAML and using databinding, INotifyPropertyChanged to reduce your code complexity.

I hope I've answered your question. let me know if there is anything else in the comments section.

Also, please note: in the question the link you've mentioned. exactly like that the style will go in the XAML


问:
Large graph processing on Hadoop
I am working on a project that involves a RandomWalk on a large graph(too big to fit in memory). I coded it in Python using networkx but soon, the graph became too big to fit in memory, and so I realised that I needed to switch to a distributed system. So, I understand the following:

I will need to use a graph database as such(Titan, neo4j, etc)

A graph processing framework such as Apache Giraph on hadoop/ graphx on spark.

Firstly, are there enough APIs to allow me to continue to code in Python, or should I switch to Java?

Secondly, I couldn't find exact documentation on how I can write my custom function of traversal(in either Giraph or graphx) in order to implement the Random Walk algorithm.

答:
My understanding is, you need to process large graphs which are stored on file systems. There are various distributed graph processing frameworks like Pregel, Pregel+, GraphX, GPS(Stanford), Mizan, PowerGraph etc.

It is worth taking a look at these frameworks. I will suggest coding in C, C++ using openMPI like which can help achieve better efficiency.

Frameworks in Java are not very memory efficient. I am not sure of API of these frameworks in Python.

It is worth taking a look at blogs and papers which give a comparative analysis of these frameworks before deciding on implementing them.

Title: Large graph processing on Hadoop


问:
OAuth2 - Authorize with no user interaction
So I'm trying to access my own data from an external app via their API. I only need access to my own data. Not trying to receive data from any of my users' accounts, so they don't need to authorize anything. So obviously I need to avoid any redirects (which seems to be the standard process the more I research OAuth...)

The process is hit the /authorize endpoint, which returns a code. Then provide that code in a request to the /token endpoint. Which then allows me to access my account via the API. I'm 95% sure this process is standard for all OAuth, but figured I'd provide details in case it's not.

How do I provide credentials on the back end to get a code to enter into the request for a token, so that all user interaction is negated? The API I'm using forces me to use OAuth.

答:
The Oauth 2 grant flow that you're describing is the Authorization Code Grant Flow, like NtFreX's answer says. And like they say, if you have the option of using one of the above two grants with that API, that's the easiest solution.

However, if you don't, there's still a way to avoid "user interaction". It's unclear what you mean by "user interaction", but in the Authorization Code flow, that usually means logging into a web app that calls the API you are trying to authenticate into, and then consenting on the consent page. See https://dev.fitbit.com/docs/oauth2/#authorization-page for an example (I implemented OAuth 2 for Fitbit :)). You'll need to use an automated web browser like Selenium to click the consent button. Then you can capture the code in the response from /authorize and send the code to the access token endpoint.

ContentLicense: CC BY-SA 4.0


问:
Every possible combos for an island in Hashi game
Here's the game : Hashiwokakero.

To solve it, I need to find all possible combinations of links + islands around every island.

Constraints are, 1 or 2 links, and one combination is enough links created for the targeted island.

For example, I have a island ['A' => 3], which means it needs 3 links to be solved, and it has 3 neighbors ['B', 'C', 'D'].

I'd like to find an algorithm which would produce such an array :

```<code>[
    ['B' => 1, 'C' => 1, 'D' => 1],
    ['B' => 1, 'C' => 2],
    ['B' => 1, 'D' => 2],
    ['B' => 2, 'C' => 1],
    ['B' => 2, 'D' => 1],
    ['C' => 1, 'D' => 2],
    ['C' => 2, 'D' => 1]
];
</code>```

Thanks.

答:
If you want to find all combinations of links (0, 1, or 2) per neighbor, with a fixed total number of links, then you could use the following recursive function:

```<code>function getPossibleLinks($value, $neighbors) {
    if ($value == 0) return [[]];
    $max = min(2, $value);
    $min = 2 - min(count($neighbors) * 2 - $value, 2);
    if ($min > 2) {
        throw new Exception('Not possible to assign that many links');
    }
    $results = [];
    for ($count = $min; $count <= $max; $count++) {
        $nextResults = getPossibleLinks($value - $count, array_slice($neighbors, 0, -1));
        foreach($nextResults as $result) {
            if ($count) $result[end($neighbors)] = $count;
            $results[] = $result;
        }
    }
    return $results;
}
</code>```

You would need to pass it the number of links as first argument ($value), and the array of neighbors as an array of strings.

Here is an example call:

```<code>$results = getPossibleLinks(3, ["B", "C", "D"]);
</code>```

After this call, $results will have this content:

```<code>[
    ['B' => 2, 'C' => 1],
    ['B' => 1, 'C' => 2],
    ['B' => 2, 'D' => 1],
    ['B' => 1, 'C' => 1, 'D' => 1],
    ['C' => 2, 'D' => 1],
    ['B' => 1, 'D' => 2],
    ['C' => 1, 'D' => 2]
]
</code>```

See it run on eval.in.

Body:
Here's the game : Hashiwokakero.

To solve it, I need to find all possible combinations of links + islands around every island.

Constraints are, 1 or 2 links, and one combination is enough links created for the targeted island.

For example, I have a island ['A' => 3], which means it needs 3 links to be solved, and it has 3 neighbors ['B', 'C', 'D'].

I'd like to find an algorithm which would produce such an array :

[
    ['B' => 1, 'C' => 1, 'D' => 1],
    ['B' => 1, 'C' => 2],
    ['B' => 1, 'D' => 2],
    ['B' => 2, 'C' => 1],
    ['B' => 2, 'D' => 1],
    ['C' => 1, 'D' => 2],
    ['C' => 2, 'D' => 1]
];

Thanks.

Body:
If you want to find all combinations of links (0, 1, or 2) per neighbor, with a fixed total number of links, then you could use the following recursive function:

function getPossibleLinks($value, $neighbors) {
    if ($value == 0) return [[]];
    $max = min(2, $value);
    $min = 2 - min(count($neighbors) * 2 - $value, 2);
    if ($min > 2) {
        throw new Exception('Not possible to assign that many links');
    }
    $results = [];
    for ($count = $min; $count <= $max; $count++) {
        $nextResults = getPossibleLinks($value - $count, array_slice($neighbors, 0, -1));
        foreach($nextResults as $result) {
            if ($count) $result[end($neighbors)] = $count;
            $results[] = $result;
        }
    }
    return $results;
}

You would need to pass it the number of links as first argument ($value), and the array of neighbors as an array of strings.

Here is an example call:

$results = getPossibleLinks(3, ["B", "C", "D"]);

After this call, $results will have this content:

[
    ['B' => 2, 'C' => 1],
    ['B' => 1, 'C' => 2],
    ['B' => 2, 'D' => 1],
    ['B' => 1, 'C' => 1, 'D' => 1],
    ['C' => 2, 'D' => 1],
    ['B' => 1, 'D' => 2],
    ['C' => 1, 'D' => 2]
]

See it run on eval.in.


问:
MVC Code First Database Without Data: Where is the Database?
Got three simple classes

```<code>namespace MVC_Risk.Models
{
    public class Customer
    {
        public string SrcSys { get; set; }
        public string CustumerID { get; set; }
        public string CustNm { get; set; }

        public virtual ICollection<Account> Accounts { get; set; }
    }
}

namespace MVC_Risk.Models
{
    public class Account
    {
        public string SrcSys { get; set; }
        public string CustomerID { get; set; }
        public string AccountID { get; set; }

        public virtual ICollection<Balance> Balances { get; set; }
        public virtual Customer Customers { get; set; }
    }
}

namespace MVC_Risk.Models
{
    public class Balance
    {
        public int BalanceID { get; set; }
        public int EntryNo { get; set; }
        public DateTime RepDt { get; set; }
        public string SrcSys { get; set; }
        public string CustIdX { get; set; }
        public string CustNm { get; set; }
        public string AccountID { get; set; }
        public string BrId { get; set; }
        public string SegId { get; set; }
        public string ProdId { get; set; }
        public decimal? PrOs { get; set; }
        public decimal? MupRec { get; set; }

        public virtual Account Accounts { get; set; }
    }
}
</code>```

Attempting to learn Fluent API auto-generated keys concept.

Context File:

```<code>namespace MVC_Risk.DAL
{
    public class RiskContext : DbContext
    {
        public RiskContext() : base("RiskyConnectionString")
        {
        }
        public DbSet<Customer> Customers;
        public DbSet<Account> Accounts;
        public DbSet<Balance> Balances;
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }
    }
}
</code>```

Initializer File (Requiring a clean Database (i.e. without data):

```<code>namespace MVC_Risk.DAL
{
    public class RiskyInitializer : System.Data.Entity.DropCreateDatabaseIfModelChanges<RiskContext>
    {
        protected override void Seed(RiskContext context)
        {
        }
    }
}
</code>```

Web.Config file as:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="RiskyConnectionString" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=RiskyDatabase1;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.6.2" />
    <httpRuntime targetFramework="4.6.2" />
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
    </httpModules>
  </system.web>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules>
      <remove name="ApplicationInsightsWebTracking" />
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
    </modules>
  </system.webServer>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
    </compilers>
  </system.codedom>
  <entityFramework>
    <contexts>
    <context type="MVC_Risk.DAL.RiskContext, MVC_Risk">
      <databaseInitializer type="MVC_Risk.DAL.RiskyInitializer, MVC_Risk" />
    </context>
  </contexts>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>
</code>```

Upon Building and running the site launches but database not found on (LocalDb)\MSSQLLocalDB?

答: Did you run your initial Entity Framework Migration?</p>

Body:
Got three simple classes

namespace MVC_Risk.Models
{
    public class Customer
    {
        public string SrcSys { get; set; }
        public string CustumerID { get; set; }
        public string CustNm { get; set; }

        public virtual ICollection<Account> Accounts { get; set; }
    }
}

namespace MVC_Risk.Models
{
    public class Account
    {
        public string SrcSys { get; set; }
        public string CustomerID { get; set; }
        public string AccountID { get; set; }

        public virtual ICollection<Balance> Balances { get; set; }
        public virtual Customer Customers { get; set; }
    }
}

namespace MVC_Risk.Models
{
    public class Balance
    {
        public int BalanceID { get; set; }
        public int EntryNo { get; set; }
        public DateTime RepDt { get; set; }
        public string SrcSys { get; set; }
        public string CustIdX { get; set; }
        public string CustNm { get; set; }
        public string AccountID { get; set; }
        public string BrId { get; set; }
        public string SegId { get; set; }
        public string ProdId { get; set; }
        public decimal? PrOs { get; set; }
        public decimal? MupRec { get; set; }

        public virtual Account Accounts { get; set; }
    }
}

Attempting to learn Fluent API auto-generated keys concept.

Context File:

namespace MVC_Risk.DAL
{
    public class RiskContext : DbContext
    {
        public RiskContext() : base("RiskyConnectionString")
        {
        }
        public DbSet<Customer> Customers;
        public DbSet<Account> Accounts;
        public DbSet<Balance> Balances;
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }
    }
}

Initializer File (Requiring a clean Database (i.e. without data):

namespace MVC_Risk.DAL
{
    public class RiskyInitializer : System.Data.Entity.DropCreateDatabaseIfModelChanges<RiskContext>
    {
        protected override void Seed(RiskContext context)
        {
        }
    }
}

Web.Config file as:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>

  </configSections>
  <connectionStrings>
    <add name="RiskyConnectionString" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=RiskyDatabase1;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.6.2" />
    <httpRuntime targetFramework="4.6.2" />
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
    </httpModules>
  </system.web>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules>
      <remove name="ApplicationInsightsWebTracking" />
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
    </modules>
  </system.webServer>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
    </compilers>
  </system.codedom>
  <entityFramework>
    <contexts>
    <context type="MVC_Risk.DAL.RiskContext, MVC_Risk">
      <databaseInitializer type="MVC_Risk.DAL.RiskyInitializer, MVC_Risk" />
    </context>
  </contexts>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

Upon Building and running the site launches but database not found on (LocalDb)\MSSQLLocalDB?


问:
How to pick names with spaces and ` ' ` in cbind in R?
I'm trying to pick column names that would allow spaces and special characters ' in them. Specifically, I want to use Cohen's d as the column name for in cbind() below. But right now, I have to Cohensd otherwise I get an error.

How can I use Cohen's d in cbind() below?

```<code>cbind(Cohensd = c(1, 2), Mean.diff = c(3, 4) )
</code>```

答:
We can use backquotes</p>

```<code>cbind(`Cohen's d` = c(1, 2), Mean.diff = c(3, 4) )
#     Cohen's d Mean.diff
#[1,]         1         3
#[2,]         2         4
</code>```

Body:
I'm trying to pick column names that would allow spaces and special characters ' in them. Specifically, I want to use Cohen's d as the column name for in cbind() below. But right now, I have to Cohensd otherwise I get an error.

How can I use Cohen's d in cbind() below?

cbind(Cohensd = c(1, 2), Mean.diff = c(3, 4) )

Body:
We can use backquotes

cbind(`Cohen's d` = c(1, 2), Mean.diff = c(3, 4) )
#     Cohen's d Mean.diff
#[1,]         1         3
#[2,]         2         4


问:
PyTorch Linear layer input dimension mismatch
Im getting this error when passing the input data to the Linear (Fully Connected Layer) in PyTorch:

```<code>matrices expected, got 4D, 2D tensors
</code>```

I fully understand the problem since the input data has a shape (N,C,H,W) (from a Convolutional+MaxPool layer) where:

N: Data Samples

C: Channels of the data

H,W: Height and Width

Nevertheless I was expecting PyTorch to do the "reshaping" of the data form:

[ N , D1,...Dn] --> [ N, D] where D = D1*D2*....Dn

I try to reshape the Variable.data, but I've read that this approach is not recommended since the gradients will conserve the previous shape, and that in general you should not mutate a Variable.data shape.

I am pretty sure there is a simple solution that goes along with the framework, but i haven't find it.

Is there a good solution for this?

PD: The Fully connected layer has as input size the value C * H * W

答:
After reading some Examples I found the solution. here is how you do it without messing up the forward/backward pass flow:</p>
```<code>(_, C, H, W) = x.data.size()
x = x.view( -1 , C * H * W)
</code>```

Body:
Im getting this error when passing the input data to the Linear (Fully Connected Layer) in PyTorch:

matrices expected, got 4D, 2D tensors

I fully understand the problem since the input data has a shape (N,C,H,W) (from a Convolutional+MaxPool layer) where:

N: Data Samples

C: Channels of the data

H,W: Height and Width

Nevertheless I was expecting PyTorch to do the "reshaping" of the data form:

[ N , D1,...Dn] --> [ N, D] where D = D1*D2*....Dn

I try to reshape the Variable.data, but I've read that this approach is not recommended since the gradients will conserve the previous shape, and that in general you should not mutate a Variable.data shape.

I am pretty sure there is a simple solution that goes along with the framework, but i haven't find it.

Is there a good solution for this?

PD: The Fully connected layer has as input size the value C * H * W

Body:
After reading some Examples I found the solution. here is how you do it without messing up the forward/backward pass flow:

(_, C, H, W) = x.data.size()
x = x.view( -1 , C * H * W)


问:
Phantom Brackets in Ajax Call when sending an Array to Django
I am trying to send a normal javascript array through an Ajax call and something weird is happening.

Here's my function:

```<code>// Save new Strategy
$('.tab-pane').on('click', 'button.saveStrat', function() {

      var stratType = $('#typeValue').val();   // Set by newEntry method in swot-nav.js
      var label = $('#newStratLabel').val();           // Form element in new_swot_modal.html
      var details = $('#newStratDetails').val();       // Form element edit_swot_modal.html
      var entries = [];

      // Build a list of SWOT entries that the user has identified as associated to this strategy.
      $('input.entryCheckbox[type=checkbox]').each(function () {
           if (this.checked) {
               entries.push($(this).val());
           }
         });

      console.log(entries);

      $.ajax({
          url: '/add_swot_strategy/',
          type: "POST",
          data: {
              'type': stratType,
              'label': label,
              'details': details,
              'entries': entries
          },

          dataType: 'json',
          success: function (data) {
              appendNewItem(data, swotType)
          }
      });

      resetAddForm()

  });
</code>```

And here is how my Django test server receives it:

<QueryDict: {'label': [''], 'type': ['A'], 'details': [''], 'entries[]': ['16', '23', '26']}>

What's with the extra brackets after the entries label? Is this intended behavior?

Can I go ahead and do it this way or am I breaking the rules?

答:
This is expected behavior.

https://github.com/django/django/blob/master/django/utils/datastructures.py

Obtain the list data with: request.POST.getlist('entries')

Body:
I am trying to send a normal javascript array through an Ajax call and something weird is happening.

Here's my function:

// Save new Strategy
$('.tab-pane').on('click', 'button.saveStrat', function() {

      var stratType = $('#typeValue').val();   // Set by newEntry method in swot-nav.js
      var label = $('#newStratLabel').val();           // Form element in new_swot_modal.html
      var details = $('#newStratDetails').val();       // Form element edit_swot_modal.html
      var entries = [];

      // Build a list of SWOT entries that the user has identified as associated to this strategy.
      $('input.entryCheckbox[type=checkbox]').each(function () {
           if (this.checked) {
               entries.push($(this).val());
           }
         });

      console.log(entries);

      $.ajax({
          url: '/add_swot_strategy/',
          type: "POST",
          data: {
              'type': stratType,
              'label': label,
              'details': details,
              'entries': entries
          },

          dataType: 'json',
          success: function (data) {
              appendNewItem(data, swotType)
          }
      });

      resetAddForm()

  });

And here is how my Django test server receives it:

<QueryDict: {'label': [''], 'type': ['A'], 'details': [''], 'entries[]': ['16', '23', '26']}>

What's with the extra brackets after the entries label? Is this intended behavior?

Can I go ahead and do it this way or am I breaking the rules?


问:
Using gganimate and ggplot for a boxplot: Cumulative not working
I'm trying to produce an animation for a simulation model, and I want to show how the distribution of results changes as the simulation runs.

I've seen gganimate used for scatter plots but not for boxplots (or ideally violin plots). Here I've provided a reprex.

When I use sim_category (which is a bucket for a certain number of simulation runs) I want the result to be cumulative of all previous runs to show the total distribution.

In this example (and my actual code), cumulative = TRUE does not do this. Why is this?

```<code>library(gganimate)
library(animation)
library(ggplot2)

df = as.data.frame(structure(list(ID = c(1,1,2,2,1,1,2,2,1,1,2,2),
                                  value = c(10,15,5,10,7,17,4,12,9,20,6,17),
                                  sim_category = c(1,1,1,1,2,2,2,2,3,3,3,3))))

df$ID <- factor(df$ID, levels = (unique(df$ID)))
df$sim_category <- factor(df$sim_category, levels = (unique(df$sim_category)))
ani.options(convert = shQuote('C:/Program Files/ImageMagick-7.0.5-Q16/magick.exe'))

p <- ggplot(df, aes(ID, value, frame= sim_category, cumulative = TRUE)) + geom_boxplot(position = "identity")

gganimate(p)
</code>```

答:
gganimate's cumulative doesn't accumulate the data, it just keeps gif frames in subsequent frames as they appear. To achieve what you want, you have to do the accumulation before building the plot, something along the following lines:

library(tidyverse)
library(gganimate)

df <- data_frame(
  ID = factor(c(1,1,2,2,1,1,2,2,1,1,2,2), levels = 1:2),
  value = c(10,15,5,10,7,17,4,12,9,20,6,17),
  sim_category = factor(c(1,1,1,1,2,2,2,2,3,3,3,3), levels = 1:3)
)

p <- df %>%
  pull(sim_category) %>%
  levels() %>%
  as.integer() %>%
  map_df(~ df %>% filter(sim_category %in% 1:.x) %>% mutate(sim_category = .x)) %>%
  ggplot(aes(ID, value, frame = factor(sim_category))) +
  geom_boxplot(position = "identity")

gganimate(p)
```

Body:
I'm trying to produce an animation for a simulation model, and I want to show how the distribution of results changes as the simulation runs.

I've seen gganimate used for scatter plots but not for boxplots (or ideally violin plots). Here I've provided a reprex.

When I use sim_category (which is a bucket for a certain number of simulation runs) I want the result to be cumulative of all previous runs to show the total distribution.

In this example (and my actual code), cumulative = TRUE does not do this. Why is this?

library(gganimate)
library(animation)
library(ggplot2)

df = as.data.frame(structure(list(ID = c(1,1,2,2,1,1,2,2,1,1,2,2),
                                  value = c(10,15,5,10,7,17,4,12,9,20,6,17),
                                  sim_category = c(1,1,1,1,2,2,2,2,3,3,3,3))))

df$ID <- factor(df$ID, levels = (unique(df$ID)))
df$sim_category <- factor(df$sim_category, levels = (unique(df$sim_category)))
ani.options(convert = shQuote('C:/Program Files/ImageMagick-7.0.5-Q16/magick.exe'))

p <- ggplot(df, aes(ID, value, frame= sim_category, cumulative = TRUE)) + geom_boxplot(position = "identity")

gganimate(p)


问:
Android: How to handle right to left swipe gestures
I want my app to recognize when a user swipes from right to left on the phone screen.

How to do this?

答:
You don't need complicated calculations.
It can be done just by using OnGestureListener interface from GestureDetector class.

Inside onFling method you can detect all four directions like this:

MyGestureListener.java:

```<code>import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;

public class MyGestureListener implements GestureDetector.OnGestureListener{

    private static final long VELOCITY_THRESHOLD = 3000;

    @Override
    public boolean onDown(final MotionEvent e){ return false; }

    @Override
    public void onShowPress(final MotionEvent e){ }

    @Override
    public boolean onSingleTapUp(final MotionEvent e){ return false; }

    @Override
    public boolean onScroll(final MotionEvent e1, final MotionEvent e2, final float distanceX,
                        final float distanceY){ return false; }

    @Override
    public void onLongPress(final MotionEvent e){ }

    @Override
    public boolean onFling(final MotionEvent e1, final MotionEvent e2,
                       final float velocityX,
                       final float velocityY){

        if(Math.abs(velocityX) < VELOCITY_THRESHOLD
                    && Math.abs(velocityY) < VELOCITY_THRESHOLD){
            return false;//if the fling is not fast enough then it's just like drag
        }

        //if velocity in X direction is higher than velocity in Y direction,
        //then the fling is horizontal, else->vertical
        if(Math.abs(velocityX) > Math.abs(velocityY)){
            if(velocityX >= 0){
                Log.i("TAG", "swipe right");
            }else{//if velocityX is negative, then it's towards left
                Log.i("TAG", "swipe left");
            }
        }else{
            if(velocityY >= 0){
                Log.i("TAG", "swipe down");
            }else{
                Log.i("TAG", "swipe up");
            }
        }

        return true;
    }
}
</code>```

usage:

```<code>GestureDetector mDetector = new GestureDetector(MainActivity.this, new MyGestureListener());

view.setOnTouchListener(new View.OnTouchListener(){
    @Override
    public boolean onTouch(final View v, final MotionEvent event){
        return mDetector.onTouchEvent(event);
    }
});
</code>```

Body:
You don't need complicated calculations.
It can be done just by using OnGestureListener interface from GestureDetector class.

Inside onFling method you can detect all four directions like this:

MyGestureListener.java:

import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;

public class MyGestureListener implements GestureDetector.OnGestureListener{

    private static final long VELOCITY_THRESHOLD = 3000;

    @Override
    public boolean onDown(final MotionEvent e){ return false; }

    @Override
    public void onShowPress(final MotionEvent e){ }

    @Override
    public boolean onSingleTapUp(final MotionEvent e){ return false; }

    @Override
    public boolean onScroll(final MotionEvent e1, final MotionEvent e2, final float distanceX,
                        final float distanceY){ return false; }

    @Override
    public void onLongPress(final MotionEvent e){ }

    @Override
    public boolean onFling(final MotionEvent e1, final MotionEvent e2,
                       final float velocityX,
                       final float velocityY){

        if(Math.abs(velocityX) < VELOCITY_THRESHOLD
                    && Math.abs(velocityY) < VELOCITY_THRESHOLD){
            return false;//if the fling is not fast enough then it's just like drag
        }

        //if velocity in X direction is higher than velocity in Y direction,
        //then the fling is horizontal, else->vertical
        if(Math.abs(velocityX) > Math.abs(velocityY)){
            if(velocityX >= 0){
                Log.i("TAG", "swipe right");
            }else{//if velocityX is negative, then it's towards left
                Log.i("TAG", "swipe left");
            }
        }else{
            if(velocityY >= 0){
                Log.i("TAG", "swipe down");
            }else{
                Log.i("TAG", "swipe up");
            }
        }

        return true;
    }
}

usage:

GestureDetector mDetector = new GestureDetector(MainActivity.this, new MyGestureListener());

view.setOnTouchListener(new View.OnTouchListener(){
    @Override
    public boolean onTouch(final View v, final MotionEvent event){
        return mDetector.onTouchEvent(event);
    }
});


问:
If Java is truly platform independent, why is there no one-for-all clearConsoleOutput libraryMethod?
I wanted to write an application for windows/mac/linux and I chose java because a java developer friend told me Java is platform independent.

I came to a problem where I wanted to clear the console (to make the reading easier on the user).

I've tried System.out.flush(); and Runtime.getRuntime().exec("cls");.

It seems the only real solution is to use a hack (and smelly code is bad) - Java: Clear the console (check "Dyndrilliac" answer).

The reason using this hack is bad, as other users have commented on "Dyndrilliac" answer, what happens when Microsoft or Apple changes the command name from "cls" or "clear" to something different? It pretty much breaks your application and you get an error (such as "command not recognized") from the OS Company.

So my question is: did Java decide not to implement a library that handles clearing console outputs due to keeping it up to date whenever Windows/Macs/Linux decides to change it's command names? Or did Java implement a library for handling this, and I just can't find it?

答:
A) because there are many many more platforms java is running on that might have extremely different views on what a console is.

B) in order to give decent tooling for console based applications, you need much more than simple "clear" commands (think nurses here!)

And finally: when Java came into existence, anything was about applets and ui. Probably nobody wanted to invest much energy in supporting "legacy style" command line programming. (that last point is probably closer to an opinion than a hard fact).


问:
SELECT certain fields based on certain WHERE conditions
I am writing an advanced MySQL query that searches a database and retrieves user information. What I am wondering is can I select certain fields if WHERE condition 1 is met and select other fields if WHERE condition 2 is met?

Database: users

```<code>------------------------
| user_id | first_name |
------------------------
|    1    |    John    |
------------------------
|    2    |    Chris   |
------------------------
|    3    |     Sam    |
------------------------
|    4    |    Megan   |
------------------------
</code>```

Database: friendship

```<code>--------------------------------------
| user_id_one | user_id_two | status |
--------------------------------------
|      2      |      4      |    0   |
--------------------------------------
|      4      |      1      |    1   |
--------------------------------------

Status 0 = Unconfirmed
Status 1 = Confirmed
</code>```

OK, as you can see John & Megan are confirmed friends while Chris & Megan are friends but the relationship is unconfirmed.

The query I am trying to write is as follow: Megan(4) searches for new friends I want all of the users except for the ones she is a confirmed friend with to be returned. So, the results should return 2,3. But since a relationship with user_id 2 exists but is not confirmed, I want to also return the status since an entry in the friendship table does exist between the two. If a user exist but there is no connection in the relationship table it still returns that users information but returns status as a NULL or doesn't return status at all since it doesn't exist in that table.

I hope this makes since. Ask questions if you need to.

答:
Why not use a left join or an if-not-exists?

```<code>SELECT users.*
FROM (users LEFT JOIN friendships
       ON status=1 AND (user_id_one=user_id OR user_id_two=user_id) )
WHERE
     status IS NULL
</code>```

or

```<code>SELECT users.*
FROM users
WHERE
NOT EXISTS (SELECT *
            FROM friendships
            WHERE status=1
            AND (user_id_one=user_id
                 OR user_id_two=user_id))
</code>```

Body:
I am writing an advanced MySQL query that searches a database and retrieves user information. What I am wondering is can I select certain fields if WHERE condition 1 is met and select other fields if WHERE condition 2 is met?

Database: users

------------------------
| user_id | first_name |
------------------------
|    1    |    John    |
------------------------
|    2    |    Chris   |
------------------------
|    3    |     Sam    |
------------------------
|    4    |    Megan   |
------------------------

Database: friendship

--------------------------------------
| user_id_one | user_id_two | status |
--------------------------------------
|      2      |      4      |    0   |
--------------------------------------
|      4      |      1      |    1   |
--------------------------------------

Status 0 = Unconfirmed
Status 1 = Confirmed

OK, as you can see John & Megan are confirmed friends while Chris & Megan are friends but the relationship is unconfirmed.

The query I am trying to write is as follow: Megan(4) searches for new friends I want all of the users except for the ones she is a confirmed friend with to be returned. So, the results should return 2,3. But since a relationship with user_id 2 exists but is not confirmed, I want to also return the status since an entry in the friendship table does exist between the two. If a user exist but there is no connection in the relationship table it still returns that users information but returns status as a NULL or doesn't return status at all since it doesn't exist in that table.

I hope this makes since. Ask questions if you need to.

Body:
Why not use a left join or an if-not-exists?

SELECT users.*
FROM (users LEFT JOIN friendships
       ON status=1 AND (user_id_one=user_id OR user_id_two=user_id) )
WHERE
     status IS NULL

or

SELECT users.*
FROM users
WHERE
NOT EXISTS (SELECT *
            FROM friendships
            WHERE status=1
            AND (user_id_one=user_id
                 OR user_id_two=user_id))


问:
java 9 resource file different module NoSuchFileException
I am trying to load a file which is present in the resources folder, but getting an exception.
I am using java 9, and the java file that has the code to read the file is present in some other module and the calling code is in some other module.
Can some one please suggest how to proceed here?

Exception stacktrace

```<code>java.nio.file.NoSuchFileException: genome-tags.csv
    at java.base/sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:85)
    at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:103)
    at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:108)
    at java.base/sun.nio.fs.WindowsFileSystemProvider.newByteChannel(WindowsFileSystemProvider.java:231)
    at java.base/java.nio.file.Files.newByteChannel(Files.java:364)
    at java.base/java.nio.file.Files.newByteChannel(Files.java:410)
    at java.base/java.nio.file.spi.FileSystemProvider.newInputStream(FileSystemProvider.java:384)
    at java.base/java.nio.file.Files.newInputStream(Files.java:154)
    at java.base/java.nio.file.Files.newBufferedReader(Files.java:2809)
    at java.base/java.nio.file.Files.readAllLines(Files.java:3239)
    at java.base/java.nio.file.Files.readAllLines(Files.java:3279)
    at com.bhargo.filesystem.reader/com.bhargo.filesystem.reader.FileSystemReader.read(FileSystemReader.java:15)
    at com.bhargo/com.bhargo.Main.main(Main.java:20)
</code>```

The code is:-

```<code>    public class Main {

        public static void main(String[] args) {
            ServiceLoader<IReader> serviceLoader = ServiceLoader.load(IReader.class);
            try {
                System.out.println(serviceLoader.iterator().next().read("genome-tags.csv", Main.class).size());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public interface IReader {
    List<String> read(String fileLocation, Class clazz) throws IOException;

    default File getFile(String fileLocation, Class clazz) {
        URL url = clazz.getResource(fileLocation);
        return new File(getClass().getClassLoader().getResource(fileLocation).getFile());
    }
}

    public class FileSystemReader implements IReader{
        @Override
        public List<String> read(String fileLocation, Class clazz) throws IOException {
            return Files.readAllLines(Paths.get(getFile(fileLocation, clazz).getName()));
        }
    }
</code>```

Thanks,

Amar

答:
Change

```<code>public class FileSystemReader implements IReader{
        @Override
        public List<String> read(String fileLocation, Class clazz) throws IOException {
            return Files.readAllLines(Paths.get(getFile(fileLocation, clazz).getName()));
        }
    }
</code>```

to

```<code>public class FileSystemReader implements IReader{
        @Override
        public List<String> read(String fileLocation, Class clazz) throws IOException {
            return Files.readAllLines(Paths.get(getFile(fileLocation, clazz).getAbsolutePath()));
        }
    }
</code>```

Body:
I am trying to load a file which is present in the resources folder, but getting an exception.
I am using java 9, and the java file that has the code to read the file is present in some other module and the calling code is in some other module.
Can some one please suggest how to proceed here?

Exception stacktrace

java.nio.file.NoSuchFileException: genome-tags.csv
    at java.base/sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:85)
    at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:103)
    at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:108)
    at java.base/sun.nio.fs.WindowsFileSystemProvider.newByteChannel(WindowsFileSystemProvider.java:231)
    at java.base/java.nio.file.Files.newByteChannel(Files.java:364)
    at java.base/java.nio.file.Files.newByteChannel(Files.java:410)
    at java.base/java.nio.file.spi.FileSystemProvider.newInputStream(FileSystemProvider.java:384)
    at java.base/java.nio.file.Files.newInputStream(Files.java:154)
    at java.base/java.nio.file.Files.newBufferedReader(Files.java:2809)
    at java.base/java.nio.file.Files.readAllLines(Files.java:3239)
    at java.base/java.nio.file.Files.readAllLines(Files.java:3279)
    at com.bhargo.filesystem.reader/com.bhargo.filesystem.reader.FileSystemReader.read(FileSystemReader.java:15)
    at com.bhargo/com.bhargo.Main.main(Main.java:20)

The code is:-

    public class Main {

        public static void main(String[] args) {
            ServiceLoader<IReader> serviceLoader = ServiceLoader.load(IReader.class);
            try {
                System.out.println(serviceLoader.iterator().next().read("genome-tags.csv", Main.class).size());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public interface IReader {
    List<String> read(String fileLocation, Class clazz) throws IOException;

    default File getFile(String fileLocation, Class clazz) {
        URL url = clazz.getResource(fileLocation);
        return new File(getClass().getClassLoader().getResource(fileLocation).getFile());
    }
}

    public class FileSystemReader implements IReader{
        @Override
        public List<String> read(String fileLocation, Class clazz) throws IOException {
            return Files.readAllLines(Paths.get(getFile(fileLocation, clazz).getName()));
        }
    }

Thanks,

Amar

Body:
Change

public class FileSystemReader implements IReader{
        @Override
        public List<String> read(String fileLocation, Class clazz) throws IOException {
            return Files.readAllLines(Paths.get(getFile(fileLocation, clazz).getName()));
        }
    }

to

public class FileSystemReader implements IReader{
        @Override
        public List<String> read(String fileLocation, Class clazz) throws IOException {
            return Files.readAllLines(Paths.get(getFile(fileLocation, clazz).getAbsolutePath()));
        }
    }


问:
Semantic UI Form validation not working
I'm pretty new to Semantic UI and I'm a little rusty on my Javascript so please bear with me. I literally just copy pasted the code from the Semantic UI example on their website to see how their form validation works and for some reason it's not working with me. Could there be something I'm missing?</p>

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <link rel="stylesheet" type="text/css" href = "https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.2/semantic.min.css">
    <link rel="stylesheet" type="text/css" href = "https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.10/components/form.css">
    <script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"> </script>
    <script src = "https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.10/semantic.min.js"> </script>
    <script src = "https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.10/components/form.js"> </script>
  </head>
  <body>
  <script>
  $('.ui.form')
    .form({
      fields: {
        name: {
          identifier: 'name',
          rules: [
            {
              type   : 'empty',
              prompt : 'Please enter your name'
            }
          ]
        },
        skills: {
          identifier: 'skills',
          rules: [
            {
              type   : 'minCount[2]',
              prompt : 'Please select at least two skills'
            }
          ]
        },
        gender: {
          identifier: 'gender',
          rules: [
            {
              type   : 'empty',
              prompt : 'Please select a gender'
            }
          ]
        },
        username: {
          identifier: 'username',
          rules: [
            {
              type   : 'empty',
              prompt : 'Please enter a username'
            }
          ]
        },
        password: {
          identifier: 'password',
          rules: [
            {
              type   : 'empty',
              prompt : 'Please enter a password'
            },
            {
              type   : 'minLength[6]',
              prompt : 'Your password must be at least {ruleValue} characters'
            }
          ]
        },
        terms: {
          identifier: 'terms',
          rules: [
            {
              type   : 'checked',
              prompt : 'You must agree to the terms and conditions'
            }
          ]
        }
      }
    })
  ;
</script>

<form class="ui form segment">
  <p>Tell Us About Yourself</p>
  <div class="two fields">
    <div class="field">
      <label>Name</label>
      <input placeholder="First Name" name="name" type="text">
    </div>
    <div class="field">
      <label>Gender</label>
      <select class="ui dropdown" name="gender">
        <option value="">Gender</option>
        <option value="male">Male</option>
        <option value="female">Female</option>
      </select>
    </div>
  </div>
<div class="two fields">
  <div class="field">
    <label>Username</label>
    <input placeholder="Username" name="username" type="text">
  </div>
  <div class="field">
    <label>Password</label>
    <input type="password" name="password">
  </div>
</div>
<div class="field">
  <label>Skills</label>
  <select name="skills" multiple="" class="ui dropdown">
    <option value="">Select Skills</option>
    <option value="css">CSS</option>
    <option value="html">HTML</option>
    <option value="javascript">Javascript</option>
    <option value="design">Graphic Design</option>
    <option value="plumbing">Plumbing</option>
    <option value="mech">Mechanical Engineering</option>
    <option value="repair">Kitchen Repair</option>
  </select>
</div>
<div class="inline field">
  <div class="ui checkbox">
    <input type="checkbox" name="terms">
    <label>I agree to the terms and conditions</label>
  </div>
</div>
<div class="ui blue submit button">Submit</div>
<div class="ui error message"></div>
  </form>
</body>
</html>
</code>```

答:
```<code>$(document).ready(function(){
  // and here your code
});
</code>```

as semantic needs jQuery to work so you have to call the semantic UI functions in jQuery.

Title: Semantic UI Form validation not working

Body:
I'm pretty new to Semantic UI and I'm a little rusty on my Javascript so please bear with me. I literally just copy pasted the code from the Semantic UI example on their website to see how their form validation works and for some reason it's not working with me. Could there be something I'm missing?

<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href = "https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.2/semantic.min.css">
    <link rel="stylesheet" type="text/css" href = "https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.10/components/form.css">

<form class="ui form segment">

Tell Us About Yourself

      Name
      <input placeholder="First Name" name="name" type="text">

      Gender
      <select class="ui dropdown" name="gender">
        <option value="">Gender</option>
        <option value="male">Male</option>
        <option value="female">Female</option>
      </select>

    Username
    <input placeholder="Username" name="username" type="text">

    Password
    <input type="password" name="password">

  Skills
  <select name="skills" multiple="" class="ui dropdown">
    <option value="">Select Skills</option>
    <option value="css">CSS</option>
    <option value="html">HTML</option>
    <option value="javascript">Javascript</option>
    <option value="design">Graphic Design</option>
    <option value="plumbing">Plumbing</option>
    <option value="mech">Mechanical Engineering</option>
    <option value="repair">Kitchen Repair</option>
  </select>

    <input type="checkbox" name="terms">
    I agree to the terms and conditions

Submit

  </form>

Body:
$(document).ready(function(){
  // and here your code
});

as semantic needs jQuery to work so you have to call the semantic UI functions in jQuery.


问:
WHERE != not working as intended in SQL
I am currently running this code:

```<code>select distinct day
from v_nem_rm16, dbp_holiday
where v_nem_rm16.day != dbp_holiday.holiday_date;
</code>```

Why am I still getting results where v_nem_rm16.day IS equal to dbp_holidays.holiday_day? I want to filter out any rows where the date in v_nem_rm16.day is equal to the dates in dbp_holidays.holiday_day.

答:
Queries that retrieve the requested data are already supplied by other posts.
But you also asked:

Why am I still getting results where v_nem_rm16.day IS equal to dbp_holidays.holiday_day?

Assume that your  dbp_holidays table  contains at least two different dates:

```<code>table: dbp_holidays

holiday_day
----------
2015-05-01
2015-07-31
2015-12-25
</code>```

table v_nem_rm16 contains dates that may  or may not coincide with a date from dbp_holidays, e.g.

```<code>table: v_nem_rm16

day
----------
2015-02-17
2015-12-25
</code>```

The cross join

```<code>select
    v_nem_rm16.day
    dbp_holidays.holiday_day
from
    v_nem_rm16,
    dbp_holidays
</code>```

retrieves the following tuples

```<code>day         holiday_day
----------  ----------
2015-02-17  2015-05-01
2015-02-17  2015-07-31
2015-02-17  2015-12-25
2015-12-25  2015-05-01
2015-12-25  2015-07-31
2015-12-25  2015-12-25
</code>```

so each row  from the  v_nem_rm16 table appears n-times, where n is the number of rows of   dbp_holidays.

Adding the where-clause may remove at most one of each v_nem_rm16.day value and there are at least n-1 rows for each v_nem_rm16.day date remaining.

So

```<code>select
    v_nem_rm16.day
    dbp_holidays.holiday_day
from
    v_nem_rm16,
    dbp_holidays
where
    v_nem_rm16.day != dbp_holidays.holiday_day
</code>```

retrieves

```<code>day         holiday_day
----------  ----------
2015-02-17  2015-05-01
2015-02-17  2015-07-31
2015-02-17  2015-12-25
2015-12-25  2015-05-01
2015-12-25  2015-07-31
</code>```

And reducing the select list to

```<code>select
    v_nem_rm16.day
from
    v_nem_rm16,
    dbp_holidays
where
    v_nem_rm16.day != dbp_holidays.holiday_day
</code>```

gives

```<code>day
----------
2015-02-17
2015-02-17
2015-02-17
2015-12-25
2015-12-25
</code>```

After applying the distinct operator

```<code>select
    distinct v_nem_rm16.day
from
    v_nem_rm16,
    dbp_holidays
where
    v_nem_rm16.day != dbp_holidays.holiday_day
</code>```

we get

```<code>day
----------
2015-02-17
2015-12-25
</code>```

So all days of the v_nem_rm16 table are returned by the select.

Title: WHERE != not working as intended in SQL

Body:
I am currently running this code:

select distinct day
from v_nem_rm16, dbp_holiday
where v_nem_rm16.day != dbp_holiday.holiday_date;

Why am I still getting results where v_nem_rm16.day IS equal to dbp_holidays.holiday_day? I want to filter out any rows where the date in v_nem_rm16.day is equal to the dates in dbp_holidays.holiday_day.

Body:
Queries that retrieve the requested data are already supplied by other posts.
But you also asked:

Why am I still getting results where v_nem_rm16.day IS equal to dbp_holidays.holiday_day?

Assume that your  dbp_holidays table  contains at least two different dates:

table: dbp_holidays

holiday_day
----------
2015-05-01
2015-07-31
2015-12-25

table v_nem_rm16 contains dates that may  or may not coincide with a date from dbp_holidays, e.g.

table: v_nem_rm16

day
----------
2015-02-17
2015-12-25

The cross join

select
    v_nem_rm16.day
    dbp_holidays.holiday_day
from
    v_nem_rm16,
    dbp_holidays

retrieves the following tuples

day         holiday_day
----------  ----------
2015-02-17  2015-05-01
2015-02-17  2015-07-31
2015-02-17  2015-12-25
2015-12-25  2015-05-01
2015-12-25  2015-07-31
2015-12-25  2015-12-25

so each row  from the  v_nem_rm16 table appears n-times, where n is the number of rows of   dbp_holidays.

Adding the where-clause may remove at most one of each v_nem_rm16.day value and there are at least n-1 rows for each v_nem_rm16.day date remaining.

So

select
    v_nem_rm16.day
    dbp_holidays.holiday_day
from
    v_nem_rm16,
    dbp_holidays
where
    v_nem_rm16.day != dbp_holidays.holiday_day

retrieves

day         holiday_day
----------  ----------
2015-02-17  2015-05-01
2015-02-17  2015-07-31
2015-02-17  2015-12-25
2015-12-25  2015-05-01
2015-12-25  2015-07-31

And reducing the select list to

select
    v_nem_rm16.day
from
    v_nem_rm16,
    dbp_holidays
where
    v_nem_rm16.day != dbp_holidays.holiday_day

gives

day
----------
2015-02-17
2015-02-17
2015-02-17
2015-12-25
2015-12-25

After applying the distinct operator

select
    distinct v_nem_rm16.day
from
    v_nem_rm16,
    dbp_holidays
where
    v_nem_rm16.day != dbp_holidays.holiday_day

we get

day
----------
2015-02-17
2015-12-25

So all days of the v_nem_rm16 table are returned by the select.


问:
How are algorithms hidden in Android APKs
I came across this question on Stack Overflow:
How to avoid reverse engineering of an APK file?

But, if what they say there is true, and you can't completely protect the code, I am then still remained with a question:

What do you do when you have an algorithm you want to keep secret? I really find it hard to believe big apps such as Facebook, Gmail, etc. only obfuscate their code. Don't they somehow connect the Android Java code to a remote server where it runs all the background stuff?

For example: can you make a button in Android connect to a remote server which will do some PHP scripts on the server, and then return data to the app, just as you would do in web development? Or there is another way?

(*Currently trying to learn Android development, so maybe it has answer in further videos I am watching, but I am really curious now)

答: Put your top sekrit algorithm on a server, somewhere, and invoke it over the network.  ProGuard will not prevent reverse engineering. Investigate REST.


问:
How can I center UI elements in Xcode 8?
I'm trying to create a login screen, but when I center the elements for one device, it doesn't center them for all devices. How can I center them for all devices in Xcode 8?

答:
It will actually be centered at runtime. You just need to update the view's frame in Interface Builder.

Just select the view that's off and click the update button in the lower right corner:

If you want Interface Builder to automatically update your frames make sure the Automatically Refresh View option is enabled in Xcode's Editor menu:


问:
Dynamically size an array without Redimming it in VBA?
I'm currently developing a reporting suite that will interface with Microsoft Excel.  The languages that I've used primarily are Java, Perl, and Python.  I would consider myself a novice programmer.  The only reason that I have chosen to use VBA is because it was suggested as the best language to use if programming a Microsoft Office extension.

Those things considered, I absolutely HATE the way that arrays perform in VBA.  Specifically, having to define the size of an array instead of allowing it to grow dynamically.

How do I create dynamic arrays without having to Redim them?  I'm trying to avoid this as it is clearly resource intensive.

The only solution I have found is if you are using a single loop, whereby you can set the number of elements to equal the upper bound of the loop (assuming a count 1 iteration).

What do I do when I'm not using a single loop and this is not an option?

Is Redimming inevitable?

答:
This is a rather old question but I would like to add some context to the answers already given.

VBA does not directly provide a type for dynamic arrays and redimming is necessary to change the size. This seems to be inefficient as it potentially entails copying the contents of the array to a new location in memory. However, this is exactly what dynamic arrays do under the hood: they typically double size when they are full and shrink to half the size when they drop below quarter the size. This guarantees an average runtime for adding and removing items of O(1).

So, if you want to use arrays in VBA because of the high speed of index lookups and you also want dynamic size, you can simply emulate this behavior.

Edit:
One small correction. You get O(1) average performance for adding to or removing from the end of the array. Adding at random positions is always O(N) for arrays. (You have to shift everything.)
If you want to add at random positions, you should better use a linked list, which has bad index lookup performance (enumeration has good performance, however), a skip list, which is more complicated but has good lookup performance sacrificing insert performance, or a hash set, for which key lookups are very fast but which has larger space requirements.