问:
NumberFormatException in GPS processing
I am having a weird problem.

I am developing a program to log GPS and sensor readings periodically. My friend runs the code on his machine using Eclipse Galileo 3.6 and it works perfectly fine for her.

When I run the code on my machine which has Eclipse Galileo 3.5.2 it shows service stopped unexpectedly.

We have the same JDK version. I am not able to figure out what may be the exact problem.

Please let me know what else information I need to give in order to fix the problem.

logcat

```<code>    I/ActivityManager( 1104): Start proc com.sensor.test for service com.sensor.test/.SensorReadings: pid=3539 uid=10057 gids={3003, 1015}
D/AndroidRuntime( 3539): Shutting down VM
W/dalvikvm( 3539): threadid=1: thread exiting with uncaught exception (group=0x4001d7e0)
E/AndroidRuntime( 3539): FATAL EXCEPTION: main
E/AndroidRuntime( 3539): java.lang.RuntimeException: Error receiving broadcast Intent { act=android.intent.action.BATTERY_CHANGED flg=0x60000000 (has extras) } in com.sensor.test.SensorReadings$2@44770958
E/AndroidRuntime( 3539):    at android.app.ActivityThread$PackageInfo$ReceiverDispatcher$Args.run(ActivityThread.java:905)
E/AndroidRuntime( 3539):    at android.os.Handler.handleCallback(Handler.java:587)
E/AndroidRuntime( 3539):    at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime( 3539):    at android.os.Looper.loop(Looper.java:123)
E/AndroidRuntime( 3539):    at android.app.ActivityThread.main(ActivityThread.java:4627)
E/AndroidRuntime( 3539):    at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 3539):    at java.lang.reflect.Method.invoke(Method.java:521)
E/AndroidRuntime( 3539):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
E/AndroidRuntime( 3539):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
E/AndroidRuntime( 3539):    at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime( 3539): Caused by: java.lang.NullPointerException
E/AndroidRuntime( 3539):    at com.sensor.test.SensorReadings$2.onReceive(SensorReadings.java:327)
E/AndroidRuntime( 3539):    at android.app.ActivityThread$PackageInfo$ReceiverDispatcher$Args.run(ActivityThread.java:892)
E/AndroidRuntime( 3539):    ... 9 more
W/ActivityManager( 1104): Activity destroy timeout for HistoryRecord{44b38508 com.sensor.test/.MainScreen}
D/WifiService( 1104): acquireWifiLockLocked: WifiLock{NetworkLocationProvider type=2 binder=android.os.Binder@44963d80}
D/LocationMasfClient( 1104): getNetworkLocation(): Location not found in cache, making network request
D/LocationMasfClient( 1104): getNetworkLocation(): Number of prefetched entries 10
E/LocationMasfClient( 1104): getNetworkLocation(): Returning *server* computed location with accuracy 28
D/libgps  ( 1104): GpsInterface_inject_location( 35.772249, -78.673950, 28.000 )
D/WifiService( 1104): releaseWifiLockLocked: WifiLock{NetworkLocationProvider type=2 binder=android.os.Binder@44963d80}
D/WifiService( 1104): acquireWifiLockLocked: WifiLock{NetworkLocationProvider type=2 binder=android.os.Binder@44963d80}
D/WifiService( 1104): releaseWifiLockLocked: WifiLock{NetworkLocationProvider type=2 binder=android.os.Binder@44963d80}
D/NativeCrypto( 1104): Freeing OpenSSL session
D/dalvikvm( 1104): GC_FOR_MALLOC freed 22104 objects / 1169312 bytes in 128ms
D/NativeCrypto( 1104): Freeing OpenSSL session
I/Process ( 3539): Sending signal. PID: 3539 SIG: 9
W/InputManagerService( 1104): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@44b40dd0
I/ActivityManager( 1104): Process com.sensor.test (pid 3539) has died.
</code>```

The pertinent code for line 88 with parsing going on:

```<code>public void startService(){
        //startService(new Intent(MainScreen.this,SensorReadings.class));
        Intent intent = new Intent(MainScreen.this, SensorReadings.class);
        **intent.putExtra("lp", Integer.parseInt(""+longPeriod.getText()));// LINE 88**
        intent.putExtra("gp", Integer.parseInt(""+gpsPeriod.getText()));
        intent.putExtra("sp", Integer.parseInt(""+snrPeriod.getText()));
        //startActivity(intent);
        startService(intent);
    }
</code>```

Thanks.
AG

答:
```<code>E/AndroidRuntime( 2934): java.lang.NumberFormatException: unable to parse '' as integer
E/AndroidRuntime( 2934):    at java.lang.Integer.parseInt(Integer.java:412)
E/AndroidRuntime( 2934):    at java.lang.Integer.parseInt(Integer.java:382)
E/AndroidRuntime( 2934):    at com.sensor.test.MainScreen.startService(MainScreen.java:88)
</code>```

Perhaps at line 88 in MainScreen.java, your startService method is calling Integer.parseInt with an empty string?

Can you show us the pertinent code?

Title: NumberFormatException in GPS processing

Body:
I am having a weird problem.

I am developing a program to log GPS and sensor readings periodically. My friend runs the code on his machine using Eclipse Galileo 3.6 and it works perfectly fine for her.

When I run the code on my machine which has Eclipse Galileo 3.5.2 it shows service stopped unexpectedly.

We have the same JDK version. I am not able to figure out what may be the exact problem.

Please let me know what else information I need to give in order to fix the problem.

logcat

    I/ActivityManager( 1104): Start proc com.sensor.test for service com.sensor.test/.SensorReadings: pid=3539 uid=10057 gids={3003, 1015}
D/AndroidRuntime( 3539): Shutting down VM
W/dalvikvm( 3539): threadid=1: thread exiting with uncaught exception (group=0x4001d7e0)
E/AndroidRuntime( 3539): FATAL EXCEPTION: main
E/AndroidRuntime( 3539): java.lang.RuntimeException: Error receiving broadcast Intent { act=android.intent.action.BATTERY_CHANGED flg=0x60000000 (has extras) } in com.sensor.test.SensorReadings$2@44770958
E/AndroidRuntime( 3539):    at android.app.ActivityThread$PackageInfo$ReceiverDispatcher$Args.run(ActivityThread.java:905)
E/AndroidRuntime( 3539):    at android.os.Handler.handleCallback(Handler.java:587)
E/AndroidRuntime( 3539):    at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime( 3539):    at android.os.Looper.loop(Looper.java:123)
E/AndroidRuntime( 3539):    at android.app.ActivityThread.main(ActivityThread.java:4627)
E/AndroidRuntime( 3539):    at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 3539):    at java.lang.reflect.Method.invoke(Method.java:521)
E/AndroidRuntime( 3539):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
E/AndroidRuntime( 3539):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
E/AndroidRuntime( 3539):    at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime( 3539): Caused by: java.lang.NullPointerException
E/AndroidRuntime( 3539):    at com.sensor.test.SensorReadings$2.onReceive(SensorReadings.java:327)
E/AndroidRuntime( 3539):    at android.app.ActivityThread$PackageInfo$ReceiverDispatcher$Args.run(ActivityThread.java:892)
E/AndroidRuntime( 3539):    ... 9 more
W/ActivityManager( 1104): Activity destroy timeout for HistoryRecord{44b38508 com.sensor.test/.MainScreen}
D/WifiService( 1104): acquireWifiLockLocked: WifiLock{NetworkLocationProvider type=2 binder=android.os.Binder@44963d80}
D/LocationMasfClient( 1104): getNetworkLocation(): Location not found in cache, making network request
D/LocationMasfClient( 1104): getNetworkLocation(): Number of prefetched entries 10
E/LocationMasfClient( 1104): getNetworkLocation(): Returning *server* computed location with accuracy 28
D/libgps  ( 1104): GpsInterface_inject_location( 35.772249, -78.673950, 28.000 )
D/WifiService( 1104): releaseWifiLockLocked: WifiLock{NetworkLocationProvider type=2 binder=android.os.Binder@44963d80}
D/WifiService( 1104): acquireWifiLockLocked: WifiLock{NetworkLocationProvider type=2 binder=android.os.Binder@44963d80}
D/WifiService( 1104): releaseWifiLockLocked: WifiLock{NetworkLocationProvider type=2 binder=android.os.Binder@44963d80}
D/NativeCrypto( 1104): Freeing OpenSSL session
D/dalvikvm( 1104): GC_FOR_MALLOC freed 22104 objects / 1169312 bytes in 128ms
D/NativeCrypto( 1104): Freeing OpenSSL session
I/Process ( 3539): Sending signal. PID: 3539 SIG: 9
W/InputManagerService( 1104): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@44b40dd0
I/ActivityManager( 1104): Process com.sensor.test (pid 3539) has died.

The pertinent code for line 88 with parsing going on:

public void startService(){
        //startService(new Intent(MainScreen.this,SensorReadings.class));
        Intent intent = new Intent(MainScreen.this, SensorReadings.class);
        **intent.putExtra("lp", Integer.parseInt(""+longPeriod.getText()));// LINE 88**
        intent.putExtra("gp", Integer.parseInt(""+gpsPeriod.getText()));
        intent.putExtra("sp", Integer.parseInt(""+snrPeriod.getText()));
        //startActivity(intent);
        startService(intent);
    }

Thanks.
AG

Body:
E/AndroidRuntime( 2934): java.lang.NumberFormatException: unable to parse '' as integer
E/AndroidRuntime( 2934):    at java.lang.Integer.parseInt(Integer.java:412)
E/AndroidRuntime( 2934):    at java.lang.Integer.parseInt(Integer.java:382)
E/AndroidRuntime( 2934):    at com.sensor.test.MainScreen.startService(MainScreen.java:88)

Perhaps at line 88 in MainScreen.java, your startService method is calling Integer.parseInt with an empty string?

Can you show us the pertinent code?


来源: stackexchange

问:
What should be the maximum audio file length (duration) to be sent to Bing Speeh to Text API?
I have referred this documentation.
They have mentioned when using client libraries for speech to text, "the long audio stream (up to 10 minutes)".

Whether speech to text accepts audio file greater than 10 minutes?
What will happen if we pass audio file > 10 minutes?

And in my use case, I need to pass audio file greater than 30 minutes. So what we have to do for these situations?

答:
You can split your longer audio streams programmatically using ffmpeg and pass those chunks to this client library. You can check this to programmatically divide long audio streams into time-specified chunks: https://superuser.com/questions/525210/splitting-an-audio-file-into-chunks-of-a-specified-length.

You can then combine your text from these chunks to get the entire text back. Not the cleanest of the ways - but something that will scale.

ContentLicense: CC BY-SA 3.0


问:
Wrong result using a PyCapsule created from a method in Cython
We would need to create a PyCapsule from a method of a class in Cython. We managed to write a code which compiles and even runs without error but the results are wrong.

A simple example is here: https://github.com/paugier/cython_capi/tree/master/using_cpython_pycapsule_class

The capsules are executed by Pythran (one needs to use the version on github https://github.com/serge-sans-paille/pythran).

The .pyx file:

```<code>from cpython.pycapsule cimport PyCapsule_New

cdef int twice_func(int c):
    return 2*c

cdef class Twice:
    cdef public dict __pyx_capi__

    def __init__(self):
        self.__pyx_capi__ = self.get_capi()

    cpdef get_capi(self):
        return {
            'twice_func': PyCapsule_New(
                <void *>twice_func, 'int (int)', NULL),
            'twice_cpdef': PyCapsule_New(
                <void *>self.twice_cpdef, 'int (int)', NULL),
            'twice_cdef': PyCapsule_New(
                <void *>self.twice_cdef, 'int (int)', NULL),
            'twice_static': PyCapsule_New(
                <void *>self.twice_static, 'int (int)', NULL)}

    cpdef int twice_cpdef(self, int c):
        return 2*c

    cdef int twice_cdef(self, int c):
        return 2*c

    @staticmethod
    cdef int twice_static(int c):
        return 2*c
</code>```

The file compiled by pythran (call_capsule_pythran.py).

```<code># pythran export call_capsule(int(int), int)

def call_capsule(capsule, n):
    r = capsule(n)
    return r
</code>```

Once again it is a new feature of Pythran so one needs the version on github...

And the test file:

```<code>try:
    import faulthandler
    faulthandler.enable()
except ImportError:
    pass

import unittest

from twice import Twice
from call_capsule_pythran import call_capsule

class TestAll(unittest.TestCase):
    def setUp(self):
        self.obj = Twice()
        self.capi = self.obj.__pyx_capi__

    def test_pythran(self):
        value = 41
        print('\n')

        for name, capsule in self.capi.items():
            print('capsule', name)
            result = call_capsule(capsule, value)

            if name.startswith('twice'):
                if result != 2*value:
                    how = 'wrong'
                else:
                    how = 'good'

                print(how, f'result ({result})\n')

if __name__ == '__main__':
    unittest.main()
</code>```

It is buggy and gives:

```<code>capsule twice_func
good result (82)

capsule twice_cpdef
wrong result (4006664390)

capsule twice_cdef
wrong result (4006664390)

capsule twice_static
good result (82)
</code>```

It shows that it works fine for the standard function and for the static function but that there is a problem for the methods.

Note that the fact that it works for two capsules seems to indicate that the problem does not come from Pythran.

Edit

After DavidW's comments, I understand that we would have to create at run time (for example in get_capi) a C function with the signature int(int) from the bound method twice_cdef whose signature is actually int(Twice, int).

I don't know if this is really impossible to do with Cython...

答:
To follow up/expand on my comments:

The basic issue is that the Pythran is expecting a C function pointer with the signature int f(int) to be contained within the PyCapsule. However, the signature of your methods is int(PyObject* self, int c). The 2 gets passed as self (not causing disaster since it isn't actually used...) and some arbitrary bit of memory is used in place of the int c. Unfortunately it isn't possible to use pure C code to create a C function pointer with "bound arguments" so Cython can't (and realistically won't be able to) do it.

Modification 1 is to get better compile-time type checking of what you're passing to your PyCapsules by creating a function that accepts the correct types and casting in there, rather than just casting to <void*> blindly. This doesn't solve your problem but warns you at compile-time when it isn't going to work:

```<code>ctypedef int(*f_ptr_type)(int)

cdef make_PyCapsule(f_ptr_type f, string):
    return PyCapsule_New(
                <void *>f, string, NULL)

# then in get_capi:
'twice_func': make_PyCapsule(twice_func, b'int (int)'), # etc
</code>```

It is actually possible to create C function from arbitrary Python callables using ctypes (or cffi) - see Using function pointers to methods of classes without the gil (bottom of answer). This adds an extra layer of Python calls so isn't terribly quick, and the code is a bit messy. ctypes achieves this by using runtime code generation (which isn't that portable or something you can do in pure C) to build a function on the fly and then create a pointer to that.

Although you claim in the comments that you don't think you can use the Python interpreter, I don't think this is true - Pythran generates Python extension modules (so is pretty bound to the Python interpreter) and it seems to work in your test case shown here:

```<code> _func_cache = []

cdef f_ptr_type py_to_fptr(f):
    import ctypes
    functype = ctypes.CFUNCTYPE(ctypes.c_int,ctypes.c_int)
    ctypes_f = functype(f)
    _func_cache.append(ctypes_f) # ensure references are kept
    return (<f_ptr_type*><size_t>ctypes.addressof(ctypes_f))[0]

# then in make_capi:
'twice_cpdef': make_PyCapsule(py_to_fptr(self.twice_cpdef), b'int (int)')
</code>```

Unfortunately it only works for cpdef and not cdef functions since it does rely on having a Python callable. cdef functions can be made to work with a lambda (provided you change get_capi to def instead of cpdef):

```<code>'twice_cdef': make_PyCapsule(py_to_fptr(lambda x: self.twice_cdef(x)), b'int (int)'),
</code>```

It's all a little messy but can be made to work.

Body:
We would need to create a PyCapsule from a method of a class in Cython. We managed to write a code which compiles and even runs without error but the results are wrong.

A simple example is here: https://github.com/paugier/cython_capi/tree/master/using_cpython_pycapsule_class

The capsules are executed by Pythran (one needs to use the version on github https://github.com/serge-sans-paille/pythran).

The .pyx file:

from cpython.pycapsule cimport PyCapsule_New

cdef int twice_func(int c):
    return 2*c

cdef class Twice:
    cdef public dict __pyx_capi__

    def __init__(self):
        self.__pyx_capi__ = self.get_capi()

    cpdef get_capi(self):
        return {
            'twice_func': PyCapsule_New(
                <void *>twice_func, 'int (int)', NULL),
            'twice_cpdef': PyCapsule_New(
                <void *>self.twice_cpdef, 'int (int)', NULL),
            'twice_cdef': PyCapsule_New(
                <void *>self.twice_cdef, 'int (int)', NULL),
            'twice_static': PyCapsule_New(
                <void *>self.twice_static, 'int (int)', NULL)}

    cpdef int twice_cpdef(self, int c):
        return 2*c

    cdef int twice_cdef(self, int c):
        return 2*c

    @staticmethod
    cdef int twice_static(int c):
        return 2*c

The file compiled by pythran (call_capsule_pythran.py).

# pythran export call_capsule(int(int), int)

def call_capsule(capsule, n):
    r = capsule(n)
    return r

Once again it is a new feature of Pythran so one needs the version on github...

And the test file:

try:
    import faulthandler
    faulthandler.enable()
except ImportError:
    pass

import unittest

from twice import Twice
from call_capsule_pythran import call_capsule

class TestAll(unittest.TestCase):
    def setUp(self):
        self.obj = Twice()
        self.capi = self.obj.__pyx_capi__

    def test_pythran(self):
        value = 41
        print('\n')

        for name, capsule in self.capi.items():
            print('capsule', name)
            result = call_capsule(capsule, value)

            if name.startswith('twice'):
                if result != 2*value:
                    how = 'wrong'
                else:
                    how = 'good'

                print(how, f'result ({result})\n')

if __name__ == '__main__':
    unittest.main()

It is buggy and gives:

capsule twice_func
good result (82)

capsule twice_cpdef
wrong result (4006664390)

capsule twice_cdef
wrong result (4006664390)

capsule twice_static
good result (82)

It shows that it works fine for the standard function and for the static function but that there is a problem for the methods.

Note that the fact that it works for two capsules seems to indicate that the problem does not come from Pythran.

Edit

After DavidW's comments, I understand that we would have to create at run time (for example in get_capi) a C function with the signature int(int) from the bound method twice_cdef whose signature is actually int(Twice, int).

I don't know if this is really impossible to do with Cython...

Body:
To follow up/expand on my comments:

The basic issue is that the Pythran is expecting a C function pointer with the signature int f(int) to be contained within the PyCapsule. However, the signature of your methods is int(PyObject* self, int c). The 2 gets passed as self (not causing disaster since it isn't actually used...) and some arbitrary bit of memory is used in place of the int c. Unfortunately it isn't possible to use pure C code to create a C function pointer with "bound arguments" so Cython can't (and realistically won't be able to) do it.

Modification 1 is to get better compile-time type checking of what you're passing to your PyCapsules by creating a function that accepts the correct types and casting in there, rather than just casting to <void*> blindly. This doesn't solve your problem but warns you at compile-time when it isn't going to work:

ctypedef int(*f_ptr_type)(int)

cdef make_PyCapsule(f_ptr_type f, string):
    return PyCapsule_New(
                <void *>f, string, NULL)

# then in get_capi:
'twice_func': make_PyCapsule(twice_func, b'int (int)'), # etc

It is actually possible to create C function from arbitrary Python callables using ctypes (or cffi) - see Using function pointers to methods of classes without the gil (bottom of answer). This adds an extra layer of Python calls so isn't terribly quick, and the code is a bit messy. ctypes achieves this by using runtime code generation (which isn't that portable or something you can do in pure C) to build a function on the fly and then create a pointer to that.

Although you claim in the comments that you don't think you can use the Python interpreter, I don't think this is true - Pythran generates Python extension modules (so is pretty bound to the Python interpreter) and it seems to work in your test case shown here:

 _func_cache = []

cdef f_ptr_type py_to_fptr(f):
    import ctypes
    functype = ctypes.CFUNCTYPE(ctypes.c_int,ctypes.c_int)
    ctypes_f = functype(f)
    _func_cache.append(ctypes_f) # ensure references are kept
    return (<f_ptr_type*><size_t>ctypes.addressof(ctypes_f))[0]

# then in make_capi:
'twice_cpdef': make_PyCapsule(py_to_fptr(self.twice_cpdef), b'int (int)')

Unfortunately it only works for cpdef and not cdef functions since it does rely on having a Python callable. cdef functions can be made to work with a lambda (provided you change get_capi to def instead of cpdef):

'twice_cdef': make_PyCapsule(py_to_fptr(lambda x: self.twice_cdef(x)), b'int (int)'),

It's all a little messy but can be made to work.


问:
Limit the number of hex digits with string formatting
I am displaying values in hex within my project of 4 characters as the value is 16bit.  In this instance the values are also signed and this is where my problem lies.

My code:

```<code>int16_t i = -4;
printf("i = %04x\n", i);
</code>```

Output:

```<code>i = fffffffc
</code>```

What I would like is the hex output to remain only 16-bit and not switch to a 32-bit representation.  Which it does for positive values.

Desired output:

```<code>i = fffc
</code>```

Is there a nice way of specifying the total number of hex digits, or locking the output to be the same as the minimum?  (Ideally without having to resort to manipulating the value as a string :) )

Oh, I also thought this might be a compiler thing, as I 1st experienced it within Visual C++, but testing with GCC gave the same results under Linux.

答:
The C style output with printf()

The specifier "%x" is for unsigned integers. Your int16_t gets an integer promotion in the call, and  the signed number -4 is encoded in binary as integer fffffffc that is then taken as such.

The problem with specifier "%x" is, that the size and precision in the formatting string are minimum numbers of digits.  So it's not possible to force the formatting to truncate the output.  However, you can force the expected result with a binary-and (operator &) :

```<code>printf("i = %04x\n", i & 0xffff);  // put as much f as digits you want to keep
</code>```

C++ style output

With c++ streams you can also format into hexadecimal with <iomanip>:

```<code>cout<<setw(4)<< setfill('0')<<hex<<i<<endl;
</code>```

The ostreams do not perform the integer promotion and just use the type of the value that you output.

Online demo

Body:
I am displaying values in hex within my project of 4 characters as the value is 16bit.  In this instance the values are also signed and this is where my problem lies.

My code:

int16_t i = -4;
printf("i = %04x\n", i);

Output:

i = fffffffc

What I would like is the hex output to remain only 16-bit and not switch to a 32-bit representation.  Which it does for positive values.

Desired output:

i = fffc

Is there a nice way of specifying the total number of hex digits, or locking the output to be the same as the minimum?  (Ideally without having to resort to manipulating the value as a string :) )

Oh, I also thought this might be a compiler thing, as I 1st experienced it within Visual C++, but testing with GCC gave the same results under Linux.

Body:
The C style output with printf()

The specifier "%x" is for unsigned integers. Your int16_t gets an integer promotion in the call, and  the signed number -4 is encoded in binary as integer fffffffc that is then taken as such.

The problem with specifier "%x" is, that the size and precision in the formatting string are minimum numbers of digits.  So it's not possible to force the formatting to truncate the output.  However, you can force the expected result with a binary-and (operator &) :

printf("i = %04x\n", i & 0xffff);  // put as much f as digits you want to keep

C++ style output

With c++ streams you can also format into hexadecimal with <iomanip>:

cout<<setw(4)<< setfill('0')<<hex<<i<<endl;

The ostreams do not perform the integer promotion and just use the type of the value that you output.

Online demo


问:
Expose return value
I have this piece of code that I am working on. To provide context, I am using an event source to stream an server sent event. Once I receive the data/response I want to pass that into my template(handlebars) view. The code below is a GET request in which I am trying to display the data returned from SSEvents.addEventListener.

```<code>method: 'GET',
path: '/students',
config: {
handler: (request, reply) => {
  SSEvents.addEventListener('score', function(e) {
    const data = JSON.parse(e.data);
    }, false);
      reply.view('students', {result: data});
   },
    description: "Endpoint lists all users that have received at least one test score.",
    tags: ['api']
   }
 }
</code>```

The issue with this code is the constant "data" is not available outside of the scope of the event listener. I need to find a way to expose the constant so that I can use it in reply.view('students', {result: data});

NOTE: I have tried adding "reply.view('students', {result: data});" within the event listener and it throws the following error: reply interface called twice.

Any help would be appreciated.

--Thanks!

答:
It should be working like this. How long it takes your event source to produce an answer? Did you call the reply method twice? This is only one call.</p>

```<code>handler: (request, reply) => {
        SSEvents.addEventListener('score', function(e) {
            const data = JSON.parse(e.data);
            return reply.view('students', {
                result: data
            });
        }, false);
    },
    description: "Endpoint lists all users that have received at least one test score.",
    tags: ['api']
}
</code>```

Title: Expose return value

Body:
I have this piece of code that I am working on. To provide context, I am using an event source to stream an server sent event. Once I receive the data/response I want to pass that into my template(handlebars) view. The code below is a GET request in which I am trying to display the data returned from SSEvents.addEventListener.

method: 'GET',
path: '/students',
config: {
handler: (request, reply) => {
  SSEvents.addEventListener('score', function(e) {
    const data = JSON.parse(e.data);
    }, false);
      reply.view('students', {result: data});
   },
    description: "Endpoint lists all users that have received at least one test score.",
    tags: ['api']
   }
 }

The issue with this code is the constant "data" is not available outside of the scope of the event listener. I need to find a way to expose the constant so that I can use it in reply.view('students', {result: data});

NOTE: I have tried adding "reply.view('students', {result: data});" within the event listener and it throws the following error: reply interface called twice.

Any help would be appreciated.

--Thanks!

Body:
It should be working like this. How long it takes your event source to produce an answer? Did you call the reply method twice? This is only one call.

handler: (request, reply) => {
        SSEvents.addEventListener('score', function(e) {
            const data = JSON.parse(e.data);
            return reply.view('students', {
                result: data
            });
        }, false);
    },
    description: "Endpoint lists all users that have received at least one test score.",
    tags: ['api']
}


问:
Unity resolution fails in release mode
When I deploy my app to Android device in release mode, I get the following error in the application output...

```<code>Unity.Exceptions.ResolutionFailedException: Resolution of the dependency failed, type = 'Hello.MainPage', name = '(none)'.
</code>```

That's the first thing it attempts to resolve. I've tried changing the first type that's resolved and it's the same result. So, for some reason, Unity apparently doesn't work in release mode. (Although it has in the past.)

I've reduced MainPage down to the following...

```<code>public class MainPage : TabbedPage
{

}
</code>```

... so there are no sub resolutions that are failing. It's simply not there even though I add this prior to the call...

```<code>Container.RegisterType<MainPage>();
</code>```

Why might this fail in release mode but not in debug mode?

If I set the app's main page property to a TabbedPage, then the app doesn't crash.

This does work...

```<code>    Container.RegisterInstance<string>("I love computers");

    string s = Container.Resolve<string>();
</code>```

This doesn't work...

```<code>    Container.RegisterType<MainPage>();

    MainPage = Container.Resolve<MainPage>();
</code>```

This does work...

```<code>MainPage = new MainPage();
</code>```

This does work...

```<code>    Container.RegisterInstance(new MainPage());

    MainPage = Container.Resolve<MainPage>();
</code>```

It's as if the concrete types aren't being included in the bundle unless they're new'ed up somewhere.

I thought I might need to add the [Preserve] attribute to injected classes, but it makes no difference.

Seems to be the result of setting the linker to "Link all assemblies".

答:
I've got this working by using an InjectionFactory for every concrete type. i.e. every type registration involves a new of the concrete type.

Also need to have...

```<code>[assembly: XamlCompilation(XamlCompilationOptions.Compile)]
</code>```

... else the compiler removes event handlers from the code behind!

Title: Unity resolution fails in release mode

Body:
When I deploy my app to Android device in release mode, I get the following error in the application output...

Unity.Exceptions.ResolutionFailedException: Resolution of the dependency failed, type = 'Hello.MainPage', name = '(none)'.

That's the first thing it attempts to resolve. I've tried changing the first type that's resolved and it's the same result. So, for some reason, Unity apparently doesn't work in release mode. (Although it has in the past.)

I've reduced MainPage down to the following...

public class MainPage : TabbedPage
{

}

... so there are no sub resolutions that are failing. It's simply not there even though I add this prior to the call...

Container.RegisterType<MainPage>();

Why might this fail in release mode but not in debug mode?

If I set the app's main page property to a TabbedPage, then the app doesn't crash.

This does work...

    Container.RegisterInstance<string>("I love computers");

    string s = Container.Resolve<string>();

This doesn't work...

    Container.RegisterType<MainPage>();

    MainPage = Container.Resolve<MainPage>();

This does work...

MainPage = new MainPage();

This does work...

    Container.RegisterInstance(new MainPage());

    MainPage = Container.Resolve<MainPage>();

It's as if the concrete types aren't being included in the bundle unless they're new'ed up somewhere.

I thought I might need to add the [Preserve] attribute to injected classes, but it makes no difference.

Seems to be the result of setting the linker to "Link all assemblies".

Body:
I've got this working by using an InjectionFactory for every concrete type. i.e. every type registration involves a new of the concrete type.

Also need to have...

[assembly: XamlCompilation(XamlCompilationOptions.Compile)]

... else the compiler removes event handlers from the code behind!


问:
Split categories list with custom field into two columns (Wordpress)
I’m trying to get a list of categories into two columns. Each category has a custom field ("color") created with ACF. So far so good, i can get the list in a single column with this code:

```<code><?php
          $args = array( 'hide_empty' => '0');
          $categories = get_categories($args);
          if($categories){
            echo '<div class="col"><ul class="cat-list">';
            foreach($categories as $category) {
              $color = get_field('color', 'category_'.$category->term_id);
              echo '<li style="background-color:'.$color.'">';
              echo '<a href="';
              echo esc_url( get_category_link( $category->term_id ) );
              echo '">';
              echo $category->name;
              echo '</a>';
              echo '</li>';
            }
            echo '</ul></div>';
          }
          ?>
</code>```

Now i’m trying to get the list using wp_list_categories (tip: https://wpsquare.com/display-wordpress-categories-two-columns/). This works as a solution for the two columns issue, but with this method i can’t retrieve the value from the category custom field.

Thanks in advance.

答:
$categories is an array. One of the great things you can do with an array is... look how many items you have in them, and iterate over them using a simple for-loop.

```<code><?php
  $args = array( 'hide_empty' => '0');
  $categories = get_categories($args);
  if(!empty($categories)) {
    $last_category_nr = count($categories) - 1;
    $last_in_first_column = ceil($last_category_nr / 2);
?>
    <div class="col">
      <ul class="cat-list">
        <?php
        for ($i = 0; $i <= $last_in_first_column; $i++) {
          $category = $categories[$i];
          $color = get_field('color', $category);
          $link = esc_url( get_category_link( $category->term_id ) );
          $name = $category->name;
        ?>
        <li style="background-color: <?php echo $color; ?>">
          <a href="<?php echo $link; ?>">
            <?php echo $name; ?>
          </a>
        </li>
        <?php
        }
        ?>
      </ul>
    </div>
    <div class="col">
      <ul class="cat-list">
        <?php
        for ($i = $last_in_first_column + 1; $i <= $last_category_nr; $i++) {
          $category = $categories[$i];
          $color = get_field('color', $category);
          $link = esc_url( get_category_link( $category->term_id ) );
          $name = $category->name;
        ?>
        <li style="background-color: <?php echo $color; ?>">
          <a href="<?php echo $link; ?>">
            <?php echo $name; ?>
          </a>
        </li>
        <?php
        }
        ?>
      </ul>
    </div>
  }
?>
</code>```

Body:
I’m trying to get a list of categories into two columns. Each category has a custom field ("color") created with ACF. So far so good, i can get the list in a single column with this code:

<?php
          $args = array( 'hide_empty' => '0');
          $categories = get_categories($args);
          if($categories){
            echo '

';
            foreach($categories as $category) {
              $color = get_field('color', 'category_'.$category->term_id);
              echo '
';
              echo 'term_id ) );
              echo '">';
              echo $category->name;
              echo '';
              echo '
';
            }
            echo '

';
          }
          ?>

Now i’m trying to get the list using wp_list_categories (tip: https://wpsquare.com/display-wordpress-categories-two-columns/). This works as a solution for the two columns issue, but with this method i can’t retrieve the value from the category custom field.

Thanks in advance.

Body:
$categories is an array. One of the great things you can do with an array is... look how many items you have in them, and iterate over them using a simple for-loop.

<?php
  $args = array( 'hide_empty' => '0');
  $categories = get_categories($args);
  if(!empty($categories)) {
    $last_category_nr = count($categories) - 1;
    $last_in_first_column = ceil($last_category_nr / 2);
?>
    <div class="col">
      <ul class="cat-list">
        <?php
        for ($i = 0; $i <= $last_in_first_column; $i++) {
          $category = $categories[$i];
          $color = get_field('color', $category);
          $link = esc_url( get_category_link( $category->term_id ) );
          $name = $category->name;
        ?>
        <li style="background-color: <?php echo $color; ?>">
          <a href="<?php echo $link; ?>">
            <?php echo $name; ?>
          </a>
        </li>
        <?php
        }
        ?>
      </ul>
    </div>
    <div class="col">
      <ul class="cat-list">
        <?php
        for ($i = $last_in_first_column + 1; $i <= $last_category_nr; $i++) {
          $category = $categories[$i];
          $color = get_field('color', $category);
          $link = esc_url( get_category_link( $category->term_id ) );
          $name = $category->name;
        ?>
        <li style="background-color: <?php echo $color; ?>">
          <a href="<?php echo $link; ?>">
            <?php echo $name; ?>
          </a>
        </li>
        <?php
        }
        ?>
      </ul>
    </div>
  }
?>


问:
How do I use t-distribution with glm() in R?
I've established pretty conclusively that the residuals I'm generating with a standard lm() regression can be reasonably modeled by a t-distribution with 6-ish degrees of freedom.  I'd like to use glm() with that error model, but I'm not seeing that the t fits into one of the families.  Any recommendations on either alternatives to glm() that play well with t, or a family that would serve reasonably well as a substitute for (or superset of) t?

答:
Package heavy can perform t-student regression models. Here is an example from the documentation:

```<code>library(heavy)
data(ereturns)
fit <- heavyLm(m.marietta ~ CRSP, data = ereturns, family = Student(df = 6))
summary(fit)
# Linear model under heavy-tailed distributions
# Data: ereturns; Family: Student(df = 2.83727)
#
# Residuals:
#  Min        1Q    Median        3Q       Max
# -0.142237 -0.036156  0.003433  0.041310  0.546533
#
# Coefficients:
#  Estimate Std.Error Z value p-value
# (Intercept) -0.0072   0.0082   -0.8876  0.3748
# CRSP         1.2637   0.1902    6.6459  0.0000
#
# Degrees of freedom: 60 total; 58 residual
# Scale estimate: 0.002520795
# Log-likelihood: 71.81294 on 3 degrees of freedom
</code>```

Body:
Package heavy can perform t-student regression models. Here is an example from the documentation:

library(heavy)
data(ereturns)
fit <- heavyLm(m.marietta ~ CRSP, data = ereturns, family = Student(df = 6))
summary(fit)
# Linear model under heavy-tailed distributions
# Data: ereturns; Family: Student(df = 2.83727)
#
# Residuals:
#  Min        1Q    Median        3Q       Max
# -0.142237 -0.036156  0.003433  0.041310  0.546533
#
# Coefficients:
#  Estimate Std.Error Z value p-value
# (Intercept) -0.0072   0.0082   -0.8876  0.3748
# CRSP         1.2637   0.1902    6.6459  0.0000
#
# Degrees of freedom: 60 total; 58 residual
# Scale estimate: 0.002520795
# Log-likelihood: 71.81294 on 3 degrees of freedom


问:
How to trace or to check history of redirected URLs with python only urllib library
When you go to https://httpbin.org/redirect/6 after 6 redirection, you will lead to https://httpbin.org/get. I want to check what URLs are in between - only using python urllib.request.

```<code>import urllib.request

def openurl(url):

    headers = {}

    req = urllib.request.Request(url, headers=headers)
    httpResponse = urllib.request.urlopen(req)
    code = httpResponse.getcode()

    httpHeader = httpResponse.info()
    httpBody = httpResponse.read().decode()

    return httpHeader, httpBody, code

url = 'https://httpbin.org/redirect/6'
h, b, c = openurl(url)
print(h)
print(b)
print('http Response Code:', c)
</code>```

Is there any way to tweak the behavior of urlopen inorder to produce a list of URLs in between?

P.S. I cannot vote your answer as my reputation is below 15 otherwise unless I obtain 4 more points.

答:
Agree with georgexsh,
But you can also modify the HTTPRedirectHandler as below which is shorter:

```
class MyHTTPRedirectHandler(urllib.request.HTTPRedirectHandler):
    pass
```

Body:
When you go to https://httpbin.org/redirect/6 after 6 redirection, you will lead to https://httpbin.org/get. I want to check what URLs are in between - only using python urllib.request.

import urllib.request

def openurl(url):

    headers = {}

    req = urllib.request.Request(url, headers=headers)
    httpResponse = urllib.request.urlopen(req)
    code = httpResponse.getcode()

    httpHeader = httpResponse.info()
    httpBody = httpResponse.read().decode()

    return httpHeader, httpBody, code

url = 'https://httpbin.org/redirect/6'
h, b, c = openurl(url)
print(h)
print(b)
print('http Response Code:', c)

Is there any way to tweak the behavior of urlopen inorder to produce a list of URLs in between?

P.S. I cannot vote your answer as my reputation is below 15 otherwise unless I obtain 4 more points.

Body:
Agree with georgexsh,
But you can also modify the HTTPRedirectHandler as below which is shorter:

class MyHTTPRedirectHandler(urllib.request.HTTPRedirectHandler):
    pass


问:
Get monthly profit in webpage
I need some help getting the monthly profit as this image below:

My database table is named orders and has the following fields id, totalprice, date, status.

My date is saved as datetime eg: 2016-11-08 20:10:12
The calculation must be made monthly as the picture and only for orders with status equal to DELIVERED.

At the moment my code is only showing the last month and it's not even close to what I want to see, here is my code at the moment...

```<code><table class="table table-bordered">
  <thead>
    <tr><th>Status</th> <th>Total Price</th> <th>Time</th></tr>
  </thead>
  <tbody>
  <?php
        $cons_no="DELIVERED";
  $result = mysqli_query($conn, "SELECT SUM(totalprice) AS value_sum FROM orders WHERE status = '$cons_no' AND date BETWEEN (CURRENT_DATE() - INTERVAL 2 MONTH) AND CURRENT_DATE()");
        $row = mysqli_fetch_assoc($result);
        $sum = $row['value_sum'];
        //$query2 = "SELECT * FROM orders WHERE status = '$cons_no' AND YEAR(date) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH) AND MONTH(date) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)";
        $query2 = "SELECT * FROM orders WHERE status = '$cons_no' AND date BETWEEN (CURRENT_DATE() - INTERVAL 2 MONTH) AND CURRENT_DATE()";
        $results2 = $conn->query($query2);
        if($results2){
            $currentDate = false;
            while($row2 = $results2->fetch_assoc()) {
    ?>
    <tr>
        <td><?php echo $row2['status']; ?></td>
        <td><?php echo $row2['totalprice']; ?></td>
        <td><?php echo $row2['date']; ?></td>
    </tr>
    <?php
          }

        }
    ?>

        <td><?php echo "$".number_format($sum); ?></td>
    </tbody>
</code>```

It would be great if someone can help me reach the image result, I have tried some stuff that I found here in StackOverflow but nothing helped me reaching to what I need.

答:
This query would give you the sum of all orders for a year,month. Use it in your code to convert it into text.</p>

```<code>SELECT SUM(totalprice),* FROM [orders] GROUP BY YEAR(OrderDate),MONTH(OrderDate);
</code>```

Title: Get monthly profit in webpage

Body:
I need some help getting the monthly profit as this image below:

My database table is named orders and has the following fields id, totalprice, date, status.

My date is saved as datetime eg: 2016-11-08 20:10:12
The calculation must be made monthly as the picture and only for orders with status equal to DELIVERED.

At the moment my code is only showing the last month and it's not even close to what I want to see, here is my code at the moment...

Status	 Total Price	 Time

  <?php
        $cons_no="DELIVERED";
  $result = mysqli_query($conn, "SELECT SUM(totalprice) AS value_sum FROM orders WHERE status = '$cons_no' AND date BETWEEN (CURRENT_DATE() - INTERVAL 2 MONTH) AND CURRENT_DATE()");
        $row = mysqli_fetch_assoc($result);
        $sum = $row['value_sum'];
        //$query2 = "SELECT * FROM orders WHERE status = '$cons_no' AND YEAR(date) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH) AND MONTH(date) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)";
        $query2 = "SELECT * FROM orders WHERE status = '$cons_no' AND date BETWEEN (CURRENT_DATE() - INTERVAL 2 MONTH) AND CURRENT_DATE()";
        $results2 = $conn->query($query2);
        if($results2){
            $currentDate = false;
            while($row2 = $results2->fetch_assoc()) {
    ?>

        <?php echo $row2['status']; ?>
        <?php echo $row2['totalprice']; ?>
        <?php echo $row2['date']; ?>

    <?php
          }

        }
    ?>

        <?php echo "$".number_format($sum); ?>

It would be great if someone can help me reach the image result, I have tried some stuff that I found here in StackOverflow but nothing helped me reaching to what I need.

Body:
This query would give you the sum of all orders for a year,month. Use it in your code to convert it into text.

SELECT SUM(totalprice),* FROM [orders] GROUP BY YEAR(OrderDate),MONTH(OrderDate);


问:
Problem or bug in xticklabel_rotate while drawing heatmap and rotating xtick labels in Matlab
I have been drawing heatmaps with labels in Matlab, mainly using the functions imagesc to draw the heatmap and xticklabel_rotate to rotate the xtick labels.
(please see here for xticklabel_rotate).
It usually works well. But today I met some problem which appeared to be caused by xticklabel_rotate (or maybe the Matlab text handle used by xticklabel_rotate?)

To illustrate the problem, in the following I print my code and the results generated from the code (basically, what it does is to randomly generate a normally distributed data matrix, draw a heatmap for the data using imagesc, draw its labels on top and right of the axis, and then rotate xticklabels):

```<code>function debug_xticklabelRotate(numX, numY, axisFontsize)
    data = randn(numY, numX);
    imagesc(data);
    colormap(jet);
    box on
    set(gca, 'ticklength', [0,0]);
    set(gca, 'xminortick', 'off', 'yminortick', 'off');
    set(gca, 'XAxisLocation', 'top');
    set(gca, 'YAxisLocation', 'right');
    set(gca,'FontSize', axisFontsize);
    axis image
    set(gca, 'Xtick', 1 : numX);
    htext = xticklabel_rotate([],90, [], 'fontsize', axisFontsize);
    set(gca, 'YTick', 1 : numY);
end
</code>```

Problem 1: I called the above function with parameters as

```<code>debug_xticklabelRotate(40, 100, .5);
</code>```

the output image is shown below (to save space here, I cut the image and only show the top few rows):

Please notice that the bug is that, as the result of calling xticklabel_rotate, neither the right side of the figure box nor the yticklabels are drawn.

Problem 2: When I call the above function with parameters as

```<code>debug_xticklabelRotate(40, 200, .5);  % only numY is changed from 100 to 200
</code>```

the output image is shown below (again to save space here, I cut the image and only show the top few rows):

http://i55.tinypic.com/317grdd.png

Compared to the call with numY=100, in this figure both the data image and the labels are shown. However, please notice two problems here. First, the fontsize of xticklabel is not the same as that of yticklabel (axisFontsize). Second, the xtick labels are not aligned well with the columns (xticks): some labels are closer and some are further away.

Please note if I remove the function call of xticklable_rotate in my function debug_xticklabelRotate, all these mentioned problems are gone (except that now the xticklabel are not rotated).

I wish my problem is stated clear above. Any suggestion on solving the problem will be highly appreciated. Thank you very much.

答:
If you comment out the line:

```<code>set(gca, 'YAxisLocation', 'right')
</code>```

then it should work as expected. It seems that the XTICKLABEL_ROTATE function does not support right y-labels. You should contact the original author and let him know of the possible bug...

ContentLicense: CC BY-SA 4.0

Body:
I have been drawing heatmaps with labels in Matlab, mainly using the functions imagesc to draw the heatmap and xticklabel_rotate to rotate the xtick labels.
(please see here for xticklabel_rotate).
It usually works well. But today I met some problem which appeared to be caused by xticklabel_rotate (or maybe the Matlab text handle used by xticklabel_rotate?)

To illustrate the problem, in the following I print my code and the results generated from the code (basically, what it does is to randomly generate a normally distributed data matrix, draw a heatmap for the data using imagesc, draw its labels on top and right of the axis, and then rotate xticklabels):

function debug_xticklabelRotate(numX, numY, axisFontsize)
    data = randn(numY, numX);
    imagesc(data);
    colormap(jet);
    box on
    set(gca, 'ticklength', [0,0]);
    set(gca, 'xminortick', 'off', 'yminortick', 'off');
    set(gca, 'XAxisLocation', 'top');
    set(gca, 'YAxisLocation', 'right');
    set(gca,'FontSize', axisFontsize);
    axis image
    set(gca, 'Xtick', 1 : numX);
    htext = xticklabel_rotate([],90, [], 'fontsize', axisFontsize);
    set(gca, 'YTick', 1 : numY);
end

Problem 1: I called the above function with parameters as

debug_xticklabelRotate(40, 100, .5);

the output image is shown below (to save space here, I cut the image and only show the top few rows):

Please notice that the bug is that, as the result of calling xticklabel_rotate, neither the right side of the figure box nor the yticklabels are drawn.

Problem 2: When I call the above function with parameters as

debug_xticklabelRotate(40, 200, .5);  % only numY is changed from 100 to 200

the output image is shown below (again to save space here, I cut the image and only show the top few rows):

http://i55.tinypic.com/317grdd.png

Compared to the call with numY=100, in this figure both the data image and the labels are shown. However, please notice two problems here. First, the fontsize of xticklabel is not the same as that of yticklabel (axisFontsize). Second, the xtick labels are not aligned well with the columns (xticks): some labels are closer and some are further away.

Please note if I remove the function call of xticklable_rotate in my function debug_xticklabelRotate, all these mentioned problems are gone (except that now the xticklabel are not rotated).

I wish my problem is stated clear above. Any suggestion on solving the problem will be highly appreciated. Thank you very much.

Body:
If you comment out the line:

set(gca, 'YAxisLocation', 'right')

then it should work as expected. It seems that the XTICKLABEL_ROTATE function does not support right y-labels. You should contact the original author and let him know of the possible bug...

ContentLicense: CC BY-SA 2.5


问:
What is the prototype of the String constructor function (String.__proto__)?
```<code>var mString = new String('A');

console.log(typeof mString); // object

console.log(mString instanceof String); // true

console.log(mString instanceof Object); // true

console.log(mString.__proto__ === String.prototype); // true

console.log(mString.__proto__.__proto__ === Object.prototype); // true
</code>```

Now, why

```<code>console.log(String.__proto__.__proto__ === Object.prototype); // true
</code>```

and not

```<code>console.log(String.__proto__ === Object.prototype); // false
</code>```

when walking up the prototype chain?

What is between String and Object prototypes?

答:
```<code>Function.prototype === String.__proto__ //true
</code>```

It's a function's prototype, because String is a constructor function.

Body:
var mString = new String('A');

console.log(typeof mString); // object

console.log(mString instanceof String); // true

console.log(mString instanceof Object); // true

console.log(mString.__proto__ === String.prototype); // true

console.log(mString.__proto__.__proto__ === Object.prototype); // true

Now, why

console.log(String.__proto__.__proto__ === Object.prototype); // true

and not

console.log(String.__proto__ === Object.prototype); // false

when walking up the prototype chain?

What is between String and Object prototypes?

Body:
Function.prototype === String.__proto__ //true

It's a function's prototype, because String is a constructor function.


问:
Protractor hard to click popup/dropdown
Hey guys I am trying to click on an element called practitioner access on my company's web site and I have tried looking up documentation on stack over flow and have not figured out how to do this exactly I need help. What I am trying to do is click on the practitioner access popup/drop down and I have not been able to find the code to do it. Please see epic at the bottom:

This is how far I have gotten so far but protractor cant find the element

```<code>var pracaccess = element(by.xpath("//contains(@onclick, 'Practitioner Access')"))
pracaccess.click();
browser.sleep(10000);
</code>```

I have tried to use these site to try and help myself but I can't piece it together. Any help would be appreciated. I am new to xpath as well.

new info to possibly help:
Here is a more expanded view

Also this is what it looks like in vb-script but its basically the same any suggestions?

```<code>Browser("ADP_2").Page("ADP_3").Link("html tag:=A","innertext:=Practitioner Access").WaitProperty "visible",True,30000
        Browser("ADP_2").Page("ADP_3").Link("html tag:=A","innertext:=Practitioner Access").Object.Click
</code>```

答:
This XPath expression would look for a tag with the contains tag name, which does not exist. Instead, you've actually meant:

```<code>//a[contains(@onclick, 'Practitioner Access')]
</code>```

Or, there is a nicer way to locate an a element by the link text:

```<code>element(by.linkText("Practitioner Access"))
</code>```

Title: Protractor hard to click popup/dropdown

Body:
Hey guys I am trying to click on an element called practitioner access on my company's web site and I have tried looking up documentation on stack over flow and have not figured out how to do this exactly I need help. What I am trying to do is click on the practitioner access popup/drop down and I have not been able to find the code to do it. Please see epic at the bottom:

This is how far I have gotten so far but protractor cant find the element

var pracaccess = element(by.xpath("//contains(@onclick, 'Practitioner Access')"))
pracaccess.click();
browser.sleep(10000);

I have tried to use these site to try and help myself but I can't piece it together. Any help would be appreciated. I am new to xpath as well.

new info to possibly help:
Here is a more expanded view

Also this is what it looks like in vb-script but its basically the same any suggestions?

Browser("ADP_2").Page("ADP_3").Link("html tag:=A","innertext:=Practitioner Access").WaitProperty "visible",True,30000
        Browser("ADP_2").Page("ADP_3").Link("html tag:=A","innertext:=Practitioner Access").Object.Click

Body:
This XPath expression would look for a tag with the contains tag name, which does not exist. Instead, you've actually meant:

//a[contains(@onclick, 'Practitioner Access')]

Or, there is a nicer way to locate an a element by the link text:

element(by.linkText("Practitioner Access"))


问:
Text input with IF statements
I am creating a very simple story based "game" where there is a question with choices (not radio buttons etc) and the user has to type in the choices that's been given to them. I am not very good with JavaScript as you will see...

```<code><!DOCTYPE HTML>
<html>

<head>
<script type="text/javascript" src="gamescript.js"></script>
</head>

<body>

<p id ="door"> Which door do you wish to enter? Door 1 or Door 2? </p>

<input id="myInput" type="text">

<button onclick="myFunction()">Enter</button>

<script>
function myFunction(){
    var door = document.getElementById("myInput").value;
    if (door == "Door 1", "door 1"){
        document.getElementById("door").innerHTML = "You have entered" + door;
    }else if (door == "Door 2", "door 2"){
        document.getElementById("door").innerHTML = "You have entered" + door;
    }else{
        document.getElementById("door").innerHTML = "You must enter a door!"
    }
}

</script>

</body>
</html>
</code>```

I am not getting any errors but when I type in something random/or leave blank, it's meant to say "Choose a door" but it's displaying anything i type into the text box. This code might be wrong, i'm guessing it most likely is..I didn't want to come online for help but have no one else to ask. All help is appreciated. Thank you.

答:
The comma operator , evaluates each of its operands (from left to right) and returns the value of the last operand. Your issue is that the first if check is always returning true.

```<code>function myFunction(){
    var doorVal = document.getElementById("myInput").value;
    var door = document.getElementById("door");
    // this could just as well be an object
    var acceptedResponses = ["Door1", "door1", "Door2", "door2"];
    if (acceptedResponses.indexOf(doorVal) !== -1) {
      door.innerHTML = "You have entered " + door;
    } else {
      door.innerHTML = "You must enter a door!";
    }
}
</code>```

Title: Text input with IF statements

Body:
I am creating a very simple story based "game" where there is a question with choices (not radio buttons etc) and the user has to type in the choices that's been given to them. I am not very good with JavaScript as you will see...

<!DOCTYPE HTML>

 Which door do you wish to enter? Door 1 or Door 2?

<input id="myInput" type="text">

<button onclick="myFunction()">Enter</button>

I am not getting any errors but when I type in something random/or leave blank, it's meant to say "Choose a door" but it's displaying anything i type into the text box. This code might be wrong, i'm guessing it most likely is..I didn't want to come online for help but have no one else to ask. All help is appreciated. Thank you.

Body:
The comma operator , evaluates each of its operands (from left to right) and returns the value of the last operand. Your issue is that the first if check is always returning true.

function myFunction(){
    var doorVal = document.getElementById("myInput").value;
    var door = document.getElementById("door");
    // this could just as well be an object
    var acceptedResponses = ["Door1", "door1", "Door2", "door2"];
    if (acceptedResponses.indexOf(doorVal) !== -1) {
      door.innerHTML = "You have entered " + door;
    } else {
      door.innerHTML = "You must enter a door!";
    }
}


问:
Opening show page in a modal with updating url in address bar as in instagram example using Ruby on Rails 5
I'm trying to achieve the attached behaviour in my Ruby on Rails 5 project.

Clicking post in index opens modal instead of linking to show page, but also updates browser's address bar with the post url.

For modal I'm using jquery-modal http://jquerymodal.com ,
not using Bootstrap

My sample codes are below ↓

Currently I have code below. The modal works fine but it doesn't update the url.

index.html.erb

```<code><%= link_to image_tag(post.image_url.to_s), post_path(post), remote: true %>
</code>```

_post_modal.html.erb

```<code><div id="post-modal" class="modal fade" role="dialog">

  <div class="modal-dialog modal-lg">
    <div class="modal-content flex flex-wrap items-start w-100 postmodal">

      <div class="w-75-l">
        <a href="#close" rel="modal:close" title="Close"><%= image_tag @post.image_url.to_s %></a>
      </div>

      <div class="w-25-l">

        <a href="#close" rel="modal:close" title="Close" class="btn-closemodal">X</a>

        <h1><%= @post.title %></h1>

      </div>
    </div>
  </div>
</div>
</code>```

post_controller.rb

```<code>  def show

    @post = Post.friendly.find(params[:id])

    respond_to do |format|
      format.js
    end
  end
</code>```

show.js.erb

```<code>$('#post-content').html("<%= j render 'post_modal', post: @post %>");
$('#post-modal').modal('show');
</code>```

and I'm getting this error at show page

答:
Adding this line to show.js.erb solved the issue

```<code>history.replaceState({}, "<%= @post.title %>", "<%= request.original_url %>");
</code>```

or if you don't want to change url when modal opened. Adding this line to show.js.erb

```<code>history.pushState({}, "Your Title", "<%= your_current_url %>");
</code>```

Body:
I'm trying to achieve the attached behaviour in my Ruby on Rails 5 project.

Clicking post in index opens modal instead of linking to show page, but also updates browser's address bar with the post url.

For modal I'm using jquery-modal http://jquerymodal.com ,
not using Bootstrap

My sample codes are below ↓

Currently I have code below. The modal works fine but it doesn't update the url.

index.html.erb

<%= link_to image_tag(post.image_url.to_s), post_path(post), remote: true %>

_post_modal.html.erb

        <%= image_tag @post.image_url.to_s %>

        X

<%= @post.title %>

post_controller.rb

  def show

    @post = Post.friendly.find(params[:id])

    respond_to do |format|
      format.js
    end
  end

show.js.erb

$('#post-content').html("<%= j render 'post_modal', post: @post %>");
$('#post-modal').modal('show');

and I'm getting this error at show page

Body:
Adding this line to show.js.erb solved the issue

history.replaceState({}, "<%= @post.title %>", "<%= request.original_url %>");

or if you don't want to change url when modal opened. Adding this line to show.js.erb

history.pushState({}, "Your Title", "<%= your_current_url %>");


问:
Twilio sending texts on android problems
am creating an android app for school which will need to send text messages. I have had twilio recommended by several people so I decided to go with it. Following this tutorial: https://www.twilio.com/blog/2016/05/how-to-send-an-sms-from-android.html , with my own android app and the one including I am getting a 404 when post is called (seen through ngrok). I am at a complete loss, still new to android. The backend gives the following message through intellij:
8810 [qtp649044888-15] INFO spark.http.matching.MatcherFilter - The requested route [/] has not been mapped in Spark for Accept: [null]

Account IDs, addresses, phone numbers, etc. replaced with x's
Backend:

```<code>//Heroku assigns different port each time, hence reading it from process.
        ProcessBuilder process = new ProcessBuilder();
        Integer port;
        if (process.environment().get("PORT") != null) {
            port = Integer.parseInt(process.environment().get("PORT"));
        } else {
            port = 4567;
        }
        Spark.port(port);

        get("/", (req, res) -> "Hello, World");

        TwilioRestClient client = new TwilioRestClient.Builder(System.getenv("ACxxxxxxx72279fb226f0dd162c869ce1e"), System.getenv("xxxxxxxc324a89155b93b5af26393297")).build();

        post("/sms", (req, res) -> {
            String body = req.queryParams("Body");
            String to = req.queryParams("To");
            String from = System.getenv("216450xxxx");

            Message message = new MessageCreator(
                    new PhoneNumber(to),
                    new PhoneNumber(from),
                    body).create(client);

            return message.getSid();
        });
</code>```

App- post method

```<code>Call post(String url, Callback callback) throws IOException {
        RequestBody formBody = new FormBody.Builder().add("To", "609420xxxx").add("Body", "TEST").build();
        Request request = new Request.Builder().url(url).post(formBody).build();
        Call response = mClient.newCall(request);
        response.enqueue(callback);
        Log.d("CALL: ", response.toString()+ "     " + callback.toString());
        return response;
    }
</code>```

App post method on button:

```<code>emailButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    post("http://xxxxxxxx.ngrok.io", new  Callback(){
                        @Override
                        public void onFailure(Call call, IOException e) {
                            e.printStackTrace();
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getApplicationContext(),"SMS Sent!",Toast.LENGTH_SHORT).show();
                                }
                            });
                        }

                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });
</code>```

This should be sending a text to my number (verified on twilio account), but I get nothing. The toast does appear saying the text has been sent.

答:
Looking at the spark source code for MatcherFilter the only reference to the error you are getting is thrown when the body is not set

```<code>if (body.notSet()) {
    LOG.info("The requested route [{}] has not been mapped in Spark for {}: [{}]",
             uri, ACCEPT_TYPE_REQUEST_MIME_HEADER, acceptType);
</code>```

Looking at the Twilio tutorial you linked to (assuming your supplied code is exactly what you are using) it seems that you have altered the code to hard code your variables into classes and methods.

I don't know much about coding for Android, but I can tell you that this line in the tutorial references an environment variable within the project containing the Twilio account SID

```<code>(System.getenv("TWILIO_ACCOUNT_SID")
</code>```

Now here's your version:

```<code>(System.getenv("ACxxxxxxx72279fb226f0dd162c869ce1e")
</code>```

An environment variable is a variable which is set once, usually in a file containing all the other environment variables and is specific to the user or system the code is running on. These allow developers to easily change user or syystem specific variable values even if they have referenced these variables many times within a project.

You are attempting to reference an environment variable, but then supplying a value you wish to use. It doesn't work like that.

Here's your app post on button method:

```<code>post("http://xxxxxxxx.ngrok.io", new  Callback(){
</code>```

Here's Twilio's:

```<code>post(mContext.getString("YOUR_NGROK_URL/sms"), new  Callback(){
</code>```

Your hardcoded url drops the reference to the mContext variable, I don't know if that matters, but the other thing you have overlooked is you need to add /sms to the end of your URL.

My recommendation, seeing as you are just starting out with Android would be to follow tutorials to the letter for now. It might seem like you are saving time cutting some corners and changing a few bits here and there, but then when it doesn't work you don't have the experience to understand what is wrong.

Cutting corners, hard coding variables etc is a bad habit to get in to anyway. We've all done it, then we've all regretted it later. Learn properly, code properly, add comments explaining your code and you'll save yourself countless hours of future frustration.

Body:
am creating an android app for school which will need to send text messages. I have had twilio recommended by several people so I decided to go with it. Following this tutorial: https://www.twilio.com/blog/2016/05/how-to-send-an-sms-from-android.html , with my own android app and the one including I am getting a 404 when post is called (seen through ngrok). I am at a complete loss, still new to android. The backend gives the following message through intellij:
8810 [qtp649044888-15] INFO spark.http.matching.MatcherFilter - The requested route [/] has not been mapped in Spark for Accept: [null]

Account IDs, addresses, phone numbers, etc. replaced with x's
Backend:

//Heroku assigns different port each time, hence reading it from process.
        ProcessBuilder process = new ProcessBuilder();
        Integer port;
        if (process.environment().get("PORT") != null) {
            port = Integer.parseInt(process.environment().get("PORT"));
        } else {
            port = 4567;
        }
        Spark.port(port);

        get("/", (req, res) -> "Hello, World");

        TwilioRestClient client = new TwilioRestClient.Builder(System.getenv("ACxxxxxxx72279fb226f0dd162c869ce1e"), System.getenv("xxxxxxxc324a89155b93b5af26393297")).build();

        post("/sms", (req, res) -> {
            String body = req.queryParams("Body");
            String to = req.queryParams("To");
            String from = System.getenv("216450xxxx");

            Message message = new MessageCreator(
                    new PhoneNumber(to),
                    new PhoneNumber(from),
                    body).create(client);

            return message.getSid();
        });

App- post method

Call post(String url, Callback callback) throws IOException {
        RequestBody formBody = new FormBody.Builder().add("To", "609420xxxx").add("Body", "TEST").build();
        Request request = new Request.Builder().url(url).post(formBody).build();
        Call response = mClient.newCall(request);
        response.enqueue(callback);
        Log.d("CALL: ", response.toString()+ "     " + callback.toString());
        return response;
    }

App post method on button:

emailButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    post("http://xxxxxxxx.ngrok.io", new  Callback(){
                        @Override
                        public void onFailure(Call call, IOException e) {
                            e.printStackTrace();
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getApplicationContext(),"SMS Sent!",Toast.LENGTH_SHORT).show();
                                }
                            });
                        }

                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });

This should be sending a text to my number (verified on twilio account), but I get nothing. The toast does appear saying the text has been sent.

Body:
Looking at the spark source code for MatcherFilter the only reference to the error you are getting is thrown when the body is not set

if (body.notSet()) {
    LOG.info("The requested route [{}] has not been mapped in Spark for {}: [{}]",
             uri, ACCEPT_TYPE_REQUEST_MIME_HEADER, acceptType);

Looking at the Twilio tutorial you linked to (assuming your supplied code is exactly what you are using) it seems that you have altered the code to hard code your variables into classes and methods.

I don't know much about coding for Android, but I can tell you that this line in the tutorial references an environment variable within the project containing the Twilio account SID

(System.getenv("TWILIO_ACCOUNT_SID")

Now here's your version:

(System.getenv("ACxxxxxxx72279fb226f0dd162c869ce1e")

An environment variable is a variable which is set once, usually in a file containing all the other environment variables and is specific to the user or system the code is running on. These allow developers to easily change user or syystem specific variable values even if they have referenced these variables many times within a project.

You are attempting to reference an environment variable, but then supplying a value you wish to use. It doesn't work like that.

Here's your app post on button method:

post("http://xxxxxxxx.ngrok.io", new  Callback(){

Here's Twilio's:

post(mContext.getString("YOUR_NGROK_URL/sms"), new  Callback(){

Your hardcoded url drops the reference to the mContext variable, I don't know if that matters, but the other thing you have overlooked is you need to add /sms to the end of your URL.

My recommendation, seeing as you are just starting out with Android would be to follow tutorials to the letter for now. It might seem like you are saving time cutting some corners and changing a few bits here and there, but then when it doesn't work you don't have the experience to understand what is wrong.

Cutting corners, hard coding variables etc is a bad habit to get in to anyway. We've all done it, then we've all regretted it later. Learn properly, code properly, add comments explaining your code and you'll save yourself countless hours of future frustration.


问:
Authenticating Google API with a service account with Java API
I am attempting to use oauth API to authenticate a google service account through the Java API. I am hoping to use it to access Google Bigquery. I get an "invalid grant" returned from my API requests.

Here is the code, which is a copy of a basic authentication example (which wasn't for Bigquery.. but another Google API):

```<code>  /** Global instance of the HTTP transport. */
  private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  /** Global instance of the JSON factory. */
  private static final JsonFactory JSON_FACTORY = new JacksonFactory();

  private static Bigquery bigquery;

public ServiceAccountExample() {

      try {
          try {

            GoogleCredential credential = new  GoogleCredential.Builder().setTransport(HTTP_TRANSPORT)
                .setJsonFactory(JSON_FACTORY)
                .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
                .setServiceAccountScopes(BigqueryScopes.BIGQUERY)
                .setServiceAccountPrivateKeyFromP12File(new File("GoogleBigQuery-privatekey.p12"))
                //.setRefreshListeners(refreshListeners)
                //.setServiceAccountUser("email.com")
                .build();

            credential.refreshToken();

            bigquery = new Bigquery.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
                        //.setApplicationName("GoogleBigQuery/1.0")
                        .build();

            listDatasets(bigquery, "publicdata");

            return;
          } catch (IOException e) {
            System.err.println(e.getMessage());
          }
        } catch (Throwable t) {
          t.printStackTrace();
        }

}
</code>```

SERVICE_ACCOUNT_EMAIL is the email address of the form: XXXXXXX@developer.gserviceaccount.com

If I remove the credential.refreshToken() line, it fails in the listsDatasets on the first call to Bigquery... Otherwise it fails on credential.refreshToken().. with the same error.

Does BigQuery not accept Service Account authentication?

I believe I have done everything correctly through the API Console. I have:

Turned access to the Big Query API on.

Created a service account under the "API Access" tab.

Downloaded my private key (which is referenced from the code above).

Given my service account user "can edit" access under the "Teams" tab.

Enabled Billing.

Have I missed anything? Is there anything else I need to do?

Thanks..

答:
To authenticate with a service account key with the Google Cloud BigQuery client libraries
 (Maven package) you can use Application Default Credentials.

First set the GOOGLE_APPLICATION_CREDENTIALS environment variable to the full path to your service account JSON key file. In your code, create the BigQuery service object using the default instance.

```<code>import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryOptions;
...
BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
</code>```

This is the recommended way, as it makes it possible to use the same code in multiple environments, such as on Google Compute Engine, where the service account is built-in rather than using a key file.

Alternatively, you may wish to construct a credentials object manually from a service account key file and use that create the BigQuery service object.

```<code>import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.ServiceAccountCredentials;
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryOptions;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

...

// TODO: update to your key path.
File credentialsPath = new File("service_account.json");

GoogleCredentials credentials;
try (FileInputStream serviceAccountStream = new FileInputStream(credentialsPath)) {
  credentials = ServiceAccountCredentials.fromStream(serviceAccountStream);
}

// Instantiate a client.
BigQuery bigquery =
    BigQueryOptions.newBuilder()
        .setCredentials(credentials)
        .build()
        .getService();
</code>```

Body:
I am attempting to use oauth API to authenticate a google service account through the Java API. I am hoping to use it to access Google Bigquery. I get an "invalid grant" returned from my API requests.

Here is the code, which is a copy of a basic authentication example (which wasn't for Bigquery.. but another Google API):

  /** Global instance of the HTTP transport. */
  private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  /** Global instance of the JSON factory. */
  private static final JsonFactory JSON_FACTORY = new JacksonFactory();

  private static Bigquery bigquery;

public ServiceAccountExample() {

      try {
          try {

            GoogleCredential credential = new  GoogleCredential.Builder().setTransport(HTTP_TRANSPORT)
                .setJsonFactory(JSON_FACTORY)
                .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
                .setServiceAccountScopes(BigqueryScopes.BIGQUERY)
                .setServiceAccountPrivateKeyFromP12File(new File("GoogleBigQuery-privatekey.p12"))
                //.setRefreshListeners(refreshListeners)
                //.setServiceAccountUser("email.com")
                .build();

            credential.refreshToken();

            bigquery = new Bigquery.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
                        //.setApplicationName("GoogleBigQuery/1.0")
                        .build();

            listDatasets(bigquery, "publicdata");

            return;
          } catch (IOException e) {
            System.err.println(e.getMessage());
          }
        } catch (Throwable t) {
          t.printStackTrace();
        }

}

SERVICE_ACCOUNT_EMAIL is the email address of the form: XXXXXXX@developer.gserviceaccount.com

If I remove the credential.refreshToken() line, it fails in the listsDatasets on the first call to Bigquery... Otherwise it fails on credential.refreshToken().. with the same error.

Does BigQuery not accept Service Account authentication?

I believe I have done everything correctly through the API Console. I have:

Turned access to the Big Query API on.

Created a service account under the "API Access" tab.

Downloaded my private key (which is referenced from the code above).

Given my service account user "can edit" access under the "Teams" tab.

Enabled Billing.

Have I missed anything? Is there anything else I need to do?

Thanks..

Body:
To authenticate with a service account key with the Google Cloud BigQuery client libraries
 (Maven package) you can use Application Default Credentials.

First set the GOOGLE_APPLICATION_CREDENTIALS environment variable to the full path to your service account JSON key file. In your code, create the BigQuery service object using the default instance.

import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryOptions;
...
BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();

This is the recommended way, as it makes it possible to use the same code in multiple environments, such as on Google Compute Engine, where the service account is built-in rather than using a key file.

Alternatively, you may wish to construct a credentials object manually from a service account key file and use that create the BigQuery service object.

import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.ServiceAccountCredentials;
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryOptions;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

...

// TODO: update to your key path.
File credentialsPath = new File("service_account.json");

GoogleCredentials credentials;
try (FileInputStream serviceAccountStream = new FileInputStream(credentialsPath)) {
  credentials = ServiceAccountCredentials.fromStream(serviceAccountStream);
}

// Instantiate a client.
BigQuery bigquery =
    BigQueryOptions.newBuilder()
        .setCredentials(credentials)
        .build()
        .getService();


问:
Remove a FileList item from a multiple "input:file"
I have this DOM:

```<code>var id = 0;

$('input:file#upload')[0].files[ id ]
</code>```

That get's the first file on the 0th index. File properties are listed and all works, but...

How do we remove items from the DOM's [object FileList] with JavaScript?

答:
Finally found a way!
I knew before that input.files would accept a FileList but the only way to get it was through a drag and drop event.

But now i know how to construct a own FileList!

This works in chrome (and maybe some other)

const dt = new DataTransfer()
dt.items.add(new File([], 'a.txt'))
input.files = dt.files

// This will remove the first item when selecting many files
input.onchange = () => {
  const dt = new DataTransfer()

  for (let file of input.files)
    if (file !== input.files[0])
      dt.items.add(file)

  input.onchange = null // remove event listener
  input.files = dt.files // this will trigger a change event
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="file" multiple id="input"></code>```

This works in Firefox

const cd = new ClipboardEvent("").clipboardData
cd.items.add(new File(['a'], 'a.txt'))
input.files = cd.files

// This will remove the fist item when selecting many files
input.onchange = () => {
  const dt = new DataTransfer()

  for (let file of input.files)
    if (file !== input.files[0])
      dt.items.add(file)

  input.onchange = null // remove event listener
  input.files = dt.files // this will trigger a change event
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="file" multiple id="input"></code>```

The thing is you need to loop over each file in the input, add those you still want to keep and assign the file.files with the new list of files.

Body:
I have this DOM:

var id = 0;

$('input:file#upload')[0].files[ id ]

That get's the first file on the 0th index. File properties are listed and all works, but...

How do we remove items from the DOM's [object FileList] with JavaScript?

Body:
Finally found a way!
I knew before that input.files would accept a FileList but the only way to get it was through a drag and drop event.

But now i know how to construct a own FileList!

This works in chrome (and maybe some other)

const dt = new DataTransfer()
dt.items.add(new File([], 'a.txt'))
input.files = dt.files

// This will remove the first item when selecting many files
input.onchange = () => {
  const dt = new DataTransfer()

  for (let file of input.files)
    if (file !== input.files[0])
      dt.items.add(file)

  input.onchange = null // remove event listener
  input.files = dt.files // this will trigger a change event
}

<input type="file" multiple id="input">

This works in Firefox

const cd = new ClipboardEvent("").clipboardData
cd.items.add(new File(['a'], 'a.txt'))
input.files = cd.files

// This will remove the fist item when selecting many files
input.onchange = () => {
  const dt = new DataTransfer()

  for (let file of input.files)
    if (file !== input.files[0])
      dt.items.add(file)

  input.onchange = null // remove event listener
  input.files = dt.files // this will trigger a change event
}

<input type="file" multiple id="input">

The thing is you need to loop over each file in the input, add those you still want to keep and assign the file.files with the new list of files.


问:
Django TemplateDoesNotExist admin/login.html
I am working with django 1.4. And this error appeared:

TemplateDoesNotExist at /admin/
admin/login.html

I tried to reinstall django, but i did not work... Please Help!

答: Assuming that you are trying to use the default Django admin, be sure that 'django.contrib.admin' is in the INSTALLED_APPS section of your settings.py file.


问:
Bootstrap modal with Vanilla Javascript
I have site navigation in Component A (Navigation).
I have a working bootstrap modal in component B (BootstrapModal).
Component A is referenced in index.html to display navigation.

What I'm trying to accomplished is a way to invoke modal window from Component B when a user clicks on a nav item containing “example” CSS class.

So will need conditional statement to invoke the modal when the CSS class is present.

Note that this is using bootstrap modal and am not able to add data-target="#myModal" to component A.

答:
Just use bootstrap's api on the click event of the item you want to target with an if statement based on the hasClass function in jQuery:

```<code>$('#myTarget').on('click', function(e) {
  if ('#myElement').hasClass('example') {
    $('#myModal').modal('show');
  }
});
</code>```

Note: I know you said "Vanilla javascript", but the fact that you are using Bootstrap seems to indicate that you are not using pure "Vanilla Javascript". Just that you need a programmatic way of opening the modal.

Title: Bootstrap modal with Vanilla Javascript

Body:
Just use bootstrap's api on the click event of the item you want to target with an if statement based on the hasClass function in jQuery:

$('#myTarget').on('click', function(e) {
  if ('#myElement').hasClass('example') {
    $('#myModal').modal('show');
  }
});

Note: I know you said "Vanilla javascript", but the fact that you are using Bootstrap seems to indicate that you are not using pure "Vanilla Javascript". Just that you need a programmatic way of opening the modal.


问:
Apache Beam initialize an PCollection to empty
I trying to convert a Spark ETL application into a Beam Application.

Inside the Spark App, I have an empty RDD.

sc.emptyRDD()

where sc is the SparkContext.

If I well understand, the PCollection is like Spark RDD. So, there is a way to create an empty PCollection?

答: Use Create.empty(). Since PCollections are typed and require coders, you'll also need to specify the coder or a type descriptor (even though the collection is empty), e.g. PCollection<String> emptyStrings = Create.of(StringUtf8Coder.of()).


问:
Webdriver Exception:Process unexpectedly closed with status: 1
I try to run a selenium program on a Linux machine.But I got the exceptions:

```<code>    Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/site-packages/selenium/webdriver/firefox/webdriver.py", line 154, in __init__
    keep_alive=True)
  File "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 151, in __init__
    self.start_session(desired_capabilities, browser_profile)
  File "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 240, in start_session
    response = self.execute(Command.NEW_SESSION, parameters)
     File "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 308, in execute
    self.error_handler.check_response(response)
  File "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 194, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: Process unexpectedly closed with status: 1
</code>```

How can I fix the exceptions? Thanks for helping.

答:
This error can come up when you are trying to run the browser in non-headless mode on a box that doesn't have a display (like an Ubuntu server).

You can check if that's the cause of your Process unexpectedly closed with status: 1 error by looking at the geckodriver.log file that is usually left in your working directory after you run your script, it should have a line like:

```<code>Error: GDK_BACKEND does not match available displays
</code>```

If you see that line in the geckodriver.log then you'll need to switch your script to run Firefox in headless mode:

```<code>from selenium import webdriver
from selenium.webdriver import FirefoxOptions

opts = FirefoxOptions()
opts.add_argument("--headless")
browser = webdriver.Firefox(options=opts)

browser.get('http://example.com')
</code>```

Body:
I try to run a selenium program on a Linux machine.But I got the exceptions:

    Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/site-packages/selenium/webdriver/firefox/webdriver.py", line 154, in __init__
    keep_alive=True)
  File "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 151, in __init__
    self.start_session(desired_capabilities, browser_profile)
  File "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 240, in start_session
    response = self.execute(Command.NEW_SESSION, parameters)
     File "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 308, in execute
    self.error_handler.check_response(response)
  File "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 194, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: Process unexpectedly closed with status: 1

How can I fix the exceptions? Thanks for helping.

Body:
This error can come up when you are trying to run the browser in non-headless mode on a box that doesn't have a display (like an Ubuntu server).

You can check if that's the cause of your Process unexpectedly closed with status: 1 error by looking at the geckodriver.log file that is usually left in your working directory after you run your script, it should have a line like:

Error: GDK_BACKEND does not match available displays

If you see that line in the geckodriver.log then you'll need to switch your script to run Firefox in headless mode:

from selenium import webdriver
from selenium.webdriver import FirefoxOptions

opts = FirefoxOptions()
opts.add_argument("--headless")
browser = webdriver.Firefox(options=opts)

browser.get('http://example.com')


问:
Pandas: Get values from column that appear more than X times
I have a data frame in pandas and would like to get all the values of a certain column that appear more than X times. I know this should be easy but somehow I am not getting anywhere with my current attempts.

Here is an example:

```<code>>>> df2 = pd.DataFrame([{"uid": 0, "mi":1}, {"uid": 0, "mi":2}, {"uid": 0, "mi":1}, {"uid": 0, "mi":1}])
>>> df2

    mi  uid
0    1   0
1    2   0
2    1   0
3    1   0
</code>```

Now supposed I want to get all values from column "mi" that appear more than 2 times, the result should be

```<code>>>> <fancy query>
array([1])
</code>```

I have tried a couple of things with groupby and count but I always end up with a series with the values and their respective counts but don't know how to extract the values that have count more than X from that:

```<code>>>> df2.groupby('mi').mi.count() > 2
mi
1      True
2     False
dtype: bool
</code>```

But how can I use this now to get the values of mi that are true?

Any hints appreciated :)

答:
```<code>from collections import Counter

counts = Counter(df2.mi)
df2[df2.mi.isin([key for key in counts if counts[key] > 2])]
</code>```

Body:
I have a data frame in pandas and would like to get all the values of a certain column that appear more than X times. I know this should be easy but somehow I am not getting anywhere with my current attempts.

Here is an example:

>>> df2 = pd.DataFrame([{"uid": 0, "mi":1}, {"uid": 0, "mi":2}, {"uid": 0, "mi":1}, {"uid": 0, "mi":1}])
>>> df2

    mi  uid
0    1   0
1    2   0
2    1   0
3    1   0

Now supposed I want to get all values from column "mi" that appear more than 2 times, the result should be

>>> <fancy query>
array([1])

I have tried a couple of things with groupby and count but I always end up with a series with the values and their respective counts but don't know how to extract the values that have count more than X from that:

>>> df2.groupby('mi').mi.count() > 2
mi
1      True
2     False
dtype: bool

But how can I use this now to get the values of mi that are true?

Any hints appreciated :)


问:
jquery html($("").attr("src", this.href)); not working in Safari
I'm  using a simple jquery function for an image gallery. There is a div of thumbnails, then the target div where the large images are loaded into after one clicks on a thumbnail.

It's working fine in all browsers, with the exception of Safari, where the image's absolute url is loaded, opposed to being loaded inside of the div.

Here's the jquery code:

```<code>$("#thumbnails a").click(function() {
    $("#work").html($("<img>").attr("src", this.href));

    return false;
});
</code>```

Any thoughts? Thanks

答:
I its getting confused off the this.href because while your in the attribute $("#work").

try this:

```<code>$("#thumbnails a").click(function() {
    var urlHref = $(this).attr('href');
    $("#work").html($("<img>").attr("src", urlHref));
    return false;
});
</code>```

Title: jquery html($("<img>").attr("src", this.href)); not working in Safari

Body:
I'm  using a simple jquery function for an image gallery. There is a div of thumbnails, then the target div where the large images are loaded into after one clicks on a thumbnail.

It's working fine in all browsers, with the exception of Safari, where the image's absolute url is loaded, opposed to being loaded inside of the div.

Here's the jquery code:

$("#thumbnails a").click(function() {
    $("#work").html($("").attr("src", this.href));

    return false;
});

Any thoughts? Thanks

Body:
I its getting confused off the this.href because while your in the attribute $("#work").

try this:

$("#thumbnails a").click(function() {
    var urlHref = $(this).attr('href');
    $("#work").html($("<img>").attr("src", urlHref));
    return false;
});